From dcdf8377535ee144a5c95e280db71a20806616fa Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:25:18 -0500 Subject: [PATCH 01/28] 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 02/28] 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 b94692d4c0b87b9bca15ee4159a1d8af8737c0ba Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:25:52 -0500 Subject: [PATCH 03/28] audio: codecs/Mdct (FFT, DCT-IV, MDCT/IMDCT, windows) + test; codecs/Pcm (Audio|Decoder pull source for encoders, int<->float); tools/fixtures/_audio.py (signals, ffmpeg decode, SNR, run Luau in the fixture step) --- docs/FORMATS.md | 2 + src/Formats/codecs/Mdct/init.luau | 288 ++++++++++++++++++++++++++++++ src/Formats/codecs/Pcm.luau | 151 ++++++++++++++++ tests/codecs/mdct.luau | 131 ++++++++++++++ tools/fixtures/_audio.py | 194 ++++++++++++++++++++ 5 files changed, 766 insertions(+) create mode 100644 src/Formats/codecs/Mdct/init.luau create mode 100644 src/Formats/codecs/Pcm.luau create mode 100644 tests/codecs/mdct.luau create mode 100644 tools/fixtures/_audio.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..ad373e2 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,3 +10,5 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Mdct: the shared audio transforms: radix-2 complex FFT, DCT-IV and MDCT / IMDCT (power-of-two sizes). +- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples. diff --git a/src/Formats/codecs/Mdct/init.luau b/src/Formats/codecs/Mdct/init.luau new file mode 100644 index 0000000..4393107 --- /dev/null +++ b/src/Formats/codecs/Mdct/init.luau @@ -0,0 +1,288 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Mdct: the shared audio transforms: radix-2 complex FFT, DCT-IV and MDCT / IMDCT (power-of-two sizes). +-- The MDCT (any power of two N >= 16) runs as a DCT-IV on an N/4-point complex FFT (pre-twiddle, FFT, post-twiddle). +-- Used by the Vorbis decoder and encoder, and open to AAC / Opus (CELT). New code (the textbook algorithm; no port). +-- +-- local Mdct = require("@formats/codecs/Mdct") +-- local m = Mdct.new(2048) -- N = 2048: 2048 time samples <-> 1024 coefficients (cached per N) +-- m:forward(x, xo, X, Xo, scale?) -- X[Xo+1 .. Xo+N/2] = scale * sum_n x[xo+1+n] cos(pi/M (n + 1/2 + M/2)(k + 1/2)) +-- m:inverse(X, Xo, y, yo) -- y[yo+1 .. yo+N] = sum_k X[Xo+1+k] cos(pi/M (n + 1/2 + M/2)(k + 1/2)) +-- local f = Mdct.fft(256) -- complex FFT plan (cached per n) +-- f:forward(re, im) -- in place, 1-based arrays of n numbers: X[k] = sum x[j] e^(-2 pi i jk/n) +-- f:inverse(re, im) -- in place, unscaled (e^(+2 pi i jk/n)) +-- Mdct.dct4(u, uo, X, Xo, M, scale?) -- DCT-IV, M a power of two >= 4: X[k] = sum u[n] cos(pi/M (n+1/2)(k+1/2)) +-- +-- M = N/2. Both MDCT directions are unscaled (the Vorbis convention): windowing with a Princen-Bradley window (sine, +-- Vorbis) before forward and after inverse, then overlap-adding, gives x * N/4, so an encoder for an unscaled decoder +-- passes scale = 4/N (as libvorbis does; tests/codecs/mdct.luau checks this). Arrays are plain 1-based Luau arrays +-- with explicit 0-based offsets; work arrays live in the plan (calls never yield, so sharing a plan is safe). +-- Never throws: a bad size returns nil. +local Mdct = {} + +local cos, sin, pi = math.cos, math.sin, math.pi + +-- ------------------------------------------------------------------------------------------------ FFT +export type Fft = { + n: number, + rev: { number }, -- bit reversal permutation (1-based targets) + cr: { number }, -- twiddles cos(2 pi k / n), k = 0 .. n/2 - 1 + ci: { number }, -- sin(2 pi k / n) + forward: (self: Fft, re: { number }, im: { number }) -> (), + inverse: (self: Fft, re: { number }, im: { number }) -> (), +} + +local function isPow2(n: number): boolean + if n < 1 or n ~= math.floor(n) then + return false + end + while n > 1 do + if n % 2 ~= 0 then + return false + end + n //= 2 + end + return true +end + +-- the radix-2 decimation-in-time butterflies; sign = -1 forward, +1 inverse +local function transform(p: Fft, re: { number }, im: { number }, sign: number) + local n = p.n + local rev, cr, ci = p.rev, p.cr, p.ci + for i = 1, n do + local j = rev[i] + if j > i then + re[i], re[j] = re[j], re[i] + im[i], im[j] = im[j], im[i] + end + end + -- size-2 butterflies first (twiddle 1) + for i = 1, n - 1, 2 do + local ar, ai, br, bi = re[i], im[i], re[i + 1], im[i + 1] + re[i], im[i] = ar + br, ai + bi + re[i + 1], im[i + 1] = ar - br, ai - bi + end + local half = 2 + while half < n do + local size = half * 2 + local step = n // size + for start = 1, n, size do + local t = 1 + for k = start, start + half - 1 do + local wr, wi = cr[t], sign * ci[t] + local m = k + half + local xr, xi = re[m], im[m] + -- (xr + i xi) * (wr + i wi) + local tr = xr * wr - xi * wi + local ti = xr * wi + xi * wr + local ar, ai = re[k], im[k] + re[k], im[k] = ar + tr, ai + ti + re[m], im[m] = ar - tr, ai - ti + t += step + end + end + half = size + end +end + +local function fftForward(self: Fft, re: { number }, im: { number }) + transform(self, re, im, -1) +end +local function fftInverse(self: Fft, re: { number }, im: { number }) + transform(self, re, im, 1) +end + +local fftCache: { [number]: Fft } = {} + +-- fft(n) -> Fft plan for a power-of-two n >= 2 | nil +function Mdct.fft(n: number): Fft? + local c = fftCache[n] + if c then + return c + end + if not isPow2(n) or n < 2 or n > 2 ^ 20 then + return nil + end + local bits = 0 + while 2 ^ bits < n do + bits += 1 + end + local rev = table.create(n, 0) + for i = 0, n - 1 do + local r, v = 0, i + for _ = 1, bits do + r = r * 2 + v % 2 + v //= 2 + end + rev[i + 1] = r + 1 + end + local cr, ci = table.create(n // 2, 0), table.create(n // 2, 0) + for k = 0, n // 2 - 1 do + cr[k + 1] = cos(2 * pi * k / n) + ci[k + 1] = sin(2 * pi * k / n) + end + local p: Fft = { n = n, rev = rev, cr = cr, ci = ci, forward = fftForward, inverse = fftInverse } + fftCache[n] = p + return p +end + +-- ------------------------------------------------------------------------------------------------ DCT-IV +type Dct4 = { + m: number, + fft: Fft, + pr: { number }, -- pre-twiddle exp(-i pi (n + 1/4) / M), n = 0 .. M/2 - 1 + pi_: { number }, + qr: { number }, -- post-twiddle exp(-i pi k / M) + qi: { number }, + re: { number }, -- work + im: { number }, +} +local dctCache: { [number]: Dct4 } = {} + +local function dctPlan(m: number): Dct4? + local c = dctCache[m] + if c then + return c + end + if not isPow2(m) or m < 4 then + return nil + end + local h = m // 2 + local f = Mdct.fft(h) + if not f then + return nil + end + local pr, pim, qr, qi = table.create(h, 0), table.create(h, 0), table.create(h, 0), table.create(h, 0) + for n = 0, h - 1 do + local a = -pi * (n + 0.25) / m + pr[n + 1], pim[n + 1] = cos(a), sin(a) + local b = -pi * n / m + qr[n + 1], qi[n + 1] = cos(b), sin(b) + end + local p: Dct4 = { m = m, fft = f, pr = pr, pi_ = pim, qr = qr, qi = qi, re = table.create(h, 0), im = table.create(h, 0) } + dctCache[m] = p + return p +end + +-- X[Xo+1+k] = scale * sum_n u[uo+1+n] cos(pi/M (n+1/2)(k+1/2)); u and X may be the same array only at distinct ranges +local function dct4(p: Dct4, u: { number }, uo: number, X: { number }, Xo: number, scale: number) + local m = p.m + local h = m // 2 + local re, im, pr, pim, qr, qi = p.re, p.im, p.pr, p.pi_, p.qr, p.qi + for n = 0, h - 1 do + local a, b = u[uo + 2 * n + 1], u[uo + m - 2 * n] + local wr, wi = pr[n + 1], pim[n + 1] + re[n + 1] = a * wr - b * wi + im[n + 1] = a * wi + b * wr + end + p.fft:forward(re, im) + for k = 0, h - 1 do + local vr, vi = re[k + 1], im[k + 1] + local wr, wi = qr[k + 1], qi[k + 1] + X[Xo + 2 * k + 1] = (vr * wr - vi * wi) * scale + X[Xo + m - 2 * k] = -(vr * wi + vi * wr) * scale + end +end + +-- dct4(u, uo, X, Xo, M, scale?): a DCT-IV of length M (power of two >= 4). Returns false for a bad M. +function Mdct.dct4(u: { number }, uo: number, X: { number }, Xo: number, m: number, scale: number?): boolean + local p = dctPlan(m) + if not p then + return false + end + dct4(p, u, uo, X, Xo, scale or 1) + return true +end + +-- ------------------------------------------------------------------------------------------------ MDCT +export type Plan = { + n: number, + forward: (self: Plan, x: { number }, xo: number, X: { number }, Xo: number, scale: number?) -> (), + inverse: (self: Plan, X: { number }, Xo: number, y: { number }, yo: number) -> (), + dct: Dct4, + fold: { number }, -- work, M +} + +-- forward: fold N inputs into M (the transpose of the inverse unfolding below), then the DCT-IV +local function forward(self: Plan, x: { number }, xo: number, X: { number }, Xo: number, scale: number?) + local n = self.n + local m = n // 2 + local q = m // 2 + local f = self.fold + -- m' = n' + M/2 for input index n' + -- n' < M/2 : f[n' + M/2] += x + -- M/2 <= n' < 3M/2 : f[3M/2 - 1 - n'] -= x + -- n' >= 3M/2 : f[n' - 3M/2] -= x + for i = 0, q - 1 do + -- f[i] (i < M/2) gets -x[3M/2 + i] (third range) and -x[3M/2 - 1 - i] (second range) + f[i + 1] = -x[xo + 3 * q + i + 1] - x[xo + 3 * q - i] + end + for i = q, m - 1 do + -- f[i] (i >= M/2) gets x[i - M/2] (first range) and -x[3M/2 - 1 - i] (second range) + f[i + 1] = x[xo + i - q + 1] - x[xo + 3 * q - i] + end + dct4(self.dct, f, 0, X, Xo, scale or 1) +end + +local function inverse(self: Plan, X: { number }, Xo: number, y: { number }, yo: number) + local n = self.n + local m = n // 2 + local q = m // 2 + local u = self.fold + dct4(self.dct, X, Xo, u, 0, 1) + -- y[n'] with m' = n' + M/2: m' < M -> u[m']; M <= m' < 2M -> -u[2M-1-m']; m' >= 2M -> -u[m'-2M] + for i = 0, q * 3 - 1 do + local mm = i + q + if mm < m then + y[yo + i + 1] = u[mm + 1] + else + y[yo + i + 1] = -u[2 * m - mm] + end + end + for i = q * 3, n - 1 do + y[yo + i + 1] = -u[i + q - 2 * m + 1] + end +end + +local mdctCache: { [number]: Plan } = {} + +-- new(N) -> Plan for an MDCT of N time samples (N/2 coefficients); N a power of two >= 16 | nil +function Mdct.new(n: number): Plan? + local c = mdctCache[n] + if c then + return c + end + if not isPow2(n) or n < 16 or n > 2 ^ 18 then + return nil + end + local d = dctPlan(n // 2) + if not d then + return nil + end + local p: Plan = { n = n, forward = forward, inverse = inverse, dct = d, fold = table.create(n // 2, 0) } + mdctCache[n] = p + return p +end + +-- ------------------------------------------------------------------------------------------------ windows +-- the Vorbis power-complementary window rising over n samples: sin(pi/2 sin^2(pi (i + 1/2) / (2n))), i = 0 .. n-1 +function Mdct.vorbisWindow(n: number): { number } + local w = table.create(n, 0) + for i = 0, n - 1 do + local s = sin((i + 0.5) / n * pi / 2) + w[i + 1] = sin(pi / 2 * s * s) + end + return w +end + +-- the sine window over the whole block of n samples: sin(pi (i + 1/2) / n) +function Mdct.sineWindow(n: number): { number } + local w = table.create(n, 0) + for i = 0, n - 1 do + w[i + 1] = sin(pi * (i + 0.5) / n) + end + return w +end + +return Mdct diff --git a/src/Formats/codecs/Pcm.luau b/src/Formats/codecs/Pcm.luau new file mode 100644 index 0000000..077f6dc --- /dev/null +++ b/src/Formats/codecs/Pcm.luau @@ -0,0 +1,151 @@ +--!strict +-- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples. +-- An encoder accepts a Types.Audio (fully decoded) or a +-- Types.Decoder (streamed); Pcm.source turns either into one pull interface, so encoders stream in blocks without +-- caring which they got. Also the float <-> integer sample conversions (the same rounding and clipping everywhere). +-- +-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else +-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read +-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] +-- local x = Pcm.fromInt(s16, 16) -- s / 32768 +-- local audio = Pcm.collect(src) -- read everything into a Types.Audio +-- +-- Never throws (a decoder's read that throws is caught and ends the stream). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") + +local Pcm = {} + +export type Source = { + sampleRate: number, + channels: number, + frames: number, -- total frames, 0 = unknown (a streaming decoder without an index) + tags: Types.Tags, + -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end) + read: (self: Source, n: number, out: buffer?) -> (buffer, number), + err: Err.Err?, -- set when the underlying decoder failed mid-stream +} + +local function audioRead(self: any, n: number, out: buffer?): (buffer, number) + local a = self._audio + local ch = a.channels + local left = a.frames - self._pos + if n > left then + n = left + end + if n <= 0 then + return out or buffer.create(0), 0 + end + local bytes = n * ch * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) + self._pos += n + return b, n +end + +local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) + if self._done then + return out or buffer.create(0), 0 + end + local ok, b, got = pcall(self._dec.read, self._dec, n, out) + if not ok then + self._done = true + self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b)) + return out or buffer.create(0), 0 + end + if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then + self._done = true + return out or buffer.create(0), 0 + end + local ch = self.channels + if buffer.len(b) < got * ch * 4 then + got = buffer.len(b) // (ch * 4) + end + return b, got +end + +-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read) +function Pcm.source(v: any): (Source?, Err.Err?) + if type(v) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") + end + local sr, ch = v.sampleRate, v.channels + if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + if v.kind == "audio" and type(v.samples) == "buffer" then + local frames = v.frames + if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4") + end + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil + end + if type(v.read) == "function" then + local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0 + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil + end + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") +end + +-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames) +function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) + local ch = src.channels + local cap = math.max(src.frames, 4096) + local data = buffer.create(cap * ch * 4) + local total = 0 + local limit = maxFrames or 2 ^ 31 + local tmp: buffer? = nil + while true do + local b, n = src:read(16384, tmp) + if n <= 0 then + break + end + tmp = b + if total + n > limit then + return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit)) + end + if total + n > cap then + cap = math.max(cap * 2, total + n) + local nd = buffer.create(cap * ch * 4) + buffer.copy(nd, 0, data, 0, total * ch * 4) + data = nd + end + buffer.copy(data, total * ch * 4, b, 0, n * ch * 4) + total += n + end + if src.err then + return nil, src.err + end + local a = Types.Audio.new(src.sampleRate, ch, 0) + a.frames = total + if buffer.len(data) == total * ch * 4 then + a.samples = data + else + a.samples = buffer.create(total * ch * 4) + buffer.copy(a.samples, 0, data, 0, total * ch * 4) + end + a.tags = table.clone(src.tags) + return a, nil +end + +-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) +function Pcm.toInt(x: number, bits: number): number + local s = 2 ^ (bits - 1) + local v = math.floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- fromInt(v, bits) -> v / 2^(bits-1) +function Pcm.fromInt(v: number, bits: number): number + return v / 2 ^ (bits - 1) +end + +return Pcm diff --git a/tests/codecs/mdct.luau b/tests/codecs/mdct.luau new file mode 100644 index 0000000..0f5fdcb --- /dev/null +++ b/tests/codecs/mdct.luau @@ -0,0 +1,131 @@ +-- codecs/Mdct tests: the FFT against a direct DFT, the DCT-IV against its definition, the MDCT / IMDCT against their +-- O(N^2) definitions at offsets, perfect reconstruction (TDAC) with the sine and Vorbis windows at scale 4/N, and bad +-- sizes. No fixtures (the definitions are the reference). +local T = require("@tests/T") +local Mdct = require("@formats/codecs/Mdct") + +local t = T.suite("mdct") +local rand = T.rng(7) +local function rnd(): number + return rand(20001) / 10000 - 1 +end +local cos, sin, pi = math.cos, math.sin, math.pi + +-- FFT vs DFT +for _, n in { 2, 4, 8, 64, 256 } do + local f = Mdct.fft(n) :: Mdct.Fft + local re, im, r0, i0 = {}, {}, {}, {} + for i = 1, n do + re[i], im[i] = rnd(), rnd() + r0[i], i0[i] = re[i], im[i] + end + f:forward(re, im) + local worst = 0 + for k = 0, n - 1 do + local sr, si = 0, 0 + for j = 0, n - 1 do + local a = -2 * pi * j * k / n + sr += r0[j + 1] * cos(a) - i0[j + 1] * sin(a) + si += r0[j + 1] * sin(a) + i0[j + 1] * cos(a) + end + worst = math.max(worst, math.abs(sr - re[k + 1]), math.abs(si - im[k + 1])) + end + t:check(worst < 1e-9, "fft " .. n .. ": error " .. worst) + f:inverse(re, im) + local back = 0 + for i = 1, n do + back = math.max(back, math.abs(re[i] / n - r0[i]), math.abs(im[i] / n - i0[i])) + end + t:check(back < 1e-12, "fft " .. n .. ": inverse") +end + +-- DCT-IV +for _, m in { 4, 8, 32, 128 } do + local u, X = {}, {} + for i = 1, m do + u[i] = rnd() + end + t:check(Mdct.dct4(u, 0, X, 0, m), "dct4 plan " .. m) + local worst = 0 + for k = 0, m - 1 do + local s = 0 + for n = 0, m - 1 do + s += u[n + 1] * cos(pi / m * (n + 0.5) * (k + 0.5)) + end + worst = math.max(worst, math.abs(s - X[k + 1])) + end + t:check(worst < 1e-9, "dct4 " .. m .. ": error " .. worst) +end + +-- MDCT / IMDCT vs the definitions, with offsets +for _, n in { 16, 32, 64, 256, 512 } do + local p = Mdct.new(n) :: Mdct.Plan + local m = n // 2 + local x = {} + for i = 1, n + 3 do + x[i] = rnd() + end + local X = table.create(m + 5, 0) + p:forward(x, 3, X, 5) + local worst = 0 + for k = 0, m - 1 do + local s = 0 + for i = 0, n - 1 do + s += x[3 + i + 1] * cos(pi / m * (i + 0.5 + m / 2) * (k + 0.5)) + end + worst = math.max(worst, math.abs(s - X[5 + k + 1])) + end + t:check(worst < 1e-8, "mdct " .. n .. ": error " .. worst) + local y = table.create(n + 2, 0) + p:inverse(X, 5, y, 2) + worst = 0 + for i = 0, n - 1 do + local s = 0 + for k = 0, m - 1 do + s += X[5 + k + 1] * cos(pi / m * (i + 0.5 + m / 2) * (k + 0.5)) + end + worst = math.max(worst, math.abs(s - y[2 + i + 1])) + end + t:check(worst < 1e-8, "imdct " .. n .. ": error " .. worst) +end + +-- TDAC: window, forward (scale 4/N), inverse, window, overlap-add reconstructs the middle blocks +for _, wname in { "sine", "vorbis" } do + local n = 256 + local m = n // 2 + local p = Mdct.new(n) :: Mdct.Plan + local w = if wname == "sine" then Mdct.sineWindow(n) else Mdct.vorbisWindow(m) + local function win(i: number): number -- i = 0 .. n-1 + if wname == "sine" then + return w[i + 1] + end + return if i < m then w[i + 1] else w[n - i] + end + local len = m * 6 + local sig = {} + for i = 1, len do + sig[i] = rnd() + end + local out = table.create(len, 0) + local blk, X, y = table.create(n, 0), table.create(m, 0), table.create(n, 0) + for start = 0, len - n, m do + for i = 0, n - 1 do + blk[i + 1] = sig[start + i + 1] * win(i) + end + p:forward(blk, 0, X, 0, 4 / n) + p:inverse(X, 0, y, 0) + for i = 0, n - 1 do + out[start + i + 1] += y[i + 1] * win(i) + end + end + local worst = 0 + for i = m + 1, len - m do + worst = math.max(worst, math.abs(out[i] - sig[i])) + end + t:check(worst < 1e-9, wname .. " window TDAC: error " .. worst) +end + +t:check(Mdct.new(100) == nil and Mdct.new(8) == nil and Mdct.fft(3) == nil and Mdct.new(0.5) == nil, "bad sizes") +t:check(Mdct.new(64) == Mdct.new(64), "plans are cached") +-- (Mdct is a codec without a decoder of untrusted bytes: there is nothing to fuzz.) +t:done() diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py new file mode 100644 index 0000000..cf0f16f --- /dev/null +++ b/tools/fixtures/_audio.py @@ -0,0 +1,194 @@ +# Shared helpers for the audio fixture generators (aiff, au, voc, vorbis, flac encoder, mp3 / mp2 encoders): +# A = _audio.load() in a generator: import this file (generators are loaded by path, not as a package) +# A.signal(kind, rate, ch, frames) deterministic test signals -> list of float frames-interleaved samples +# A.f32le(samples) / A.from_f32le(b) float list <-> raw little-endian f32 bytes +# A.wav(samples, rate, ch, bits=16) a WAV file (PCM 8/16/24/32 or float 32) for reference tools to read +# A.ffdecode(ctx, data, fmt=None) decode any file with ffmpeg -> (rate, ch, floats) +# A.tool(ctx, pkg, argv, data, ext) run a nix reference tool on a temp input file, return its stdout +# A.snr(ref, test, ch, max_lag=0) SNR in dB of test against ref (searching an alignment lag up to max_lag frames, +# either direction), and the lag found +# A.luau(ctx, code) run Luau code (luau --codegen -O2 from the repo root, the .luaurc aliases +# apply) and return its stdout bytes. Encoder fixtures use it to encode with our +# encoder in the fixture step, then decode the output with the reference tool: +# print(buffer.tostring(buf)) writes the raw bytes (plus one newline, stripped). +import array, math, os, random, shutil, struct, subprocess, sys, tempfile, importlib.util + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +def load(): + return sys.modules[__name__] + + +def signal(kind, rate, ch, frames, seed=1): + """kinds: sine (440 Hz + 1 kHz per channel), sweep (50 Hz .. rate/2.2 log sweep), noise (white, -12 dBFS), + music (a few harmonic notes with an envelope + a little noise), silence, square (aliased square, a stress test), + loud (a full-scale sine near clipping).""" + rng = random.Random(seed) + out = [0.0] * (frames * ch) + for c in range(ch): + ph = 0.0 + notes = [(220.0 * 2 ** (rng.randrange(0, 24) / 12.0), rng.random() * 0.25 + 0.05) for _ in range(4)] + for i in range(frames): + t = i / rate + if kind == "sine": + v = 0.5 * math.sin(2 * math.pi * (440 + 110 * c) * t) + 0.2 * math.sin(2 * math.pi * 1000 * t + c) + elif kind == "sweep": + f0, f1 = 50.0, rate / 2.2 + dur = frames / rate + f = f0 * (f1 / f0) ** (t / dur) + ph += 2 * math.pi * f / rate + v = 0.6 * math.sin(ph + c) + elif kind == "noise": + v = (rng.random() * 2 - 1) * 0.25 + elif kind == "music": + v = 0.0 + for k, (f, a) in enumerate(notes): + seg = (i // max(1, rate // 4) + k) % 4 + env = math.exp(-3.0 * ((i % max(1, rate // 4)) / rate)) + if seg != 3: + v += a * env * (math.sin(2 * math.pi * f * t) + 0.3 * math.sin(4 * math.pi * f * t) + 0.1 * math.sin(6 * math.pi * f * t)) + v += (rng.random() * 2 - 1) * 0.01 + elif kind == "silence": + v = 0.0 + elif kind == "square": + v = 0.4 if math.sin(2 * math.pi * (300 + 50 * c) * t) >= 0 else -0.4 + elif kind == "loud": + v = 0.98 * math.sin(2 * math.pi * 330 * t + c) + else: + raise ValueError(kind) + out[i * ch + c] = v + return out + + +def quantize(samples, bits): + s = 2 ** (bits - 1) + return [max(-s, min(s - 1, int(math.floor(v * s + 0.5)))) / s for v in samples] + + +def f32le(samples): + a = array.array("f", samples) + if sys.byteorder != "little": + a.byteswap() + return a.tobytes() + + +def from_f32le(b): + a = array.array("f") + a.frombytes(b[: len(b) // 4 * 4]) + if sys.byteorder != "little": + a.byteswap() + return a.tolist() + + +def wav(samples, rate, ch, bits=16, float_=False): + n = len(samples) // ch + if float_: + data = f32le(samples) + fmt = struct.pack(" 64: + # coarse cross-correlation on the first channel to find candidate lags, then refine + cands = [] + m = min(nref, 1 << 15) + seg = [ref[i * ch] for i in range(skip, min(nref, skip + m))] + for lag in range(-max_lag, max_lag + 1): + acc = 0.0 + for i in range(0, len(seg), 7): + j = skip + i + lag + if 0 <= j < ntest: + acc += seg[i] * test[j * ch] + cands.append((acc, lag)) + cands.sort(reverse=True) + lags = sorted(set(l for _, l in cands[:3])) + for lag in lags: + sig = err = 0.0 + for i in range(skip, nref): + j = i + lag + if j < 0 or j >= ntest: + continue + for c in range(ch): + a = ref[i * ch + c] + e = a - test[j * ch + c] + sig += a * a + err += e * e + s = 200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0) + if s > best[0]: + best = (s, lag) + return best + + +def luau_bin(): + p = shutil.which("luau") + if p: + return p + return subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "sh", "-c", "command -v luau"], capture_output=True, check=True, + text=True).stdout.strip() + + +def luau(ctx, code): + d = os.path.join(ROOT, "tests", "gen") + os.makedirs(d, exist_ok=True) + fd, path = tempfile.mkstemp(prefix="_run_", suffix=".luau", dir=d) + try: + with os.fdopen(fd, "w") as f: + f.write(code) + r = subprocess.run([luau_bin(), "--codegen", "-O2", path], cwd=ROOT, capture_output=True) + if r.returncode != 0: + raise RuntimeError("luau failed:\n" + r.stderr.decode(errors="replace") + r.stdout.decode(errors="replace")[-2000:]) + out = r.stdout + return out[:-1] if out.endswith(b"\n") else out + finally: + os.unlink(path) From aea16eeec7fcf268f7ac843eb73fa2399e99936e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:26:10 -0500 Subject: [PATCH 04/28] audio: drop our codecs/Mdct: ws-m4a landed theirs first (960107b), merging it instead --- docs/FORMATS.md | 1 - src/Formats/codecs/Mdct/init.luau | 288 ------------------------------ tests/codecs/mdct.luau | 131 -------------- 3 files changed, 420 deletions(-) delete mode 100644 src/Formats/codecs/Mdct/init.luau delete mode 100644 tests/codecs/mdct.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index ad373e2..e60ff70 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,5 +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 shared audio transforms: radix-2 complex FFT, DCT-IV and MDCT / IMDCT (power-of-two sizes). - codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples. diff --git a/src/Formats/codecs/Mdct/init.luau b/src/Formats/codecs/Mdct/init.luau deleted file mode 100644 index 4393107..0000000 --- a/src/Formats/codecs/Mdct/init.luau +++ /dev/null @@ -1,288 +0,0 @@ ---!strict ---!native ---!optimize 2 --- codecs/Mdct: the shared audio transforms: radix-2 complex FFT, DCT-IV and MDCT / IMDCT (power-of-two sizes). --- The MDCT (any power of two N >= 16) runs as a DCT-IV on an N/4-point complex FFT (pre-twiddle, FFT, post-twiddle). --- Used by the Vorbis decoder and encoder, and open to AAC / Opus (CELT). New code (the textbook algorithm; no port). --- --- local Mdct = require("@formats/codecs/Mdct") --- local m = Mdct.new(2048) -- N = 2048: 2048 time samples <-> 1024 coefficients (cached per N) --- m:forward(x, xo, X, Xo, scale?) -- X[Xo+1 .. Xo+N/2] = scale * sum_n x[xo+1+n] cos(pi/M (n + 1/2 + M/2)(k + 1/2)) --- m:inverse(X, Xo, y, yo) -- y[yo+1 .. yo+N] = sum_k X[Xo+1+k] cos(pi/M (n + 1/2 + M/2)(k + 1/2)) --- local f = Mdct.fft(256) -- complex FFT plan (cached per n) --- f:forward(re, im) -- in place, 1-based arrays of n numbers: X[k] = sum x[j] e^(-2 pi i jk/n) --- f:inverse(re, im) -- in place, unscaled (e^(+2 pi i jk/n)) --- Mdct.dct4(u, uo, X, Xo, M, scale?) -- DCT-IV, M a power of two >= 4: X[k] = sum u[n] cos(pi/M (n+1/2)(k+1/2)) --- --- M = N/2. Both MDCT directions are unscaled (the Vorbis convention): windowing with a Princen-Bradley window (sine, --- Vorbis) before forward and after inverse, then overlap-adding, gives x * N/4, so an encoder for an unscaled decoder --- passes scale = 4/N (as libvorbis does; tests/codecs/mdct.luau checks this). Arrays are plain 1-based Luau arrays --- with explicit 0-based offsets; work arrays live in the plan (calls never yield, so sharing a plan is safe). --- Never throws: a bad size returns nil. -local Mdct = {} - -local cos, sin, pi = math.cos, math.sin, math.pi - --- ------------------------------------------------------------------------------------------------ FFT -export type Fft = { - n: number, - rev: { number }, -- bit reversal permutation (1-based targets) - cr: { number }, -- twiddles cos(2 pi k / n), k = 0 .. n/2 - 1 - ci: { number }, -- sin(2 pi k / n) - forward: (self: Fft, re: { number }, im: { number }) -> (), - inverse: (self: Fft, re: { number }, im: { number }) -> (), -} - -local function isPow2(n: number): boolean - if n < 1 or n ~= math.floor(n) then - return false - end - while n > 1 do - if n % 2 ~= 0 then - return false - end - n //= 2 - end - return true -end - --- the radix-2 decimation-in-time butterflies; sign = -1 forward, +1 inverse -local function transform(p: Fft, re: { number }, im: { number }, sign: number) - local n = p.n - local rev, cr, ci = p.rev, p.cr, p.ci - for i = 1, n do - local j = rev[i] - if j > i then - re[i], re[j] = re[j], re[i] - im[i], im[j] = im[j], im[i] - end - end - -- size-2 butterflies first (twiddle 1) - for i = 1, n - 1, 2 do - local ar, ai, br, bi = re[i], im[i], re[i + 1], im[i + 1] - re[i], im[i] = ar + br, ai + bi - re[i + 1], im[i + 1] = ar - br, ai - bi - end - local half = 2 - while half < n do - local size = half * 2 - local step = n // size - for start = 1, n, size do - local t = 1 - for k = start, start + half - 1 do - local wr, wi = cr[t], sign * ci[t] - local m = k + half - local xr, xi = re[m], im[m] - -- (xr + i xi) * (wr + i wi) - local tr = xr * wr - xi * wi - local ti = xr * wi + xi * wr - local ar, ai = re[k], im[k] - re[k], im[k] = ar + tr, ai + ti - re[m], im[m] = ar - tr, ai - ti - t += step - end - end - half = size - end -end - -local function fftForward(self: Fft, re: { number }, im: { number }) - transform(self, re, im, -1) -end -local function fftInverse(self: Fft, re: { number }, im: { number }) - transform(self, re, im, 1) -end - -local fftCache: { [number]: Fft } = {} - --- fft(n) -> Fft plan for a power-of-two n >= 2 | nil -function Mdct.fft(n: number): Fft? - local c = fftCache[n] - if c then - return c - end - if not isPow2(n) or n < 2 or n > 2 ^ 20 then - return nil - end - local bits = 0 - while 2 ^ bits < n do - bits += 1 - end - local rev = table.create(n, 0) - for i = 0, n - 1 do - local r, v = 0, i - for _ = 1, bits do - r = r * 2 + v % 2 - v //= 2 - end - rev[i + 1] = r + 1 - end - local cr, ci = table.create(n // 2, 0), table.create(n // 2, 0) - for k = 0, n // 2 - 1 do - cr[k + 1] = cos(2 * pi * k / n) - ci[k + 1] = sin(2 * pi * k / n) - end - local p: Fft = { n = n, rev = rev, cr = cr, ci = ci, forward = fftForward, inverse = fftInverse } - fftCache[n] = p - return p -end - --- ------------------------------------------------------------------------------------------------ DCT-IV -type Dct4 = { - m: number, - fft: Fft, - pr: { number }, -- pre-twiddle exp(-i pi (n + 1/4) / M), n = 0 .. M/2 - 1 - pi_: { number }, - qr: { number }, -- post-twiddle exp(-i pi k / M) - qi: { number }, - re: { number }, -- work - im: { number }, -} -local dctCache: { [number]: Dct4 } = {} - -local function dctPlan(m: number): Dct4? - local c = dctCache[m] - if c then - return c - end - if not isPow2(m) or m < 4 then - return nil - end - local h = m // 2 - local f = Mdct.fft(h) - if not f then - return nil - end - local pr, pim, qr, qi = table.create(h, 0), table.create(h, 0), table.create(h, 0), table.create(h, 0) - for n = 0, h - 1 do - local a = -pi * (n + 0.25) / m - pr[n + 1], pim[n + 1] = cos(a), sin(a) - local b = -pi * n / m - qr[n + 1], qi[n + 1] = cos(b), sin(b) - end - local p: Dct4 = { m = m, fft = f, pr = pr, pi_ = pim, qr = qr, qi = qi, re = table.create(h, 0), im = table.create(h, 0) } - dctCache[m] = p - return p -end - --- X[Xo+1+k] = scale * sum_n u[uo+1+n] cos(pi/M (n+1/2)(k+1/2)); u and X may be the same array only at distinct ranges -local function dct4(p: Dct4, u: { number }, uo: number, X: { number }, Xo: number, scale: number) - local m = p.m - local h = m // 2 - local re, im, pr, pim, qr, qi = p.re, p.im, p.pr, p.pi_, p.qr, p.qi - for n = 0, h - 1 do - local a, b = u[uo + 2 * n + 1], u[uo + m - 2 * n] - local wr, wi = pr[n + 1], pim[n + 1] - re[n + 1] = a * wr - b * wi - im[n + 1] = a * wi + b * wr - end - p.fft:forward(re, im) - for k = 0, h - 1 do - local vr, vi = re[k + 1], im[k + 1] - local wr, wi = qr[k + 1], qi[k + 1] - X[Xo + 2 * k + 1] = (vr * wr - vi * wi) * scale - X[Xo + m - 2 * k] = -(vr * wi + vi * wr) * scale - end -end - --- dct4(u, uo, X, Xo, M, scale?): a DCT-IV of length M (power of two >= 4). Returns false for a bad M. -function Mdct.dct4(u: { number }, uo: number, X: { number }, Xo: number, m: number, scale: number?): boolean - local p = dctPlan(m) - if not p then - return false - end - dct4(p, u, uo, X, Xo, scale or 1) - return true -end - --- ------------------------------------------------------------------------------------------------ MDCT -export type Plan = { - n: number, - forward: (self: Plan, x: { number }, xo: number, X: { number }, Xo: number, scale: number?) -> (), - inverse: (self: Plan, X: { number }, Xo: number, y: { number }, yo: number) -> (), - dct: Dct4, - fold: { number }, -- work, M -} - --- forward: fold N inputs into M (the transpose of the inverse unfolding below), then the DCT-IV -local function forward(self: Plan, x: { number }, xo: number, X: { number }, Xo: number, scale: number?) - local n = self.n - local m = n // 2 - local q = m // 2 - local f = self.fold - -- m' = n' + M/2 for input index n' - -- n' < M/2 : f[n' + M/2] += x - -- M/2 <= n' < 3M/2 : f[3M/2 - 1 - n'] -= x - -- n' >= 3M/2 : f[n' - 3M/2] -= x - for i = 0, q - 1 do - -- f[i] (i < M/2) gets -x[3M/2 + i] (third range) and -x[3M/2 - 1 - i] (second range) - f[i + 1] = -x[xo + 3 * q + i + 1] - x[xo + 3 * q - i] - end - for i = q, m - 1 do - -- f[i] (i >= M/2) gets x[i - M/2] (first range) and -x[3M/2 - 1 - i] (second range) - f[i + 1] = x[xo + i - q + 1] - x[xo + 3 * q - i] - end - dct4(self.dct, f, 0, X, Xo, scale or 1) -end - -local function inverse(self: Plan, X: { number }, Xo: number, y: { number }, yo: number) - local n = self.n - local m = n // 2 - local q = m // 2 - local u = self.fold - dct4(self.dct, X, Xo, u, 0, 1) - -- y[n'] with m' = n' + M/2: m' < M -> u[m']; M <= m' < 2M -> -u[2M-1-m']; m' >= 2M -> -u[m'-2M] - for i = 0, q * 3 - 1 do - local mm = i + q - if mm < m then - y[yo + i + 1] = u[mm + 1] - else - y[yo + i + 1] = -u[2 * m - mm] - end - end - for i = q * 3, n - 1 do - y[yo + i + 1] = -u[i + q - 2 * m + 1] - end -end - -local mdctCache: { [number]: Plan } = {} - --- new(N) -> Plan for an MDCT of N time samples (N/2 coefficients); N a power of two >= 16 | nil -function Mdct.new(n: number): Plan? - local c = mdctCache[n] - if c then - return c - end - if not isPow2(n) or n < 16 or n > 2 ^ 18 then - return nil - end - local d = dctPlan(n // 2) - if not d then - return nil - end - local p: Plan = { n = n, forward = forward, inverse = inverse, dct = d, fold = table.create(n // 2, 0) } - mdctCache[n] = p - return p -end - --- ------------------------------------------------------------------------------------------------ windows --- the Vorbis power-complementary window rising over n samples: sin(pi/2 sin^2(pi (i + 1/2) / (2n))), i = 0 .. n-1 -function Mdct.vorbisWindow(n: number): { number } - local w = table.create(n, 0) - for i = 0, n - 1 do - local s = sin((i + 0.5) / n * pi / 2) - w[i + 1] = sin(pi / 2 * s * s) - end - return w -end - --- the sine window over the whole block of n samples: sin(pi (i + 1/2) / n) -function Mdct.sineWindow(n: number): { number } - local w = table.create(n, 0) - for i = 0, n - 1 do - w[i + 1] = sin(pi * (i + 0.5) / n) - end - return w -end - -return Mdct diff --git a/tests/codecs/mdct.luau b/tests/codecs/mdct.luau deleted file mode 100644 index 0f5fdcb..0000000 --- a/tests/codecs/mdct.luau +++ /dev/null @@ -1,131 +0,0 @@ --- codecs/Mdct tests: the FFT against a direct DFT, the DCT-IV against its definition, the MDCT / IMDCT against their --- O(N^2) definitions at offsets, perfect reconstruction (TDAC) with the sine and Vorbis windows at scale 4/N, and bad --- sizes. No fixtures (the definitions are the reference). -local T = require("@tests/T") -local Mdct = require("@formats/codecs/Mdct") - -local t = T.suite("mdct") -local rand = T.rng(7) -local function rnd(): number - return rand(20001) / 10000 - 1 -end -local cos, sin, pi = math.cos, math.sin, math.pi - --- FFT vs DFT -for _, n in { 2, 4, 8, 64, 256 } do - local f = Mdct.fft(n) :: Mdct.Fft - local re, im, r0, i0 = {}, {}, {}, {} - for i = 1, n do - re[i], im[i] = rnd(), rnd() - r0[i], i0[i] = re[i], im[i] - end - f:forward(re, im) - local worst = 0 - for k = 0, n - 1 do - local sr, si = 0, 0 - for j = 0, n - 1 do - local a = -2 * pi * j * k / n - sr += r0[j + 1] * cos(a) - i0[j + 1] * sin(a) - si += r0[j + 1] * sin(a) + i0[j + 1] * cos(a) - end - worst = math.max(worst, math.abs(sr - re[k + 1]), math.abs(si - im[k + 1])) - end - t:check(worst < 1e-9, "fft " .. n .. ": error " .. worst) - f:inverse(re, im) - local back = 0 - for i = 1, n do - back = math.max(back, math.abs(re[i] / n - r0[i]), math.abs(im[i] / n - i0[i])) - end - t:check(back < 1e-12, "fft " .. n .. ": inverse") -end - --- DCT-IV -for _, m in { 4, 8, 32, 128 } do - local u, X = {}, {} - for i = 1, m do - u[i] = rnd() - end - t:check(Mdct.dct4(u, 0, X, 0, m), "dct4 plan " .. m) - local worst = 0 - for k = 0, m - 1 do - local s = 0 - for n = 0, m - 1 do - s += u[n + 1] * cos(pi / m * (n + 0.5) * (k + 0.5)) - end - worst = math.max(worst, math.abs(s - X[k + 1])) - end - t:check(worst < 1e-9, "dct4 " .. m .. ": error " .. worst) -end - --- MDCT / IMDCT vs the definitions, with offsets -for _, n in { 16, 32, 64, 256, 512 } do - local p = Mdct.new(n) :: Mdct.Plan - local m = n // 2 - local x = {} - for i = 1, n + 3 do - x[i] = rnd() - end - local X = table.create(m + 5, 0) - p:forward(x, 3, X, 5) - local worst = 0 - for k = 0, m - 1 do - local s = 0 - for i = 0, n - 1 do - s += x[3 + i + 1] * cos(pi / m * (i + 0.5 + m / 2) * (k + 0.5)) - end - worst = math.max(worst, math.abs(s - X[5 + k + 1])) - end - t:check(worst < 1e-8, "mdct " .. n .. ": error " .. worst) - local y = table.create(n + 2, 0) - p:inverse(X, 5, y, 2) - worst = 0 - for i = 0, n - 1 do - local s = 0 - for k = 0, m - 1 do - s += X[5 + k + 1] * cos(pi / m * (i + 0.5 + m / 2) * (k + 0.5)) - end - worst = math.max(worst, math.abs(s - y[2 + i + 1])) - end - t:check(worst < 1e-8, "imdct " .. n .. ": error " .. worst) -end - --- TDAC: window, forward (scale 4/N), inverse, window, overlap-add reconstructs the middle blocks -for _, wname in { "sine", "vorbis" } do - local n = 256 - local m = n // 2 - local p = Mdct.new(n) :: Mdct.Plan - local w = if wname == "sine" then Mdct.sineWindow(n) else Mdct.vorbisWindow(m) - local function win(i: number): number -- i = 0 .. n-1 - if wname == "sine" then - return w[i + 1] - end - return if i < m then w[i + 1] else w[n - i] - end - local len = m * 6 - local sig = {} - for i = 1, len do - sig[i] = rnd() - end - local out = table.create(len, 0) - local blk, X, y = table.create(n, 0), table.create(m, 0), table.create(n, 0) - for start = 0, len - n, m do - for i = 0, n - 1 do - blk[i + 1] = sig[start + i + 1] * win(i) - end - p:forward(blk, 0, X, 0, 4 / n) - p:inverse(X, 0, y, 0) - for i = 0, n - 1 do - out[start + i + 1] += y[i + 1] * win(i) - end - end - local worst = 0 - for i = m + 1, len - m do - worst = math.max(worst, math.abs(out[i] - sig[i])) - end - t:check(worst < 1e-9, wname .. " window TDAC: error " .. worst) -end - -t:check(Mdct.new(100) == nil and Mdct.new(8) == nil and Mdct.fft(3) == nil and Mdct.new(0.5) == nil, "bad sizes") -t:check(Mdct.new(64) == Mdct.new(64), "plans are cached") --- (Mdct is a codec without a decoder of untrusted bytes: there is nothing to fuzz.) -t:done() From 08af33d82afa53782a24968f97564ab6249d1d61 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:37:25 -0500 Subject: [PATCH 05/28] ws-music: music/midi (SMF 0/1/2 read/write, tempo map, render), codecs/SoundFont (SF2 parser + TinySoundFont-port synth + fallback waveform set), midi tests vs mido Types.luau: Midi gets an optional render(self, opts) -> Decoder field (backward compatible; set by music/midi decode). --- licenses/TinySoundFont-LICENSE.txt | 22 + src/Formats/Registry.luau | 24 + src/Formats/Types.luau | 1 + src/Formats/codecs/SoundFont/Fallback.luau | 149 ++++ src/Formats/codecs/SoundFont/Parse.luau | 523 ++++++++++++++ src/Formats/codecs/SoundFont/Synth.luau | 797 +++++++++++++++++++++ src/Formats/codecs/SoundFont/init.luau | 69 ++ src/Formats/music/midi/Render.luau | 261 +++++++ src/Formats/music/midi/Smf.luau | 402 +++++++++++ src/Formats/music/midi/init.luau | 136 ++++ src/Formats/music/sf2/init.luau | 44 ++ tests/music/midi.luau | 272 +++++++ tools/fixtures/_midi_ref.py | 183 +++++ tools/fixtures/midi.py | 72 ++ 14 files changed, 2955 insertions(+) create mode 100644 licenses/TinySoundFont-LICENSE.txt create mode 100644 src/Formats/codecs/SoundFont/Fallback.luau create mode 100644 src/Formats/codecs/SoundFont/Parse.luau create mode 100644 src/Formats/codecs/SoundFont/Synth.luau create mode 100644 src/Formats/codecs/SoundFont/init.luau create mode 100644 src/Formats/music/midi/Render.luau create mode 100644 src/Formats/music/midi/Smf.luau create mode 100644 src/Formats/music/midi/init.luau create mode 100644 src/Formats/music/sf2/init.luau create mode 100644 tests/music/midi.luau create mode 100644 tools/fixtures/_midi_ref.py create mode 100644 tools/fixtures/midi.py diff --git a/licenses/TinySoundFont-LICENSE.txt b/licenses/TinySoundFont-LICENSE.txt new file mode 100644 index 0000000..bf4692a --- /dev/null +++ b/licenses/TinySoundFont-LICENSE.txt @@ -0,0 +1,22 @@ +TinySoundFont v0.9 (https://github.com/schellingb/TinySoundFont), tsf.h + +LICENSE (MIT) + +Copyright (C) 2017-2025 Bernhard Schelling +Based on SFZero, Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..0b33666 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,30 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "midi", + category = "music", + path = "music/midi", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, + load = function() + return require("@formats/music/midi") + end, + }, + { + name = "sf2", + category = "music", + path = "music/sf2", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, + load = function() + return require("@formats/music/sf2") + end, + }, } return list diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 9f37bd1..170314b 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -154,6 +154,7 @@ export type Midi = { division: number, -- ticks per quarter note (or SMPTE, negative) tracks: { { events: { MidiEvent }, name: string? } }, meta: { [string]: any }, + render: ((self: any, opts: any?) -> Decoder)?, -- set by music/midi decode: the SoundFont synth as an audio Decoder } local Midi = {} function Midi.new(division: number?): Midi diff --git a/src/Formats/codecs/SoundFont/Fallback.luau b/src/Formats/codecs/SoundFont/Fallback.luau new file mode 100644 index 0000000..ae8f8ca --- /dev/null +++ b/src/Formats/codecs/SoundFont/Fallback.luau @@ -0,0 +1,149 @@ +--!strict +-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont +-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a +-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass, +-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes, +-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with +-- an exclusive class, cymbals). Written for this library (no third-party code). +local Parse = require("@formats/codecs/SoundFont/Parse") + +local Fallback = {} + +local CYCLE = 256 +local NOISE = 32768 +local C4 = 261.6255653005986 + +local function hzToCents(hz: number): number + return 1200 * math.log(hz / 8.176, 2) +end + +local cached: any = nil + +-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it) +function Fallback.build(): any + if cached then + return cached + end + local waves = { "sine", "triangle", "square", "saw" } + local count = #waves * CYCLE + NOISE + local samples = buffer.create((count + 1) * 4) + local starts: { [string]: number } = {} + for w, name in waves do + local base = (w - 1) * CYCLE + starts[name] = base + for i = 0, CYCLE - 1 do + local ph = i / CYCLE + local v + if name == "sine" then + v = math.sin(2 * math.pi * ph) + elseif name == "triangle" then + v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4 + elseif name == "square" then + v = if ph < 0.5 then 0.6 else -0.6 + else + v = (1 - 2 * ph) * 0.7 + end + buffer.writef32(samples, (base + i) * 4, v) + end + end + local noiseStart = #waves * CYCLE + starts.noise = noiseStart + local seed = 12345 + for i = 0, NOISE - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7) + end + + local function region(wave: string, fields: { [string]: number }): { [string]: number } + local r = Parse.defaultRegion() + local s = starts[wave] + r.offset = s + r.loopMode = 1 + r.loopStart = s + if wave == "noise" then + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60 + else + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60 + end + r.aRelease = 0.08 + for k, v in fields do + r[k] = v + end + return r + end + + -- the 16 GM families: wave + envelope / filter / vibrato + local families: { { any } } = { + { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, + { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, + { "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } }, + { "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } }, + { "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } }, + { "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } }, + { "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } }, + { "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } }, + { "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } }, + { "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } }, + { "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } }, + { "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } }, + { "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } }, + { "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } }, + { "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } }, + { "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } }, + } + local presets = {} + for program = 0, 127 do + local f = families[program // 8 + 1] + table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) + end + + -- the drum kit (bank 128, every program): one region per key + local kit = {} + -- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0 + local function drum(lo: number, hi: number, wave: string, fields: { [string]: number }) + local r = region(wave, fields) + r.lokey, r.hikey = lo, hi + r.sampleRate *= 2 ^ ((fields.semis or 0) / 12) + r.semis = nil :: any + table.insert(kit, r) + end + local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } + local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number } + local c = table.clone(a) + for k, v in b do + c[k] = v + end + return c + end + drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) }) + drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 })) + drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) }) + drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) }) + drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) }) + drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) }) + for _, k in { 41, 43, 45, 47, 48, 50 } do + drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 })) + end + drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 }) + drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) }) + drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 }) + drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) }) + table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit }) + + cached = { + kind = "soundfont", + info = { name = "formats-luau fallback" }, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = {}, + instruments = {}, + meta = { source = { format = "fallback" } }, + } + return cached +end + +return Fallback diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/SoundFont/Parse.luau new file mode 100644 index 0000000..8e4f60a --- /dev/null +++ b/src/Formats/codecs/SoundFont/Parse.luau @@ -0,0 +1,523 @@ +--!strict +-- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24 +-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened +-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's +-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) +-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped +-- so the synth never reads outside the sample buffer. +-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01); +-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h). +-- Never throws: a bad file returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local Parse = {} + +-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level +export type Region = { [string]: number } + +export type Preset = { name: string, preset: number, bank: number, regions: { Region } } + +export type SoundFont = { + kind: "soundfont", + info: { [string]: string }, + samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end) + sampleCount: number, + presets: { Preset }, -- sorted by bank, then preset number + sampleHeaders: { { [string]: any } }, + instruments: { { name: string, zones: number } }, + meta: { [string]: any }, +} + +local GEN_INSTRUMENT, GEN_KEYRANGE, GEN_VELRANGE, GEN_SAMPLEID = 41, 43, 44, 53 + +-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address +-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) +local LIM12K5K = { 1, -12000, 5000 } +local LIM12K8K = { 1, -12000, 8000 } +local LIM1200 = { 1, -1200, 1200 } +local GEN: { [number]: { any } } = { + [0] = { "offset", "a" }, + [1] = { "stop", "a" }, + [2] = { "loopStart", "a" }, + [3] = { "loopEnd", "a" }, + [4] = { "offset", "a15" }, + [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, + [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, + [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, + [8] = { "filterFc", "i", { 1, 1500, 13500 } }, + [9] = { "filterQ", "i", { 1, 0, 960 } }, + [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, + [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, + [12] = { "stop", "a15" }, + [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, + [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, + [21] = { "delayModLFO", "f", LIM12K5K }, + [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, + [23] = { "delayVibLFO", "f", LIM12K5K }, + [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, + [25] = { "mDelay", "f", LIM12K5K }, + [26] = { "mAttack", "f", LIM12K8K }, + [27] = { "mHold", "f", LIM12K5K }, + [28] = { "mDecay", "f", LIM12K8K }, + [29] = { "mSustain", "f", { 1, 0, 1000 } }, + [30] = { "mRelease", "f", LIM12K8K }, + [31] = { "mKeyHold", "f", LIM1200 }, + [32] = { "mKeyDecay", "f", LIM1200 }, + [33] = { "aDelay", "f", LIM12K5K }, + [34] = { "aAttack", "f", LIM12K8K }, + [35] = { "aHold", "f", LIM12K5K }, + [36] = { "aDecay", "f", LIM12K8K }, + [37] = { "aSustain", "f", { 1, 0, 1440 } }, + [38] = { "aRelease", "f", LIM12K8K }, + [39] = { "aKeyHold", "f", LIM1200 }, + [40] = { "aKeyDecay", "f", LIM1200 }, + [43] = { "", "kr" }, + [44] = { "", "vr" }, + [45] = { "loopStart", "a15" }, + [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, + [50] = { "loopEnd", "a15" }, + [51] = { "transpose", "i" }, + [52] = { "tune", "i" }, + [54] = { "loopMode", "loop" }, + [56] = { "keytrack", "i" }, + [57] = { "group", "group" }, + [58] = { "keycenter", "key" }, +} +-- the merged fields: value generators once each (several ops share a field), then the four address fields +local MERGE: { { any } } = {} +do + local seen: { [string]: boolean } = {} + for op = 0, 58 do + local g = GEN[op] + if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then + seen[g[1]] = true + table.insert(MERGE, g) + end + end +end + +local FIELDS = { + "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", + "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", + "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", + "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", + "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", + "sampleIndex", +} + +-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +local function clear(relative: boolean): Region + local r: Region = {} + for _, f in FIELDS do + r[f] = 0 + end + r.hikey, r.hivel, r.keycenter = 127, 127, 60 + if relative then + return r + end + r.keytrack = 100 + r.keycenter = -1 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = -12000 + end + end + r.filterFc = 13500 + r.delayModLFO, r.delayVibLFO = -12000, -12000 + return r +end + +local function copy(r: Region): Region + local c: Region = {} + for k, v in r do + c[k] = v + end + return c +end + +-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from +function Parse.defaultRegion(): Region + local r = clear(false) + r.keycenter = 60 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = 0 + end + end + r.aSustain, r.mSustain = 1, 1 + r.delayModLFO, r.delayVibLFO = 0, 0 + return r +end + +-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 +local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number) + local g = GEN[op] + if not g then + return + end + local mode = g[2] + if mode == "f" or mode == "i" then + r[g[1]] = s + elseif mode == "a" then + r[g[1]] += s + elseif mode == "a15" then + r[g[1]] += s * 32768 + elseif mode == "kr" then + r.lokey, r.hikey = lo, hi + elseif mode == "vr" then + r.lovel, r.hivel = lo, hi + elseif mode == "loop" then + local m = w % 4 + r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0 + elseif mode == "group" then + r.group = w + elseif mode == "key" then + r.keycenter = s + end +end + +-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) +local function merge(z: Region, p: Region) + for _, g in MERGE do + local f = g[1] + local v = z[f] + p[f] + local lim = g[3] + if lim then + v *= lim[1] + v = math.clamp(v, lim[2], lim[3]) + end + z[f] = v + end +end + +local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end + +-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key +local function envToSecs(r: Region, p: string, sustainIsGain: boolean) + for _, s in { "Delay", "Attack", "Release" } do + local v = r[p .. s] + r[p .. s] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyHold"] == 0 then + local v = r[p .. "Hold"] + r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyDecay"] == 0 then + local v = r[p .. "Decay"] + r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v) + end + local sus = r[p .. "Sustain"] + if sus < 0 then + sus = 0 + elseif sustainIsGain then + sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0 + else + sus = 1 - sus / 1000 + end + r[p .. "Sustain"] = sus +end + +-- ------------------------------------------------------------------------------------------------ RIFF +type Hydra = { [string]: { { number } } } + +-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) +local LAYOUT: { [string]: { number } } = { + phdr = { 20, 2, 2, 2, 4, 4, 4 }, + pbag = { 2, 2 }, + pmod = { 2, 2, -2, 2, 2 }, + pgen = { 2, 2 }, + inst = { 20, 2 }, + ibag = { 2, 2 }, + imod = { 2, 2, -2, 2, 2 }, + igen = { 2, 2 }, + shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, +} +local RECSIZE = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } + +local INFO_NAMES = { + isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", + ICOP = "copyright", ICMT = "comment", ISFT = "software", +} + +export type Options = { maxRegions: number?, maxSamples: number? } + +-- parse(r, opts?) -> SoundFont | nil, Err +function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) + local maxRegions = opts and opts.maxRegions or 1000000 + local maxSamples = opts and opts.maxSamples or 2 ^ 28 + if r:string(4) ~= "RIFF" then + return r:fail(Err.CORRUPT, "not a RIFF file") + end + local riffSize = r:u32le() + if r:string(4) ~= "sfbk" then + return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") + end + if r.err then + return nil, r.err + end + local body = r:sub(12, math.max(0, riffSize - 4)) + local info: { [string]: string } = {} + local hydra: Hydra = {} + local smpl: Bytes.Reader? = nil + local sm24: Bytes.Reader? = nil + local version = "" + while body:remaining() >= 8 do + local id, size = body:string(4), body:u32le() + local chunk = body:slice(size) + if size % 2 == 1 and body:remaining() > 0 then + body:skip(1) + end + if id == "LIST" and chunk:remaining() >= 4 then + local kind = chunk:string(4) + while chunk:remaining() >= 8 do + local sid, ssize = chunk:string(4), chunk:u32le() + local sub = chunk:slice(ssize) + if ssize % 2 == 1 and chunk:remaining() > 0 then + chunk:skip(1) + end + if kind == "INFO" then + if sid == "ifil" and sub:remaining() >= 4 then + local major, minor = sub:u16le(), sub:u16le() + version = string.format("%d.%02d", major, minor) + elseif INFO_NAMES[sid] then + info[INFO_NAMES[sid]] = sub:fixed(sub:remaining()) + end + elseif kind == "sdta" then + if sid == "smpl" and not smpl then + smpl = sub + elseif sid == "sm24" then + sm24 = sub + end + elseif kind == "pdta" then + local layout = LAYOUT[sid] + if layout and not hydra[sid] then + local rs = RECSIZE[sid] + local n = sub:remaining() // rs + local recs = table.create(n) + for i = 1, n do + local rec = {} + for _, w in layout do + if w == 20 then + table.insert(rec, 0) -- the name is read separately + sub:skip(20) + elseif w == 4 then + table.insert(rec, sub:u32le()) + elseif w == 2 then + table.insert(rec, sub:u16le()) + elseif w == -2 then + table.insert(rec, sub:i16le()) + elseif w == 1 then + table.insert(rec, sub:u8()) + else + table.insert(rec, sub:i8()) + end + end + recs[i] = rec + end + hydra[sid] = recs + if sid == "phdr" or sid == "inst" or sid == "shdr" then + local names = table.create(n) + for i = 0, n - 1 do + names[i + 1] = sub:sub(i * rs, 20):fixed(20) + end + hydra[sid .. "Names"] = names :: any + end + end + end + end + end + end + if not smpl then + return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)") + end + for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do + if not hydra[k] or #hydra[k] == 0 then + return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") + end + end + -- samples + local sr = smpl :: Bytes.Reader + local count = sr:remaining() // 2 + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples)) + end + local samples = buffer.create((count + 1) * 4) + do + local b, p = sr.buf, sr.pos + local readi16, writef32 = buffer.readi16, buffer.writef32 + local s24 = sm24 + if s24 and s24:remaining() >= count then + local q = s24.pos + local readu8 = buffer.readu8 + for i = 0, count - 1 do + writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607) + end + else + s24 = nil + for i = 0, count - 1 do + writef32(samples, i * 4, readi16(b, p + i * 2) / 32767) + end + end + sm24 = s24 + end + -- presets (tsf_load_presets) + local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen + local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr + local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames + local nInst = #inst - 1 -- the last record of each list is the terminal one + local nShdr = #shdr - 1 + local function range(list: { { number } }, i: number, field: number, limit: number): (number, number) + -- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes) + local a = list[i][field] + 1 + local b = if list[i + 1] then list[i + 1][field] + 1 else a + return math.max(1, a), math.min(b, limit + 1) + end + local presets: { Preset } = {} + local regionTotal = 0 + for pi = 1, #phdr - 1 do + local ph = phdr[pi] + local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} } + local globalRegion = clear(true) + local b0, b1 = range(phdr, pi, 4, #pbag) + for bi = b0, b1 - 1 do + local presetRegion = copy(globalRegion) + local hadInstrument = false + local g0, g1 = range(pbag, bi, 1, #pgen) + for gi = g0, g1 - 1 do + local pg = pgen[gi] + local op, amount = pg[1], pg[2] + local lo, hi = amount % 256, amount // 256 + local s = if amount >= 32768 then amount - 65536 else amount + if op == GEN_INSTRUMENT then + hadInstrument = true + if amount < nInst then + local instRegion = clear(false) + local ib0, ib1 = range(inst, amount + 1, 2, #ibag) + for ibi = ib0, ib1 - 1 do + local zone = copy(instRegion) + local hadSample = false + local ig0, ig1 = range(ibag, ibi, 1, #igen) + for igi = ig0, ig1 - 1 do + local ig = igen[igi] + local iop, iamt = ig[1], ig[2] + if iop == GEN_SAMPLEID then + hadSample = true + if iamt >= nShdr then + break + end + local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey) + and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel) + if ok then + local z = copy(zone) + z.lokey = math.max(z.lokey, presetRegion.lokey) + z.hikey = math.min(z.hikey, presetRegion.hikey) + z.lovel = math.max(z.lovel, presetRegion.lovel) + z.hivel = math.min(z.hivel, presetRegion.hivel) + merge(z, presetRegion) + envToSecs(z, "a", true) + envToSecs(z, "m", false) + z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO) + z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO) + local sh = shdr[iamt + 1] + local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5] + z.offset = math.clamp(z.offset + sStart, 0, count) + local stop = z.stop + sEnd + if stop > 0 and stop < count then + stop += 1 + else + stop = count + end + z.stop = math.clamp(stop, 0, count) + z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count) + local le = z.loopEnd + sLoopEnd + if sLoopEnd > 0 then + le -= 1 + end + z.loopEnd = math.clamp(le, 0, count) + if z.keycenter == -1 then + z.keycenter = sh[7] + end + z.tune += sh[8] + z.sampleRate = sh[6] + z.sampleIndex = iamt + regionTotal += 1 + if regionTotal > maxRegions then + return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions") + end + table.insert(preset.regions, z) + end + break -- sampleID ends a zone's generator list + else + local ilo, ihi = iamt % 256, iamt // 256 + operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt) + end + end + if ibi == ib0 and not hadSample then + instRegion = zone -- the instrument's global zone + end + end + end + break -- instrument ends a preset zone's generator list + else + operator(presetRegion, op, lo, hi, s, amount) + end + end + if bi == b0 and not hadInstrument then + globalRegion = presetRegion -- the preset's global zone + end + end + table.insert(presets, preset) + end + -- sorted by bank, then preset, then file order (tsf's sortedIndex) + for i, p in presets do + (p :: any)._order = i + end + table.sort(presets, function(a: Preset, b: Preset): boolean + if a.bank ~= b.bank then + return a.bank < b.bank + end + if a.preset ~= b.preset then + return a.preset < b.preset + end + return (a :: any)._order < (b :: any)._order + end) + for _, p in presets do + (p :: any)._order = nil + end + local headers = table.create(nShdr) + for i = 1, nShdr do + local sh = shdr[i] + headers[i] = { + name = shdrNames[i], + start = sh[2], + stop = sh[3], + loopStart = sh[4], + loopEnd = sh[5], + sampleRate = sh[6], + originalPitch = sh[7], + pitchCorrection = sh[8], + link = sh[9], + type = sh[10], + } + end + local instruments = table.create(nInst) + for i = 1, nInst do + instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } + end + local sf: SoundFont = { + kind = "soundfont", + info = info, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = headers, + instruments = instruments, + meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } }, + } + return sf, nil +end + +return Parse diff --git a/src/Formats/codecs/SoundFont/Synth.luau b/src/Formats/codecs/SoundFont/Synth.luau new file mode 100644 index 0000000..0bde0cd --- /dev/null +++ b/src/Formats/codecs/SoundFont/Synth.luau @@ -0,0 +1,797 @@ +--!strict +--!native +-- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9, +-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt): +-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter +-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear +-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with +-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, +-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not +-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. +-- Differences from tsf.h: a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. +-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, +-- the sample buffer has a zero pad sample, the output range is checked before mixing). +local Synth = {} + +local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len +local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor + +local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7 +local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block +local FASTRELEASE = 0.01 +local PI = math.pi +local LOOP_NONE, LOOP_SUSTAIN = 0, 2 + +type Env = { + segment: number, + isExp: boolean, + isAmp: boolean, + vel: number, + level: number, + slope: number, + untilNext: number, + delay: number, + attack: number, + hold: number, + decay: number, + sustain: number, + release: number, +} +type Lfo = { untilStart: number, level: number, delta: number } +export type Voice = { + preset: number, -- 1-based preset index, -1 = idle + key: number, + channel: number, + held: boolean, -- note off while sustain was down + region: { [string]: number }, + pitchIn: number, -- timecents + pitchOut: number, + pos: number, + gainDB: number, + panL: number, + panR: number, + playIndex: number, + loopStart: number, + loopEnd: number, + amp: Env, + mod: Env, + lpActive: boolean, + qinv: number, + a0: number, + a1: number, + b1: number, + b2: number, + z1: number, + z2: number, + modlfo: Lfo, + viblfo: Lfo, +} +export type Channel = { + preset: number, + bank: number, + pitchWheel: number, + midiPan: number, + midiVolume: number, + midiExpression: number, + midiRPN: number, + midiData: number, + sustain: boolean, + panOffset: number, + gainDB: number, + pitchRange: number, + tuning: number, +} +export type State = { + presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, + lookup: { [number]: number }, -- bank * 128 + preset -> preset index + samples: buffer, + rate: number, + gainDB: number, + voices: { Voice }, + maxVoices: number, + playIndex: number, + channels: { Channel }, -- [1..16] = MIDI channels 0..15 +} + +local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end +local function cents2Hz(c: number): number + return 8.176 * 2 ^ (c / 1200) +end +local function db2gain(db: number): number + return if db > -100 then 10 ^ (db * 0.05) else 0 +end +local function gain2db(g: number): number + return if g <= 0.00001 then -100 else 20 * math.log10(g) +end + +-- ------------------------------------------------------------------------------------------------ envelope +local function releaseSamples(e: Env, rate: number): number + return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) +end + +local function nextSegment(e: Env, active: number, rate: number) + local seg = active + if seg == NONE then + e.untilNext = floor(e.delay * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0 + return + end + seg = DELAY + end + if seg == DELAY then + e.untilNext = floor(e.attack * rate) + if e.untilNext > 0 then + if not e.isAmp then + -- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x) + e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate) + end + e.segment, e.isExp, e.level = ATTACK, false, 0 + e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1 + return + end + seg = ATTACK + end + if seg == ATTACK then + e.untilNext = floor(e.hold * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0 + return + end + seg = HOLD + end + if seg == HOLD then + e.untilNext = floor(e.decay * rate) + if e.untilNext > 0 then + e.segment, e.level = DECAY, 1 + if e.isAmp then + local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h) + e.slope = exp(mystery) + e.isExp = true + if e.sustain > 0 then + e.untilNext = floor(log(e.sustain) / mystery) + end + else + e.slope = -1 / e.untilNext + e.untilNext = floor(e.decay * (1 - e.sustain) * rate) + e.isExp = false + end + return + end + seg = DECAY + end + if seg == DECAY then + e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false + return + end + if seg == SUSTAIN then + e.segment = RELEASE + e.untilNext = math.max(1, releaseSamples(e, rate)) + if e.isAmp then + e.slope = exp(-9.226 / e.untilNext) + e.isExp = true + else + e.slope = -e.level / e.untilNext + e.isExp = false + end + return + end + e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF +end + +local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) + e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] + e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] + local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] + if kh ~= 0 then + local h = e.hold + kh * (60 - key) + e.hold = if h < -10000 then 0 else tc2s(h) + end + if kd ~= 0 then + local d = e.decay + kd * (60 - key) + e.decay = if d < -10000 then 0 else tc2s(d) + end + e.vel, e.isAmp = vel, isAmp + nextSegment(e, NONE, rate) +end + +local function envProcess(e: Env, n: number, rate: number) + local slope = e.slope + if slope ~= 0 then + if e.isExp then + e.level *= slope ^ n + else + e.level += slope * n + end + end + e.untilNext -= n + if e.untilNext <= 0 then + nextSegment(e, e.segment, rate) + end +end + +local function newEnv(): Env + return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } +end + +-- ------------------------------------------------------------------------------------------------ filter / lfo +local function lowpassSetup(v: Voice, fc: number) + -- the biquad from earlevel.com (as tsf.h) + local k = tan(PI * fc) + local kk = k * k + local norm = 1 / (1 + k * v.qinv + kk) + v.a0 = kk * norm + v.a1 = 2 * v.a0 + v.b1 = 2 * (kk - 1) * norm + v.b2 = (1 - k * v.qinv + kk) * norm +end + +local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) + l.untilStart = floor(delay * rate) + l.delta = 4 * cents2Hz(freqCents) / rate + l.level = 0 +end + +local function lfoProcess(l: Lfo, n: number) + if l.untilStart > n then + l.untilStart -= n + return + end + l.level += l.delta * n + if l.level > 1 then + l.delta = -l.delta + l.level = 2 - l.level + elseif l.level < -1 then + l.delta = -l.delta + l.level = -2 - l.level + end +end + +-- ------------------------------------------------------------------------------------------------ voices +local function calcPitch(v: Voice, shift: number, rate: number) + local r = v.region + local note = v.key + r.transpose + r.tune / 100 + local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift + v.pitchIn = adjusted * 100 + v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) +end + +local function setPan(v: Voice, pan: number) + if pan <= -0.5 then + v.panL, v.panR = 1, 0 + elseif pan >= 0.5 then + v.panL, v.panR = 0, 1 + else + v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan) + end +end + +local function channelShift(c: Channel): number + return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning +end + +local function voiceEnd(s: State, v: Voice) + nextSegment(v.amp, SUSTAIN, s.rate) + nextSegment(v.mod, SUSTAIN, s.rate) + if v.region.loopMode == LOOP_SUSTAIN then + v.loopEnd = v.loopStart -- keep playing, stop looping + end +end + +local function voiceEndQuick(s: State, v: Voice) + v.amp.release = 0 + nextSegment(v.amp, SUSTAIN, s.rate) + v.mod.release = 0 + nextSegment(v.mod, SUSTAIN, s.rate) +end + +local function newVoice(): Voice + return { + preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, + panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), + lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0, + modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 }, + } +end + +local function newChannel(): Channel + return { + preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, + midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, + } +end + +-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build). +-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256) +function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State + local lookup: { [number]: number } = {} + for i, p in sf.presets do + local k = p.bank * 128 + p.preset + if lookup[k] == nil then + lookup[k] = i + end + end + local s: State = { + presets = sf.presets, + lookup = lookup, + samples = sf.samples, + rate = rate, + gainDB = gain2db(gain or 0.5), + voices = {}, + maxVoices = maxVoices or 256, + playIndex = 0, + channels = {}, + } + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end + return s +end + +local function presetIndex(s: State, bank: number, preset: number): number + return s.lookup[bank * 128 + preset] or -1 +end + +-- noteOn(s, channel, key, velocity 0..127) +function Synth.noteOn(s: State, ch: number, key: number, velocity: number) + local c = s.channels[ch + 1] + if not c then + return + end + if velocity <= 0 then + Synth.noteOff(s, ch, key) + return + end + local pi = c.preset + local preset = s.presets[pi] + if not preset then + return + end + local vel = math.min(velocity, 127) / 127 + local midiVel = floor(vel * 127) + local rate = s.rate + local voices = s.voices + local playIndex = s.playIndex + s.playIndex += 1 + for _, region in preset.regions do + if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then + continue + end + local voice: Voice? = nil + if region.group ~= 0 then + for _, v in voices do + if v.preset == pi and v.region.group == region.group then + voiceEndQuick(s, v) + elseif v.preset == -1 and not voice then + voice = v + end + end + else + for _, v in voices do + if v.preset == -1 then + voice = v + break + end + end + end + if not voice then + if #voices < s.maxVoices then + local v = newVoice() + table.insert(voices, v) + voice = v + else + local best = -1e18 + for _, v in voices do + if v.amp.segment == RELEASE then + local done = releaseSamples(v.amp, rate) - v.amp.untilNext + if done > best then + best, voice = done, v + end + end + end + if not voice then + continue + end + end + end + local v = voice :: Voice + v.region = region + v.preset = pi + v.key = key + v.channel = ch + v.playIndex = playIndex + v.held = false + v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB + calcPitch(v, channelShift(c), rate) + setPan(v, region.pan + c.panOffset) + v.pos = region.offset + local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd + v.loopStart = if doLoop then region.loopStart else 0 + v.loopEnd = if doLoop then region.loopEnd else 0 + envSetup(v.amp, region, "a", key, midiVel, true, rate) + envSetup(v.mod, region, "m", key, midiVel, false, rate) + local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1 + v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20) + v.z1, v.z2 = 0, 0 + v.lpActive = fc < 0.499 + if v.lpActive then + lowpassSetup(v, fc) + end + lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate) + lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate) + end +end + +-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down +function Synth.noteOff(s: State, ch: number, key: number) + local c = s.channels[ch + 1] + if not c then + return + end + local first = -1 + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then + if first == -1 or v.playIndex < first then + first = v.playIndex + end + end + end + if first == -1 then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then + if c.sustain then + v.held = true + else + voiceEnd(s, v) + end + end + end +end + +local function applyPitch(s: State, ch: number, c: Channel) + local shift = channelShift(c) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + calcPitch(v, shift, s.rate) + end + end +end + +local function setVolume(s: State, ch: number, c: Channel, volume: number) + local db = gain2db(volume) + if db == c.gainDB then + return + end + local change = db - c.gainDB + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + v.gainDB += change + end + end + c.gainDB = db +end + +local function setChannelPan(s: State, ch: number, c: Channel, pan: number) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + setPan(v, v.region.pan + pan - 0.5) + end + end + c.panOffset = pan - 0.5 +end + +local function setTuning(s: State, ch: number, c: Channel, tuning: number) + if c.tuning ~= tuning then + c.tuning = tuning + applyPitch(s, ch, c) + end +end + +local function setPitchRange(s: State, ch: number, c: Channel, range: number) + if c.pitchRange ~= range then + c.pitchRange = range + if c.pitchWheel ~= 8192 then + applyPitch(s, ch, c) + end + end +end + +local function setSustain(s: State, ch: number, c: Channel, on: boolean) + if c.sustain == on then + return + end + c.sustain = on + if on then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then + voiceEnd(s, v) + end + end +end + +-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128) +function Synth.program(s: State, ch: number, program: number) + local c = s.channels[ch + 1] + if not c then + return + end + local bank = c.bank % 32768 + local idx + if ch == 9 then + idx = presetIndex(s, 128 + bank, program) + if idx == -1 then + idx = presetIndex(s, 128, program) + end + if idx == -1 then + idx = presetIndex(s, 128, 0) + end + if idx == -1 then + idx = presetIndex(s, bank, program) + end + else + idx = presetIndex(s, bank, program) + end + if idx == -1 then + idx = presetIndex(s, 0, program) + end + if idx ~= -1 then + c.preset = idx + end +end + +-- pitchBend(s, channel, 0..16383) +function Synth.pitchBend(s: State, ch: number, value: number) + local c = s.channels[ch + 1] + if not c or c.pitchWheel == value then + return + end + c.pitchWheel = value + applyPitch(s, ch, c) +end + +-- control(s, channel, controller, value 0..127) +function Synth.control(s: State, ch: number, cc: number, value: number) + local c = s.channels[ch + 1] + if not c then + return + end + local volume, pan, data = false, false, false + if cc == 7 then + c.midiVolume = c.midiVolume % 128 + value * 128 + volume = true + elseif cc == 39 then + c.midiVolume = c.midiVolume - c.midiVolume % 128 + value + volume = true + elseif cc == 11 then + c.midiExpression = c.midiExpression % 128 + value * 128 + volume = true + elseif cc == 43 then + c.midiExpression = c.midiExpression - c.midiExpression % 128 + value + volume = true + elseif cc == 10 then + c.midiPan = c.midiPan % 128 + value * 128 + pan = true + elseif cc == 42 then + c.midiPan = c.midiPan - c.midiPan % 128 + value + pan = true + elseif cc == 6 then + c.midiData = c.midiData % 128 + value * 128 + data = true + elseif cc == 38 then + c.midiData = c.midiData - c.midiData % 128 + value + data = true + elseif cc == 0 then + c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h) + elseif cc == 32 then + c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value + elseif cc == 101 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn % 128 + value * 128 + elseif cc == 100 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn - rpn % 128 + value + elseif cc == 98 or cc == 99 then + c.midiRPN = 0xFFFF + elseif cc == 64 then + setSustain(s, ch, c, value >= 64) + elseif cc == 120 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then + voiceEndQuick(s, v) + end + end + elseif cc == 123 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then + voiceEnd(s, v) + end + end + elseif cc == 121 then + c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0 + setVolume(s, ch, c, 1) + setChannelPan(s, ch, c, 0.5) + setPitchRange(s, ch, c, 2) + setTuning(s, ch, c, 0) + end + if volume then + -- the cube gives a decent MIDI volume curve (tsf.h) + setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3) + elseif pan then + setChannelPan(s, ch, c, c.midiPan / 16383) + elseif data then + if c.midiRPN == 0 then + setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128)) + elseif c.midiRPN == 1 then + local t = c.tuning + setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192) + elseif c.midiRPN == 2 and cc == 6 then + local t = c.tuning + setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t)))) + end + end +end + +-- midi(s, status, d1, d2): one channel message +function Synth.midi(s: State, status: number, d1: number, d2: number) + local kind, ch = status // 16, status % 16 + if kind == 9 then + Synth.noteOn(s, ch, d1, d2) + elseif kind == 8 then + Synth.noteOff(s, ch, d1) + elseif kind == 11 then + Synth.control(s, ch, d1, d2) + elseif kind == 12 then + Synth.program(s, ch, d1) + elseif kind == 14 then + Synth.pitchBend(s, ch, d1 + d2 * 128) + end +end + +-- reset(s): all voices off, channels back to their defaults +function Synth.reset(s: State) + for _, v in s.voices do + v.preset = -1 + end + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end +end + +-- active(s) -> the number of sounding voices +function Synth.active(s: State): number + local n = 0 + for _, v in s.voices do + if v.preset ~= -1 then + n += 1 + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ render +local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) + local region = v.region + local input = s.samples + local rate = s.rate + local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc + local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume + local vibLfoToPitch = region.vibLfoToPitch + local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0 + local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0) + local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0 + local loopStart, loopEnd = v.loopStart, v.loopEnd + local isLooping = loopStart < loopEnd + local endD = region.stop + local loopEndD = loopEnd + 1 + local loopLen = loopEnd - loopStart + 1 + local pos = v.pos + local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2 + local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0 + local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0 + local dynamicGain = modLfoToVolume ~= 0 + local filterFc = region.filterFc + local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut + local noteGain = if dynamicGain then 0 else db2gain(v.gainDB) + local o = frame * 8 + while numSamples > 0 do + local block = if numSamples > BLOCK then BLOCK else numSamples + numSamples -= block + if dynamicLowpass then + local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc + local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1 + lpActive = fc < 0.499 + if lpActive then + lowpassSetup(v, fc) + a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2 + end + end + if dynamicPitch then + pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut + end + if dynamicGain then + noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1) + end + local gainMono = noteGain * v.amp.level + envProcess(v.amp, block, rate) + if updateModEnv then + envProcess(v.mod, block, rate) + end + if updateModLfo then + lfoProcess(v.modlfo, block) + end + if updateVibLfo then + lfoProcess(v.viblfo, block) + end + local gl, gr = gainMono * v.panL, gainMono * v.panR + local k = block + while k > 0 and pos < endD do + k -= 1 + local ip = floor(pos) + local np = if ip >= loopEnd and isLooping then loopStart else ip + 1 + local s0 = readf32(input, ip * 4) + local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) + if lpActive then + local y = val * a0 + z1 + z1 = val * a1 + z2 - b1 * y + z2 = val * a0 - b2 * y + val = y + end + writef32(out, o, readf32(out, o) + val * gl) + writef32(out, o + 4, readf32(out, o + 4) + val * gr) + o += 8 + pos += pitchRatio + if pos >= loopEndD and isLooping then + pos -= loopLen + end + end + o += k * 8 + if not (pos < endD) or v.amp.segment == DONE then + v.preset = -1 + return + end + end + v.pos = pos + v.lpActive, v.z1, v.z2 = lpActive, z1, z2 +end + +-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range +-- requests are clipped to the buffer +function Synth.render(s: State, out: buffer, frame: number, n: number) + local room = blen(out) // 8 - frame + if frame < 0 or room <= 0 then + return + end + if n > room then + n = room + end + if n <= 0 then + return + end + -- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here + -- once so a hand-made SoundFont cannot index outside it) + local count = blen(s.samples) // 4 - 1 + for _, v in s.voices do + if v.preset ~= -1 then + local r = v.region + if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then + v.preset = -1 + else + voiceRender(s, v, out, frame, n) + end + end + end +end + +return Synth diff --git a/src/Formats/codecs/SoundFont/init.luau b/src/Formats/codecs/SoundFont/init.luau new file mode 100644 index 0000000..a1c8feb --- /dev/null +++ b/src/Formats/codecs/SoundFont/init.luau @@ -0,0 +1,69 @@ +--!strict +-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by +-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT, +-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered. +-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw / +-- noise) with a drum kit. +-- +-- local SoundFont = require("@formats/codecs/SoundFont") +-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err +-- local sf = SoundFont.fallback() -- the built-in waveform set +-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100) +-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Parse = require("@formats/codecs/SoundFont/Parse") +local Synth = require("@formats/codecs/SoundFont/Synth") +local Fallback = require("@formats/codecs/SoundFont/Fallback") + +local SoundFont = {} + +export type SoundFont = Parse.SoundFont +export type State = Synth.State + +SoundFont.Synth = Synth +SoundFont.defaultRegion = Parse.defaultRegion + +-- sniff(r) -> true when r starts with RIFF....sfbk +function SoundFont.sniff(r: Bytes.Reader): boolean + return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" +end + +-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6), +-- opts.maxSamples (default 2^28) +function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) + local r: Bytes.Reader + if type(src) == "string" then + r = Bytes.reader(buffer.fromstring(src)) + elseif type(src) == "buffer" then + r = Bytes.reader(src) + elseif type(src) == "table" and type(src.buf) == "buffer" then + r = Bytes.reader(src.buf, src.pos, src.limit - src.pos) + else + return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader") + end + local ok, sf, err = pcall(Parse.parse, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf)) + end + return sf, err +end + +-- fallback() -> the built-in General MIDI waveform set +function SoundFont.fallback(): SoundFont + return Fallback.build() +end + +-- isSoundFont(v) -> true for a parsed / fallback SoundFont value +function SoundFont.isSoundFont(v: any): boolean + return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" +end + +-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256) +function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State + return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) +end + +return SoundFont diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/music/midi/Render.luau new file mode 100644 index 0000000..657246a --- /dev/null +++ b/src/Formats/music/midi/Render.luau @@ -0,0 +1,261 @@ +--!strict +-- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, +-- and the audio Decoder that plays a Midi through codecs/SoundFont's synth (a SoundFont bank, or the built-in +-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). +-- Format 2: each track is its own song with its own tempo map, played one after another. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local SoundFont = require("@formats/codecs/SoundFont") + +local Synth = SoundFont.Synth + +local Render = {} + +export type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number } + +local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } + +local function tempoOf(ev: any): number? + if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then + return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3] + end + return nil +end + +-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2) +function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap + local changes: { { number } } = {} + for ti, t in midi.tracks do + if track == nil or track == ti then + for i, ev in t.events do + local us = tempoOf(ev) + if us then + table.insert(changes, { ev.tick, ti, i, us }) + end + end + end + end + table.sort(changes, function(a: { number }, b: { number }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } + local div = midi.division + for _, c in changes do + local n = #map.ticks + local tick = c[1] + local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div + if tick == map.ticks[n] then + map.us[n] = c[4] + else + table.insert(map.ticks, tick) + table.insert(map.secs, sec) + table.insert(map.us, c[4]) + end + end + return map +end + +-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time) +function Render.seconds(map: TempoMap, tick: number): number + local div = map.division + if div < 0 then + local fps = -(div // 256) + local tpf = div % 256 + if tpf == 0 then + return 0 + end + return tick / ((if fps == 29 then 29.97 else fps) * tpf) + end + local ticks = map.ticks + -- binary search for the last change at or before tick + local lo, hi = 1, #ticks + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ticks[mid] <= tick then + lo = mid + else + hi = mid - 1 + end + end + return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div +end + +-- length(midi) -> seconds to the last event (format 2: the tracks one after another) +function Render.length(midi: Types.Midi): number + if #midi.tracks == 0 then + return 0 + end + if midi.format == 2 then + local total = 0 + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + total += Render.seconds(map, last) + end + return total + end + local map = Render.tempoMap(midi) + local last = 0 + for _, t in midi.tracks do + for _, ev in t.events do + last = math.max(last, ev.tick) + end + end + return Render.seconds(map, last) +end + +export type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number } + +-- timeline(midi) -> the channel messages in play order with their times in seconds +function Render.timeline(midi: Types.Midi): Timeline + local items: { { any } } = {} + local offset = 0 + local function add(map: TempoMap, ti: number, t: any, base: number) + for i, ev in t.events do + local st = STATUS[ev.type] + if st and type(ev.data) == "table" then + local ch = ev.channel or 0 + table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 }) + end + end + end + if midi.format == 2 then + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + add(map, ti, t, offset) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + offset += Render.seconds(map, last) + end + else + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + add(map, ti, t, 0) + end + end + table.sort(items, function(a: { any }, b: { any }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local tl: Timeline = { time = table.create(#items), status = table.create(#items), d1 = table.create(#items), d2 = table.create(#items), length = Render.length(midi) } + for i, it in items do + tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 + end + return tl +end + +export type RenderOptions = { + sampleRate: number?, -- default 44100 + soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms + gain: number?, -- linear output gain, default 0.5 + tail: number?, -- seconds rendered after the last event (release tails), default 1 + maxVoices: number?, -- default 256 +} + +-- decoder(midi, opts?) -> Types.Decoder | nil, Err +function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then + return nil, Err.new(Err.ARG, "render: needs a Midi value") + end + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 1000 or rate > 384000 then + return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000") + end + local sf = o.soundfont + if sf == nil then + sf = SoundFont.fallback() + elseif not SoundFont.isSoundFont(sf) then + local parsed, err = SoundFont.parse(sf) + if not parsed then + return nil, err + end + sf = parsed + end + local tl = Render.timeline(midi) + local tail = o.tail or 1 + local frames = math.max(0, math.ceil((tl.length + tail) * rate)) + local nev = #tl.time + local evFrame = table.create(nev) + for i = 1, nev do + evFrame[i] = math.floor(tl.time[i] * rate + 0.5) + end + local gain, maxVoices = o.gain, o.maxVoices + local state = Synth.new(sf, rate, gain, maxVoices) + local pos, nextEv = 0, 1 + + local dec = { + sampleRate = rate, + channels = 2, + frames = frames, + duration = frames / rate, + bitrate = 0, + tags = {} :: Types.Tags, + } + for _, t in midi.tracks do + if t.name and not dec.tags.title then + dec.tags.title = t.name + end + end + + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.min(math.floor(n), frames - pos)) + local buf = out + if not buf or buffer.len(buf) < n * 8 then + buf = buffer.create(math.max(n, 1) * 8) + end + local b = buf :: buffer + buffer.fill(b, 0, 0, n * 8) + local i = 0 + while i < n do + while nextEv <= nev and evFrame[nextEv] <= pos + i do + Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv]) + nextEv += 1 + end + local stop = n + if nextEv <= nev then + stop = math.min(n, evFrame[nextEv] - pos) + end + if stop > i then + Synth.render(state, b, i, stop - i) + i = stop + end + end + pos += n + return b, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames) + if target < pos then + Synth.reset(state) + pos, nextEv = 0, 1 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / rate + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +return Render diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau new file mode 100644 index 0000000..4c0ec1f --- /dev/null +++ b/src/Formats/music/midi/Smf.luau @@ -0,0 +1,402 @@ +--!strict +-- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE +-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps +-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are +-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the +-- end, mid-track end-of-track events dropped). Written from the SMF 1.0 specification (no third-party code). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +local Smf = {} + +local readu8 = buffer.readu8 + +local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } +local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } +Smf.TYPE_STATUS = TYPE_STATUS + +export type ReadOptions = { + strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated) + maxEvents: number?, -- default 2^24 +} +export type WriteOptions = { + runningStatus: boolean?, -- default true +} + +local function bytesOf(b: buffer, p: number, n: number): { number } + local t = table.create(n) + for i = 0, n - 1 do + t[i + 1] = readu8(b, p + i) + end + return t +end + +local function text(data: { number }): string + local parts = table.create(#data) + for i, c in data do + parts[i] = string.char(c) + end + return table.concat(parts) +end +Smf.text = text + +-- ------------------------------------------------------------------------------------------------ read +-- one MTrk body [p, e): events | nil, message, truncated +local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) + local events: { Types.MidiEvent } = {} + local tick = 0 + local running = 0 + while p < e do + -- delta time + local delta, n = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + n += 1 + delta = delta * 128 + c % 128 + if n > 4 then + return nil, "delta time longer than 4 bytes", false + end + until c < 128 + tick += delta + if p >= e then + return events, nil, true + end + local status = readu8(b, p) + if status < 0x80 then + if running == 0 then + return nil, "running status without a previous status byte", false + end + status = running + else + p += 1 + if status < 0xF0 then + running = status + end + end + budget[1] -= 1 + if budget[1] < 0 then + return nil, "LIMIT", false + end + if status == 0xFF or status == 0xF0 or status == 0xF7 then + local mtype = 0 + if status == 0xFF then + if p >= e then + return events, nil, true + end + mtype = readu8(b, p) + p += 1 + end + local len, m = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + m += 1 + len = len * 128 + c % 128 + if m > 4 then + return nil, "length longer than 4 bytes", false + end + until c < 128 + if p + len > e then + return events, nil, true + end + local data = bytesOf(b, p, len) + p += len + if status == 0xFF then + table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data }) + else + table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data }) + end + elseif status >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02x in a track", status), false + else + local kind = status // 16 + local count = if kind == 12 or kind == 13 then 1 else 2 + if p + count > e then + return events, nil, true + end + local d1 = readu8(b, p) + local d2 = if count == 2 then readu8(b, p + 1) else 0 + if d1 >= 128 or d2 >= 128 then + return nil, "data byte over 127", false + end + p += count + table.insert(events, { + tick = tick, + type = CHANNEL_TYPES[kind], + channel = status % 16, + data = if count == 2 then { d1, d2 } else { d1 }, + }) + end + end + return events, nil, false +end + +-- read(r, opts?) -> Midi | nil, Err +function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) + local strict = opts and opts.strict or false + local budget = { opts and opts.maxEvents or 2 ^ 24 } + local b = r.buf + local base, limit = r.base, r.limit + local rmid = false + -- RIFF RMID: the SMF is the "data" chunk + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + local q = base + 12 + local found = false + while q + 8 <= limit do + local id = buffer.readstring(b, q, 4) + local size = buffer.readu32(b, q + 4) + if id == "data" then + base = q + 8 + limit = math.min(limit, base + size) + found = true + break + end + q += 8 + size + size % 2 + end + if not found then + return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base) + end + rmid = true + end + local h = Bytes.reader(b, base, limit - base) + if h:string(4) ~= "MThd" then + return nil, Err.new(Err.CORRUPT, "no MThd header", base) + end + local hlen = h:u32be() + local format, ntrks, division = h:u16be(), h:u16be(), h:i16be() + if h.err then + return nil, h.err + end + if hlen < 6 then + return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4) + end + if format > 2 then + return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8) + end + if division == 0 then + return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12) + end + local midi = Types.Midi.new(division) + midi.format = format + local truncated = false + local p = base + 8 + hlen + while #midi.tracks < ntrks and p + 8 <= limit do + local id = buffer.readstring(b, p, 4) + local size = bit32.byteswap(buffer.readu32(b, p + 4)) + local s = p + 8 + local e = s + size + if e > limit then + e = limit + truncated = true + end + if id == "MTrk" then + local events, msg, short = readTrack(b, s, e, budget) + if not events then + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "over the event limit") + end + return nil, Err.new(Err.CORRUPT, msg or "bad track", s) + end + truncated = truncated or short + local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil } + for _, ev in events do + if ev.type == "meta" and ev.meta == 3 then + track.name = text(ev.data :: { number }) + break + end + end + table.insert(midi.tracks, track) + end + p = s + size + end + if #midi.tracks < ntrks and p < limit then + truncated = true + elseif #midi.tracks < ntrks then + truncated = true + end + if truncated and strict then + return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)") + end + midi.meta.declaredTracks = ntrks + midi.meta.truncated = truncated + midi.meta.rmid = rmid + if division < 0 then + local fps = -(division // 256) + midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 } + end + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function vlq(w: Bytes.Writer, v: number) + if v < 128 then + w:u8(v) + return + end + local bytes = {} + while v > 0 do + table.insert(bytes, 1, v % 128) + v = v // 128 + end + for i, c in bytes do + w:u8(if i < #bytes then c + 128 else c) + end +end + +local function byteList(d: any, want: number?): { number }? + if type(d) ~= "table" then + return if want == 0 then {} else nil + end + for i, v in d do + if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then + return nil + end + end + if want and #d < want then + return nil + end + return d +end + +-- write(midi, opts?) -> buffer | nil, Err +function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" then + return nil, Err.new(Err.ARG, "midi encode: needs a Midi value with tracks") + end + local running = not (opts and opts.runningStatus == false) + local format = midi.format or 1 + local division = midi.division or 480 + if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then + return nil, Err.new(Err.ARG, "midi encode: format must be 0, 1 or 2") + end + if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then + return nil, Err.new(Err.ARG, "midi encode: division must be a non-zero 16-bit integer") + end + if format == 0 and #midi.tracks ~= 1 then + return nil, Err.new(Err.ARG, "midi encode: format 0 needs exactly one track") + end + if #midi.tracks > 65535 then + return nil, Err.new(Err.ARG, "midi encode: too many tracks") + end + local w = Bytes.writer(1024) + w:string("MThd") + w:u32be(6) + w:u16be(format) + w:u16be(#midi.tracks) + w:u16be(if division < 0 then division + 65536 else division) + for ti, track in midi.tracks do + local events = if type(track) == "table" then track.events else nil + if type(events) ~= "table" then + return nil, Err.new(Err.ARG, "midi encode: track " .. ti .. " has no events list") + end + -- stable order by tick + local sorted = true + local last = 0 + for i, ev in events do + if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i)) + end + if ev.tick < last then + sorted = false + end + last = ev.tick + end + local list = events + if not sorted then + list = table.clone(events) + local order: { [any]: number } = {} + for i, ev in list do + order[ev] = i + end + table.sort(list, function(a: any, c: any): boolean + if a.tick ~= c.tick then + return a.tick < c.tick + end + return order[a] < order[c] + end) + end + w:string("MTrk") + local lenAt = w:tell() + w:u32be(0) + local start = w:tell() + local prev = 0 + local status = 0 + local endTick = 0 + for i, ev in list do + local t = ev.type + endTick = ev.tick + if t == "meta" and ev.meta == 0x2F then + continue -- written once at the end + end + local delta = ev.tick - prev + if delta > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "midi encode: a delta time over 0x0FFFFFFF ticks") + end + local base = TYPE_STATUS[t] + if base then + local ch = ev.channel or 0 + if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i)) + end + local n = if base == 0xC0 or base == 0xD0 then 1 else 2 + local d = byteList(ev.data, n) + if not d or d[1] > 127 or (n == 2 and d[2] > 127) then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n)) + end + vlq(w, delta) + local st = base + ch + if not (running and st == status) then + w:u8(st) + end + status = st + w:u8(d[1]) + if n == 2 then + w:u8(d[2]) + end + elseif t == "meta" or t == "sysex" or t == "escape" then + local d = byteList(ev.data, 0) + if not d then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i)) + end + vlq(w, delta) + if t == "meta" then + local m = ev.meta + if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i)) + end + w:u8(0xFF) + w:u8(m) + else + w:u8(if t == "sysex" then 0xF0 else 0xF7) + end + if #d > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "midi encode: event data too long") + end + vlq(w, #d) + for _, c in d do + w:u8(c) + end + status = 0 + else + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t))) + end + prev = ev.tick + end + vlq(w, math.max(0, endTick - prev)) + w:u8(0xFF) + w:u8(0x2F) + w:u8(0) + w:setU32be(lenAt, w:tell() - start) + end + return w:finish(), nil +end + +return Smf diff --git a/src/Formats/music/midi/init.luau b/src/Formats/music/midi/init.luau new file mode 100644 index 0000000..fcaeb46 --- /dev/null +++ b/src/Formats/music/midi/init.luau @@ -0,0 +1,136 @@ +--!strict +-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the +-- specification (no third-party code); rendering goes through codecs/SoundFont (a TinySoundFont port). +-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / +-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, +-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running +-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and +-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. +-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Smf = require("@formats/music/midi/Smf") +local Render = require("@formats/music/midi/Render") + +-- ------------------------------------------------------------------------------------------------ contract +local Midi = { + name = "midi", + category = "music", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24) +export type EncodeOptions = Smf.WriteOptions -- runningStatus (default true) +export type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices + +-- ------------------------------------------------------------------------------------------------ sniff +function Midi.sniff(r: Bytes.Reader): number + if r:peek(4) == "MThd" then + return 1 + end + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder + local dec, err = Render.decoder(self, opts) + if not dec then + -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) + local empty: any = { + sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, + read = function(_self: any, _n: number, out: buffer?): (buffer, number) + return out or buffer.create(0), 0 + end, + seek = function() end, + position = function(): number + return 0 + end, + } + return empty + end + return dec +end + +local function summarize(midi: Types.Midi) + local tempos, sigs, keys = {}, {}, {} + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + for _, ev in t.events do + if ev.type == "meta" then + local d = ev.data :: { number } + if ev.meta == 0x51 and #d >= 3 then + table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) + elseif ev.meta == 0x58 and #d >= 4 then + table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) + elseif ev.meta == 0x59 and #d >= 2 then + table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) + end + end + end + end + midi.meta.tempos = tempos + midi.meta.timeSignatures = sigs + midi.meta.keySignatures = keys + midi.meta.length = Render.length(midi) +end + +function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local midi, err = Smf.read(r, opts) + if not midi then + return nil, err + end + summarize(midi) + midi.meta.source = { format = "midi", smf = midi.format } + midi.render = render + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?) + return Smf.write(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) +function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Midi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) +function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + return Render.decoder(midi, opts) +end + +-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) +function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number + return Render.seconds(Render.tempoMap(midi, track), tick) +end + +-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) +Midi.tempoMap = Render.tempoMap +Midi.seconds = Render.seconds + +-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +function Midi.length(midi: Types.Midi): number + return Render.length(midi) +end + +-- text(data) -> the bytes of a text meta event as a string +Midi.text = Smf.text + +return Midi diff --git a/src/Formats/music/sf2/init.luau b/src/Formats/music/sf2/init.luau new file mode 100644 index 0000000..a7fcc20 --- /dev/null +++ b/src/Formats/music/sf2/init.luau @@ -0,0 +1,44 @@ +--!strict +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/SoundFont (the +-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), +-- presets / instruments / sample headers with global zones, generator merging into playable regions. +-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). +-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local SoundFont = require("@formats/codecs/SoundFont") + +-- ------------------------------------------------------------------------------------------------ contract +local Sf2 = { + name = "sf2", + category = "music", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxRegions: number?, -- default 10^6 + maxSamples: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Sf2.sniff(r: Bytes.Reader): number + return if SoundFont.sniff(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?) + return SoundFont.parse(r, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/SoundFont.Synth drives it) +Sf2.synth = SoundFont.synth +Sf2.fallback = SoundFont.fallback + +return Sf2 diff --git a/tests/music/midi.luau b/tests/music/midi.luau new file mode 100644 index 0000000..a906337 --- /dev/null +++ b/tests/music/midi.luau @@ -0,0 +1,272 @@ +-- music/midi tests: SMF formats 0 / 1 / 2 + SMPTE + RMID parsed exactly as python mido parses them, mido's own files +-- re-encoded byte for byte, round trips without running status, the tempo map against mido's message times and +-- lengths, meta summaries, crafted bad files, truncation (lenient / strict), the fallback-synth render (duration, +-- level, seek), and the fuzz no-throw pass (decode, and decode + a short render). Fixtures: tools/fixtures/midi.py. +local T = require("@tests/T") +local Midi = require("@formats/music/midi") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/midi_cases") +local Bad = require("@tests/gen/midi_bad") +local Trunc = require("@tests/gen/midi_trunc") + +local t = T.suite("midi") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Midi.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Midi.name, "midi", "name") +t:eq(Midi.category, "music", "category") +t:check(table.find(Midi.extensions, "mid") ~= nil, "extensions") +t:check(Midi.caps.decode and Midi.caps.encode, "caps") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("MThd\0\0\0\6"))), 1, "sniff MThd") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0RMID"))), 1, "sniff RMID") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE") + +local function sameEvents(got: { any }, want: { any }, label: string) + t:eq(#got, #want, label .. ": event count") + for i, w in want do + local g = got[i] + local l = label .. " event " .. i + t:eq(g.tick, w[1], l .. " tick") + t:eq(g.type, w[2], l .. " type") + t:eq(g.channel or -1, w[3], l .. " channel") + t:eq(if g.type == "meta" then g.meta else -1, w[5], l .. " meta type") + local d = g.data or {} + t:eq(#d, #w[4], l .. " data length") + for k, v in w[4] do + if d[k] ~= v then + t:eq(d[k], v, l .. " data byte " .. k) + end + end + end +end + +local function trackEvents(m: any): { { any } } + local out = {} + for ti, tr in m.tracks do + local evs = {} + for _, ev in tr.events do + table.insert(evs, { ev.tick, ev.type, ev.channel or -1, ev.data or {}, if ev.type == "meta" then ev.meta else -1 }) + end + out[ti] = evs + end + return out +end + +local byName = {} +for _, c in Cases do + byName[c.name] = c + local m, err = decode(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:eq(m.kind, "midi", c.name .. ": kind") + t:eq(m.format, c.type, c.name .. ": format") + t:eq(m.division, c.division, c.name .. ": division") + t:eq(#m.tracks, #c.tracks, c.name .. ": tracks") + for ti, want in c.tracks do + sameEvents(m.tracks[ti].events, want, c.name .. " track " .. ti) + end + -- mido's own bytes come back exactly (running status as mido writes it) + if c.exact then + local out, eerr = Midi.encode(m) + t:check(out, c.name .. ": encode " .. tostring(eerr)) + t:eq(buffer.tostring(out :: buffer) == c.data, true, c.name .. ": re-encoded bytes equal mido's") + end + -- without running status: longer (or equal), and the same events + local plain = Midi.encode(m, { runningStatus = false }) :: buffer + local withRs = Midi.encode(m) :: buffer + t:check(buffer.len(plain) >= buffer.len(withRs), c.name .. ": running status saves bytes") + local back = decode(plain) + t:check(back, c.name .. ": re-decode") + for ti, want in trackEvents(m) do + sameEvents(back.tracks[ti].events, want, c.name .. " round trip track " .. ti) + end + -- tempo map: every event's time against mido's merged message times + if c.times then + local secs = {} + for _, tr in m.tracks do + for _, ev in tr.events do + if not (ev.type == "meta" and ev.meta == 0x2F) then -- mido merges the end-of-track events into one + table.insert(secs, Midi.tickToSeconds(m, ev.tick)) + end + end + end + table.sort(secs) + t:eq(#secs, #c.times - 1, c.name .. ": event count vs mido") + local worst = 0 + for i, s in secs do + worst = math.max(worst, math.abs(s - c.times[i])) + end + t:check(worst < 1e-6, c.name .. ": event times match mido (worst " .. worst .. " s)") + t:check(math.abs(Midi.length(m) - c.length) < 1e-6, c.name .. ": length " .. Midi.length(m) .. " vs mido " .. c.length) + t:check(math.abs(m.meta.length - c.length) < 1e-6, c.name .. ": meta.length") + end +end +t:note("%d files parse as mido parses them; mido's files re-encode byte for byte", #Cases) + +-- meta summaries +do + local m = decode(byName.format0.data) + t:eq(m.tracks[1].name, "format zero", "track name") + t:eq(#m.meta.tempos, 3, "tempo changes") + t:eq(m.meta.tempos[1].usPerQuarter, 500000, "first tempo") + t:eq(m.meta.tempos[1].bpm, 120, "bpm") + t:eq(#m.meta.timeSignatures, 2, "time signatures") + t:eq(m.meta.timeSignatures[1].numerator, 3, "3/4 numerator") + t:eq(m.meta.timeSignatures[1].denominator, 4, "3/4 denominator") + t:eq(m.meta.timeSignatures[2].denominator, 8, "6/8 denominator") + t:eq(m.meta.keySignatures[1].sharps, -3, "Eb: 3 flats") + t:eq(m.meta.keySignatures[1].minor, false, "Eb major") + local s = decode(byName.smpte.data) + t:eq(s.meta.smpte.fps, 25, "smpte fps") + t:eq(s.meta.smpte.ticksPerFrame, 40, "smpte ticks per frame") + t:check(math.abs(Midi.tickToSeconds(s, 1000) - 1) < 1e-12, "smpte: 1000 ticks at 25 x 40 = 1 s") + t:eq(decode(byName.rmid.data).meta.rmid, true, "rmid flag") + -- format 2: per-track tempo maps, the tracks one after another + local f2 = decode(byName.format2.data) + local total = 0 + for ti, tr in f2.tracks do + local last = tr.events[#tr.events].tick + total += Midi.tickToSeconds(f2, last, ti) + end + t:check(math.abs(Midi.length(f2) - total) < 1e-9, "format 2 length = the tracks in sequence") +end + +-- a value built by hand: unsorted events are written in tick order, end of track added, bad values refused +do + local m = Types.Midi.new(96) + m.format = 0 + m.tracks[1] = { events = { + { tick = 50, type = "noteOff", channel = 2, data = { 60, 0 } }, + { tick = 0, type = "noteOn", channel = 2, data = { 60, 100 } }, + { tick = 50, type = "meta", meta = 0x2F, data = {} }, + { tick = 20, type = "controller", channel = 2, data = { 64, 127 } }, + } } + local b = Midi.encode(m) :: buffer + local back = decode(b) + sameEvents(back.tracks[1].events, { + { 0, "noteOn", 2, { 60, 100 }, -1 }, { 20, "controller", 2, { 64, 127 }, -1 }, { 50, "noteOff", 2, { 60, 0 }, -1 }, + { 50, "meta", -1, {}, 0x2F }, + }, "sorted on write") + local function refuses(mut: (any) -> (), label: string) + local x = Types.Midi.new(96) + x.tracks[1] = { events = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } } } } + mut(x) + local out, err = Midi.encode(x) + t:check(out == nil and Err.is(err) and err.code == Err.ARG, "encode refuses " .. label) + end + refuses(function(x) x.tracks[1].events[1].channel = 16 end, "channel 16") + refuses(function(x) x.tracks[1].events[1].data = { 60, 128 } end, "data byte 128") + refuses(function(x) x.tracks[1].events[1].tick = -1 end, "negative tick") + refuses(function(x) x.tracks[1].events[1].type = "wobble" end, "unknown type") + refuses(function(x) x.division = 0 end, "zero division") + refuses(function(x) x.format = 0; x.tracks[2] = { events = {} } end, "format 0 with two tracks") + local nope, nerr = Midi.encode(nil :: any) + t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil") +end + +-- crafted bad files +for _, c in Bad do + local ok, m, err = pcall(decode, c.data) + t:check(ok, c.name .. ": threw " .. tostring(m)) + t:check(m == nil and Err.is(err), c.name .. ": decoded") + t:eq(err.code, c.code, c.name .. ": error code (" .. tostring(err) .. ")") +end + +-- truncation: lenient keeps what it read, strict fails +do + local m = decode(Trunc.data) + t:check(m and m.meta.truncated, "truncated file decodes leniently, flagged") + local n = 0 + for _, tr in m.tracks do + n += #tr.events + end + t:check(n > 50, "truncated file keeps its events (" .. n .. ")") + local s, err = decode(Trunc.data, { strict = true }) + t:check(s == nil and err.code == Err.TRUNCATED, "strict: TRUNCATED") + t:eq(decode(byName.format1.data, { strict = true }).meta.truncated, false, "strict: a whole file passes") + local l, lerr = decode(byName.random.data, { maxEvents = 100 }) + t:check(l == nil and lerr.code == Err.LIMIT, "maxEvents: LIMIT") +end + +-- render through the built-in waveform set +do + local song = decode(byName.song.data) + local dec = song:render({ tail = 0.5 }) + local want = math.ceil((byName.song.length + 0.5) * 44100) + t:eq(dec.frames, want, "render: frames = (length + tail) * rate") + t:eq(dec.channels, 2, "render: stereo") + t:eq(dec.sampleRate, 44100, "render: rate") + local total, sumsq, peak = 0, 0, 0 + local out = buffer.create(4096 * 8) + while true do + local b, n = dec:read(4096, out) + if n == 0 then + break + end + for i = 0, n * 2 - 1 do + local v = buffer.readf32(b, i * 4) + sumsq += v * v + peak = math.max(peak, math.abs(v)) + end + total += n + end + t:eq(total, want, "render: reads every frame") + local rms = math.sqrt(sumsq / (total * 2)) + t:check(rms > 0.01 and peak < 4 and peak == peak, string.format("render: audible and sane (rms %.3f, peak %.3f)", rms, peak)) + t:note("fallback render: %.2f s, rms %.3f, peak %.3f", total / 44100, rms, peak) + -- seek: the same samples as playing through + local a = song:render({ tail = 0.5 }) + a:seek(1.5) + t:check(math.abs(a:position() - 1.5) < 1e-4, "seek position") + local x = buffer.create(1024 * 8) + a:read(1024, x) + local c = song:render({ tail = 0.5 }) + c:read(66150) + local y = c:read(1024) + local same = true + for i = 0, 2047 do + if buffer.readf32(x, i * 4) ~= buffer.readf32(y, i * 4) then + same = false + break + end + end + t:check(same, "seek renders the same samples as reading through") + a:seek(0.25) -- backwards + t:check(math.abs(a:position() - 0.25) < 1e-4, "seek backwards") + -- open = decode + render + local o = Midi.open(Bytes.reader(buffer.fromstring(byName.song.data)), { sampleRate = 22050, tail = 0 }) + t:check(o and o.sampleRate == 22050, "open: a Decoder at the asked rate") + local bad, berr = Midi.render(song, { sampleRate = 5 }) + t:check(bad == nil and berr.code == Err.ARG, "render: bad sampleRate") + local bs, bserr = Midi.render(song, { soundfont = "not a soundfont" }) + t:check(bs == nil and Err.is(bserr), "render: bad soundfont bytes") +end + +-- the fuzz no-throw pass +local samples = {} +for _, c in Cases do + if #c.data < 20000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return decode(b) +end, samples, { mutations = 40 }) +t:fuzz("decode + render", function(b: buffer) + local m = decode(b) + if m then + local dec = Midi.render(m, { tail = 0.1 }) + if dec then + dec:read(2048) + dec:read(2048) + end + Midi.encode(m) + end +end, samples, { mutations = 20, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/_midi_ref.py b/tools/fixtures/_midi_ref.py new file mode 100644 index 0000000..dd17630 --- /dev/null +++ b/tools/fixtures/_midi_ref.py @@ -0,0 +1,183 @@ +# MIDI reference cases (run by tools/fixtures/midi.py through ctx.python(["mido"], ...); not a generator itself). +# Builds Standard MIDI Files with python mido (formats 0 / 1 / 2, tempo changes, time / key signatures, running +# status, sysex, pitch bend, every channel message, a random stress file), saves them with mido, and prints JSON: +# per file the bytes, mido's parse in formats-luau's event shape and mido's lengths / message times. +import io, json, random, sys +import mido +from mido import Message, MetaMessage, MidiFile, MidiTrack + + +def ours(msg): + """a mido message -> [type, channel, data, meta] in formats-luau's shape (data = raw bytes)""" + t = msg.type + if msg.is_meta: + b = msg.bytes() + i = 2 + while b[i] & 0x80: + i += 1 + return ["meta", -1, list(b[i + 1:]), b[1]] + if t == "sysex": + return ["sysex", -1, list(msg.data) + [0xF7], -1] + if t == "note_on": + return ["noteOn", msg.channel, [msg.note, msg.velocity], -1] + if t == "note_off": + return ["noteOff", msg.channel, [msg.note, msg.velocity], -1] + if t == "polytouch": + return ["aftertouch", msg.channel, [msg.note, msg.value], -1] + if t == "control_change": + return ["controller", msg.channel, [msg.control, msg.value], -1] + if t == "program_change": + return ["program", msg.channel, [msg.program], -1] + if t == "aftertouch": + return ["channelPressure", msg.channel, [msg.value], -1] + if t == "pitchwheel": + v = msg.pitch + 8192 + return ["pitchBend", msg.channel, [v & 127, v >> 7], -1] + raise ValueError(t) + + +def describe(name, mid): + buf = io.BytesIO() + mid.save(file=buf) + data = buf.getvalue() + back = MidiFile(file=io.BytesIO(data)) + tracks = [] + for tr in back.tracks: + tick, evs = 0, [] + for msg in tr: + tick += msg.time + evs.append([tick] + ours(msg)) + tracks.append(evs) + case = {"name": name, "hex": data.hex(), "type": back.type, "division": back.ticks_per_beat, "tracks": tracks} + if back.type != 2 and back.ticks_per_beat > 0: + case["length"] = back.length + t, times = 0.0, [] + for msg in back: + t += msg.time + times.append(t) + case["times"] = times + return case + + +def notes(track, ch, rng, n, prog=None, start=0): + if prog is not None: + track.append(Message("program_change", channel=ch, program=prog, time=start)) + start = 0 + for i in range(n): + note = rng.randint(30, 90) + track.append(Message("note_on", channel=ch, note=note, velocity=rng.randint(1, 127), time=start if i == 0 else rng.randint(0, 120))) + track.append(Message("note_off", channel=ch, note=note, velocity=rng.randint(0, 127), time=rng.randint(1, 480))) + + +cases = [] +rng = random.Random(7) + +# format 0: one track with everything +mid = MidiFile(type=0, ticks_per_beat=480) +t = MidiTrack() +mid.tracks.append(t) +t.append(MetaMessage("track_name", name="format zero")) +t.append(MetaMessage("set_tempo", tempo=500000)) +t.append(MetaMessage("time_signature", numerator=3, denominator=4, clocks_per_click=24, notated_32nd_notes_per_beat=8)) +t.append(MetaMessage("key_signature", key="Eb")) +t.append(MetaMessage("text", text="hello")) +t.append(Message("program_change", channel=0, program=5)) +t.append(Message("control_change", channel=0, control=7, value=100)) +t.append(Message("control_change", channel=0, control=10, value=20)) +t.append(Message("note_on", channel=0, note=60, velocity=100, time=0)) +t.append(Message("note_on", channel=0, note=64, velocity=90, time=10)) # running status +t.append(Message("note_on", channel=0, note=67, velocity=80, time=10)) +t.append(Message("pitchwheel", channel=0, pitch=-8192, time=100)) +t.append(Message("pitchwheel", channel=0, pitch=8191, time=100)) +t.append(Message("pitchwheel", channel=0, pitch=0, time=100)) +t.append(Message("polytouch", channel=0, note=60, value=33, time=5)) +t.append(Message("aftertouch", channel=0, value=44, time=5)) +t.append(Message("sysex", data=[0x7E, 0x7F, 0x09, 0x01], time=0)) +t.append(MetaMessage("set_tempo", tempo=300000, time=240)) +t.append(Message("note_off", channel=0, note=60, velocity=0, time=480)) +t.append(Message("note_on", channel=0, note=64, velocity=0, time=0)) # note on, velocity 0 +t.append(Message("note_off", channel=0, note=67, velocity=64, time=0)) +t.append(Message("note_on", channel=9, note=36, velocity=127, time=100)) +t.append(Message("note_off", channel=9, note=36, velocity=0, time=100)) +t.append(MetaMessage("time_signature", numerator=6, denominator=8, time=0)) +t.append(MetaMessage("set_tempo", tempo=1000000, time=10)) +t.append(Message("note_on", channel=1, note=72, velocity=50, time=0)) +t.append(Message("note_off", channel=1, note=72, velocity=50, time=960)) +cases.append(describe("format0", mid)) + +# format 1: a conductor track + 3 instrument tracks, tempo changes in the conductor +mid = MidiFile(type=1, ticks_per_beat=96) +cond = MidiTrack() +mid.tracks.append(cond) +cond.append(MetaMessage("track_name", name="conductor")) +cond.append(MetaMessage("time_signature", numerator=4, denominator=4)) +for i, tempo in enumerate([500000, 400000, 600000, 250000, 750000]): + cond.append(MetaMessage("set_tempo", tempo=tempo, time=0 if i == 0 else 384)) +for ch in range(3): + tr = MidiTrack() + mid.tracks.append(tr) + tr.append(MetaMessage("track_name", name="part %d" % ch)) + notes(tr, ch, rng, 40, prog=ch * 10) +cases.append(describe("format1", mid)) + +# format 2: independent patterns, each with its own tempo +mid = MidiFile(type=2, ticks_per_beat=240) +for k in range(3): + tr = MidiTrack() + mid.tracks.append(tr) + tr.append(MetaMessage("set_tempo", tempo=400000 + 100000 * k)) + notes(tr, k, rng, 10) +cases.append(describe("format2", mid)) + +# a random stress file: many tracks / channels / controller streams (long running-status runs) +mid = MidiFile(type=1, ticks_per_beat=480) +for k in range(6): + tr = MidiTrack() + mid.tracks.append(tr) + if k == 0: + for j in range(20): + tr.append(MetaMessage("set_tempo", tempo=rng.randint(200000, 1500000), time=rng.randint(0, 2000))) + continue + ch = rng.randint(0, 15) + for j in range(400): + r = rng.random() + dt = rng.choice([0, 0, 1, 7, 120, 480, 20000]) + if r < 0.4: + tr.append(Message("note_on", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt)) + elif r < 0.6: + tr.append(Message("note_off", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt)) + elif r < 0.8: + tr.append(Message("control_change", channel=ch, control=rng.randint(0, 127), value=rng.randint(0, 127), time=dt)) + elif r < 0.9: + tr.append(Message("pitchwheel", channel=ch, pitch=rng.randint(-8192, 8191), time=dt)) + elif r < 0.95: + tr.append(Message("program_change", channel=ch, program=rng.randint(0, 127), time=dt)) + else: + tr.append(Message("sysex", data=[rng.randint(0, 127) for _ in range(rng.randint(0, 200))], time=dt)) +cases.append(describe("random", mid)) + +# SMPTE time (25 fps, 40 ticks per frame): division = -(25 << 8) + 40 as a signed 16-bit value +mid = MidiFile(type=0, ticks_per_beat=-6360) +t = MidiTrack() +mid.tracks.append(t) +t.append(Message("note_on", note=60, velocity=64, time=0)) +t.append(Message("note_off", note=60, velocity=64, time=1000)) +cases.append(describe("smpte", mid)) + +# the song the fallback / SoundFont render tests play (tools/fixtures/sf2.py has its own); its mido length +mid = MidiFile(type=1, ticks_per_beat=480) +cond = MidiTrack() +mid.tracks.append(cond) +cond.append(MetaMessage("set_tempo", tempo=500000)) +cond.append(MetaMessage("set_tempo", tempo=250000, time=1920)) +tr = MidiTrack() +mid.tracks.append(tr) +notes(tr, 0, rng, 12, prog=0) +dr = MidiTrack() +mid.tracks.append(dr) +for k in range(16): + dr.append(Message("note_on", channel=9, note=[36, 38, 42, 46][k % 4], velocity=110, time=0 if k == 0 else 120)) + dr.append(Message("note_off", channel=9, note=[36, 38, 42, 46][k % 4], velocity=0, time=120)) +cases.append(describe("song", mid)) + +json.dump(cases, sys.stdout) diff --git a/tools/fixtures/midi.py b/tools/fixtures/midi.py new file mode 100644 index 0000000..d1f47c5 --- /dev/null +++ b/tools/fixtures/midi.py @@ -0,0 +1,72 @@ +# MIDI fixtures (tools/fixtures.py). Reference parses from python mido (tools/fixtures/_midi_ref.py, run in a nix +# python with mido) plus hand-made byte strings for what mido does not write. +# tests/gen/midi_cases.luau { { name, data, type, division, tracks = { { {tick, type, channel, data, meta} } }, +# length?, times?, exact? } }: channel / meta = -1 when absent; exact = the bytes are +# what an encoder with running status writes (mido's own output) +# tests/gen/midi_bad.luau { { name, data, code } }: crafted bad files and the Err code expected +# tests/gen/midi_trunc.luau { name, data }: a mido file cut short (lenient decode keeps the events, strict fails) +import json, struct + +INPUTS = ["tools/fixtures/_midi_ref.py"] + + +def vlq(v): + out = [v & 127] + v >>= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def smf(tracks, fmt=0, division=96, extra=b""): + out = b"MThd" + struct.pack(">IHHh", 6, fmt, len(tracks), division) + extra + for body in tracks: + out += b"MTrk" + struct.pack(">I", len(body)) + body + return out + + +def generate(ctx): + ref = json.loads(ctx.python(["mido"], ctx.read("tools/fixtures/_midi_ref.py").decode())) + cases = [] + by_name = {} + for c in ref: + case = {"name": c["name"], "data": bytes.fromhex(c["hex"]), "type": c["type"], "division": c["division"], + "tracks": c["tracks"], "exact": True} + if "length" in c: + case["length"] = c["length"] + case["times"] = c["times"] + cases.append(case) + by_name[c["name"]] = case + + # running status across meta and escape events (mido's writer never relies on it), and an F7 escape + body = (b"\x00\x90\x3c\x40" + b"\x00\xff\x01\x01\x41" + b"\x10\x3c\x00" + b"\x00\xf7\x02\xf3\x01" + b"\x05\x3e\x7f" + + b"\x00\xff\x2f\x00") + cases.append({"name": "running-after-meta", "data": smf([body]), "type": 0, "division": 96, "exact": False, "tracks": [[ + [0, "noteOn", 0, [60, 64], -1], [0, "meta", -1, [0x41], 1], [16, "noteOn", 0, [60, 0], -1], + [16, "escape", -1, [0xF3, 0x01], -1], [21, "noteOn", 0, [62, 127], -1], [21, "meta", -1, [], 0x2F]]]}) + # an unknown chunk between MThd and MTrk, a longer MThd, and an RMID wrapper + f0 = by_name["format0"] + raw = f0["data"] + hdr, rest = raw[:14], raw[14:] + cases.append(dict(f0, name="unknown-chunk", exact=False, data=hdr + b"XFIH" + struct.pack(">I", 5) + b"abcde" + rest)) + long_hdr = b"MThd" + struct.pack(">I", 8) + raw[8:14] + b"\x00\x00" + rest + cases.append(dict(f0, name="long-mthd", exact=False, data=long_hdr)) + riff = b"RMID" + b"data" + struct.pack("IHHh", 6, 3, 0, 96), "code": "UNSUPPORTED"}, + {"name": "zero-division", "data": b"MThd" + struct.pack(">IHHh", 6, 0, 0, 0), "code": "CORRUPT"}, + {"name": "short-header", "data": b"MThd\x00\x00\x00\x06\x00", "code": "TRUNCATED"}, + {"name": "system-common", "data": smf([b"\x00\xf2\x01\x02"]), "code": "CORRUPT"}, + {"name": "rmid-without-data", "data": b"RIFF\x0c\x00\x00\x00RMIDLIST\x00\x00\x00\x00", "code": "CORRUPT"}, + ] + ctx.emit("midi_bad", bad) + f1 = by_name["format1"]["data"] + ctx.emit("midi_trunc", {"name": "format1-cut", "data": f1[: len(f1) * 3 // 5]}) From 064af84d63d290a385b63f69049a659a94a9438b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:37:32 -0500 Subject: [PATCH 06/28] 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 315e819b01e1b0d0f376c371dfcee6dd8f018c19 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:38:56 -0500 Subject: [PATCH 07/28] ws-audio: audio/aiff (AIFF/AIFC incl. sowt/fl32/fl64/ulaw/alaw), audio/au, audio/voc: decode/open/encode; codecs/Pcm folder (+ Convert: raw sample formats <-> f32, G.711, rawDecoder/audioDecoder/encode); fixtures vs ffmpeg/sox, encoder outputs decoded by ffmpeg in the fixture step --- docs/FORMATS.md | 5 +- src/Formats/Registry.luau | 36 ++ src/Formats/audio/aiff/init.luau | 384 ++++++++++++++++++ src/Formats/audio/au/init.luau | 166 ++++++++ src/Formats/audio/voc/init.luau | 278 +++++++++++++ src/Formats/codecs/Pcm/Convert.luau | 308 ++++++++++++++ .../codecs/{Pcm.luau => Pcm/init.luau} | 93 ++++- tests/audio/aiff.luau | 183 +++++++++ tests/audio/au.luau | 147 +++++++ tests/audio/voc.luau | 129 ++++++ tools/fixtures/_audio.py | 80 ++++ tools/fixtures/aiff.py | 51 +++ tools/fixtures/au.py | 47 +++ tools/fixtures/voc.py | 39 ++ 14 files changed, 1940 insertions(+), 6 deletions(-) create mode 100644 src/Formats/audio/aiff/init.luau create mode 100644 src/Formats/audio/au/init.luau create mode 100644 src/Formats/audio/voc/init.luau create mode 100644 src/Formats/codecs/Pcm/Convert.luau rename src/Formats/codecs/{Pcm.luau => Pcm/init.luau} (56%) create mode 100644 tests/audio/aiff.luau create mode 100644 tests/audio/au.luau create mode 100644 tests/audio/voc.luau create mode 100644 tools/fixtures/aiff.py create mode 100644 tools/fixtures/au.py create mode 100644 tools/fixtures/voc.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 1df48b9..049bd15 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,9 +6,12 @@ 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 | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | +| audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` | +| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | 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 -- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples. +- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..2eaac3a 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 = "aiff", + category = "audio", + path = "audio/aiff", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return require("@formats/audio/aiff") + end, + }, + { + name = "au", + category = "audio", + path = "audio/au", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return require("@formats/audio/au") + end, + }, + { + name = "voc", + category = "audio", + path = "audio/voc", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, + load = function() + return require("@formats/audio/voc") + end, + }, } return list diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau new file mode 100644 index 0000000..94b02c2 --- /dev/null +++ b/src/Formats/audio/aiff/init.luau @@ -0,0 +1,384 @@ +--!strict +-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. +-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw +-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated +-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / +-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. Not supported: compressed AIFF-C codecs (ima4, MAC3 / +-- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Aiff = { + name = "aiff", + category = "audio", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" + littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only + -- take 16-bit sowt, so other formats return Err.ARG) + aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } +local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } +local AIFC_VERSION = 0xA2805140 + +-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) +local function ext80(b: buffer, o: number): number + local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) + local hi = bit32.byteswap(buffer.readu32(b, o + 2)) + local lo = bit32.byteswap(buffer.readu32(b, o + 6)) + local e = bit32.band(se, 0x7FFF) + if e == 0 and hi == 0 and lo == 0 then + return 0 + end + if e == 0x7FFF then + return math.huge + end + local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) + return if se >= 0x8000 then -v else v +end + +-- the 10 bytes of x (> 0) as an 80-bit extended float +local function writeExt80(w: Bytes.Writer, x: number) + if x <= 0 or x ~= x then + w:fill(0, 10) + return + end + local e = 0 + while x >= 2 ^ (e + 1) do + e += 1 + end + while x < 2 ^ e do + e -= 1 + end + local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local hi = math.floor(m / 4294967296) + local lo = m - hi * 4294967296 + w:u16be(e + 16383) + w:u32be(hi) + w:u32be(math.floor(lo)) +end + +-- the sample format of a COMM chunk: Pcm format name | nil, message +local function sampleFormat(comp: string, bits: number): (string?, string?) + if comp == "NONE" or comp == "twos" or comp == "" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16be" + elseif bits <= 24 then + return "s24be" + elseif bits <= 32 then + return "s32be" + end + return nil, "bad sample size " .. bits + elseif comp == "sowt" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16le" + elseif bits <= 24 then + return "s24le" + elseif bits <= 32 then + return "s32le" + end + return nil, "bad sample size " .. bits + elseif comp == "raw " then + return "u8" + elseif comp == "in24" then + return "s24be" + elseif comp == "in32" then + return "s32be" + elseif comp == "42ni" then + return "s32le" + elseif comp == "fl32" or comp == "FL32" then + return "f32be" + elseif comp == "fl64" or comp == "FL64" then + return "f64be" + elseif comp == "ulaw" or comp == "ULAW" then + return "ulaw" + elseif comp == "alaw" or comp == "ALAW" then + return "alaw" + end + return nil, "compression " .. string.format("%q", comp) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Aiff.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "FORM" then + return 0 + end + local form = buffer.readstring(r.buf, r.pos + 8, 4) + return if form == "AIFF" or form == "AIFC" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + channels: number, + frames: number, + sampleRate: number, + bits: number, + format: string, + compression: string, + aifc: boolean, + dataOffset: number, -- absolute in r.buf + truncated: boolean, + tags: Types.Tags, +} + +-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b = r.buf + local base, limit = r.base, r.limit + if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not a FORM file", base) + end + local form = buffer.readstring(b, base + 8, 4) + if form ~= "AIFF" and form ~= "AIFC" then + return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) + end + local aifc = form == "AIFC" + local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) + local info: Info? = nil + local comm = false + local ssnd: number? = nil + local ssndLen = 0 + local tags: Types.Tags = {} + local p = base + 12 + while p + 8 <= formEnd do + local id = buffer.readstring(b, p, 4) + local len = bit32.byteswap(buffer.readu32(b, p + 4)) + local d = p + 8 + local avail = math.min(len, limit - d) + if id == "COMM" then + if avail < 18 or (aifc and avail < 22) then + return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p) + end + local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) + local frames = bit32.byteswap(buffer.readu32(b, d + 2)) + local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) + local rate = ext80(b, d + 8) + local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE" + if ch < 1 then + return nil, Err.new(Err.CORRUPT, "no channels", d) + end + if not (rate > 0 and rate < 2 ^ 31) then + return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) + end + local fmt, why = sampleFormat(comp, bits) + if not fmt then + return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18) + end + info = { + channels = ch, + frames = frames, + sampleRate = rate, + bits = bits, + format = fmt, + compression = comp, + aifc = aifc, + dataOffset = 0, + truncated = false, + tags = tags, + } + comm = true + elseif id == "SSND" then + if avail < 8 then + return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) + end + local off = bit32.byteswap(buffer.readu32(b, d)) + ssnd = d + 8 + off + ssndLen = math.max(0, avail - 8 - off) + if len >= 8 + off then + ssndLen = math.min(ssndLen, len - 8 - off) + end + elseif TEXT_TAGS[id] then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + local key = TEXT_TAGS[id] + tags[key] = if tags[key] then tags[key] .. "\n" .. s else s + end + if len > formEnd - d then + break + end + p = d + len + len % 2 + end + if not comm or not info then + return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) + end + local fi = info :: Info + if fi.frames > 0 and not ssnd then + return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) + end + local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format] + local present = if ssnd then ssndLen // frameBytes else 0 + if present < fi.frames then + fi.frames = present + fi.truncated = true + end + fi.dataOffset = ssnd or base + return fi, nil +end + +-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err +function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Aiff.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local FORMATS = { + s8 = { "s8", 8, "NONE" }, + s16 = { "s16be", 16, "NONE" }, + s24 = { "s24be", 24, "NONE" }, + s32 = { "s32be", 32, "NONE" }, + f32 = { "f32be", 32, "fl32" }, + f64 = { "f64be", 64, "fl64" }, + ulaw = { "ulaw", 16, "ulaw" }, + alaw = { "alaw", 16, "alaw" }, +} +local LE = { s16be = "s16le" } +local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } + +function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = FORMATS[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + local fmt, bits, comp = spec[1], spec[2], spec[3] + if o.littleEndian then + if not LE[fmt] then + return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") + end + fmt, comp = LE[fmt], "sowt" + end + if src.channels > 65535 then + return nil, Err.new(Err.ARG, "too many channels") + end + local aifc = o.aifc or comp ~= "NONE" + local w = Bytes.writer(65536) + w:string("FORM") + w:u32be(0) -- patched + w:string(if aifc then "AIFC" else "AIFF") + if aifc then + w:string("FVER") + w:u32be(4) + w:u32be(AIFC_VERSION) + end + -- text chunks from the tags + for _, pair in TEXT_ORDER do + local id, key = pair[1], pair[2] + local s = src.tags[key] + if type(s) == "string" and #s > 0 then + w:string(id) + w:u32be(#s) + w:string(s) + if #s % 2 == 1 then + w:u8(0) + end + end + end + local commAt = w:tell() + w:string("COMM") + if aifc then + local name = COMP_NAMES[comp] or "" + local plen = 1 + #name + plen += plen % 2 + w:u32be(22 + plen) + else + w:u32be(18) + end + w:u16be(src.channels) + w:u32be(0) -- frames, patched + w:u16be(bits) + writeExt80(w, src.sampleRate) + if aifc then + w:string(comp) + local name = COMP_NAMES[comp] or "" + w:u8(#name) + w:string(name) + if (1 + #name) % 2 == 1 then + w:u8(0) + end + end + local ssndAt = w:tell() + w:string("SSND") + w:u32be(0) -- patched + w:u32be(0) -- offset + w:u32be(0) -- block size + local frames, perr = Pcm.encode(src, fmt, w) + if not frames then + return nil, perr + end + local dataLen = w:tell() - ssndAt - 16 + if dataLen % 2 == 1 then + w:u8(0) + end + w:setU32be(ssndAt + 4, dataLen + 8) + w:setU32be(commAt + 10, frames) + w:setU32be(4, w:tell() - 8) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local info, err = parse(r) + if not info then + return nil, err + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if info.frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { + format = "aiff", + aifc = info.aifc, + compression = info.compression, + bitDepth = info.bits, + sampleFormat = info.format, + truncated = info.truncated or nil, + } + return dec, nil +end + +return Aiff diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau new file mode 100644 index 0000000..0215799 --- /dev/null +++ b/src/Formats/audio/au/init.luau @@ -0,0 +1,166 @@ +--!strict +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. +-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), +-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); +-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Au = { + name = "au", + category = "audio", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS: { [number]: string } = { + [1] = "ulaw", + [2] = "s8", + [3] = "s16be", + [4] = "s24be", + [5] = "s32be", + [6] = "f32be", + [7] = "f64be", + [27] = "alaw", +} +local WRITE = { + ulaw = { 1, "ulaw" }, + s8 = { 2, "s8" }, + s16 = { 3, "s16be" }, + s24 = { 4, "s24be" }, + s32 = { 5, "s32be" }, + f32 = { 6, "f32be" }, + f64 = { 7, "f64be" }, + alaw = { 27, "alaw" }, +} +local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } + +local function be32(b: buffer, o: number): number + return bit32.byteswap(buffer.readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Au.sniff(r: Bytes.Reader): number + return if r:peek(4) == ".snd" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Au.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) + local note = if type(src.tags.comment) == "string" then src.tags.comment else "" + local alen = #note + 1 + alen = math.max(8, alen + (8 - alen % 8) % 8) + local w = Bytes.writer(65536) + w:string(".snd") + w:u32be(24 + alen) + w:u32be(0xFFFFFFFF) -- patched + w:u32be(spec[1]) + w:u32be(src.sampleRate) + w:u32be(src.channels) + w:string(note) + w:fill(0, alen - #note) + local frames, perr = Pcm.encode(src, spec[2], w) + if not frames then + return nil, perr + end + w:setU32be(8, w:tell() - 24 - alen) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) + local fmt = ENCODINGS[enc] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) + end + if ch < 1 or ch > 65535 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) + end + if rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) + end + if off < 24 or off > limit - base then + return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) + end + local tags: Types.Tags = {} + if off > 24 then + local s = buffer.readstring(b, base + 24, off - 24) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + if #s > 0 then + tags.comment = s + end + end + local avail = limit - base - off + local truncated = false + if size == 0xFFFFFFFF then + size = avail + elseif size > avail then + size = avail + truncated = true + end + local frameBytes = ch * Pcm.Convert.SIZE[fmt] + local frames = size // frameBytes + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } + return dec, nil +end + +return Au diff --git a/src/Formats/audio/voc/init.luau b/src/Formats/audio/voc/init.luau new file mode 100644 index 0000000..3feca49 --- /dev/null +++ b/src/Formats/audio/voc/init.luau @@ -0,0 +1,278 @@ +--!strict +-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. +-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), +-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit +-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played +-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version +-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM +-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Voc = { + name = "voc", + category = "audio", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Creative Voice File\26" +local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } +local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" } +local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } +local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) + +local readu8 = buffer.readu8 +local function u16(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 +end +local function u24(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Voc.sniff(r: Bytes.Reader): number + return if r:peek(20) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence + +function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local hsize = u16(b, base + 20) + local version = u16(b, base + 22) + if hsize < 26 or hsize > limit - base then + return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + local rate, channels = 0, 0 + local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block + local lastFmt: string? = nil + local codec = -1 + local segments: { Segment } = {} + local total = 0 + local truncated = false + local tags: Types.Tags = {} + local p = base + hsize + -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) + local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? + if channels == 0 then + channels, rate = ch, sr + elseif ch ~= channels then + return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) + end + local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes + if frames > 0 then + total += frames + if total > maxFrames then + return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) + end + table.insert(segments, { at = at, frames = frames, fmt = fmt }) + end + return nil + end + while p < limit do + local t = readu8(b, p) + if t == 0 then + break + end + if p + 4 > limit then + truncated = true + break + end + local size = u24(b, p + 1) + local d = p + 4 + local avail = math.min(size, limit - d) + if avail < size then + truncated = true + end + local err: Err.Err? = nil + if t == 1 then + if avail < 2 then + break + end + local div, c = readu8(b, d), readu8(b, d + 1) + local fmt = T1_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) + end + local ch, sr = 1, 1000000 // (256 - div) + if extChannels > 0 then + ch, sr = extChannels, extRate + extChannels = 0 + end + lastFmt, codec = fmt, c + err = add(d + 2, avail - 2, fmt, ch, sr) + elseif t == 2 then + if lastFmt == nil then + return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) + end + err = add(d, avail, lastFmt, channels, rate) + elseif t == 3 then + if avail < 3 then + break + end + local len, div = u16(b, d) + 1, readu8(b, d + 2) + err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div)) + elseif t == 5 then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + tags.comment = if tags.comment then tags.comment .. "\n" .. s else s + elseif t == 8 then + if avail < 4 then + break + end + local tc, mode = u16(b, d), readu8(b, d + 3) + extChannels = mode + 1 + extRate = 256000000 // (extChannels * (65536 - tc)) + elseif t == 9 then + if avail < 12 then + break + end + local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 + local ch, c = readu8(b, d + 5), u16(b, d + 6) + local fmt = T9_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) + end + if ch < 1 or sr < 1 then + return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) + end + lastFmt, codec = fmt, c + err = add(d + 12, avail - 12, fmt, ch, sr) + end + if err then + return nil, err + end + p = d + size + end + if channels == 0 then + return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p) + end + local a = Types.Audio.new(rate, channels, total) + local o = 0 + for _, s in segments do + local n = s.frames * channels + if s.fmt then + Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) + end -- silence: the buffer is already zero + o += n * 4 + end + a.tags = tags + a.meta.source = { + format = "voc", + version = string.format("%d.%02d", version // 256, version % 256), + codec = codec, + sampleFormat = lastFmt, + bitDepth = if lastFmt == "s16le" then 16 else 8, + truncated = truncated or nil, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + w:u16le(26) + w:u16le(0x0114) + w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 + if type(src.tags.comment) == "string" and #src.tags.comment > 0 then + local s = string.sub(src.tags.comment, 1, 0xFFFFFE) + w:u8(5) + w:u24le(#s + 1) + w:string(s) + w:u8(0) + end + local size = Pcm.Convert.SIZE[spec[2]] + local frameBytes = size * src.channels + local framesPerBlock = MAX_BLOCK // frameBytes + local blockAt, blockFrames = -1, 0 + local tmp: buffer? = nil + while true do + local bf, n = src:read(math.min(8192, framesPerBlock), tmp) + if n <= 0 then + break + end + tmp = bf + local i = 0 + while i < n do + if blockAt < 0 or blockFrames == framesPerBlock then + blockAt = w:tell() + blockFrames = 0 + w:u8(9) + w:u24le(0) -- patched + w:u32le(src.sampleRate) + w:u8(spec[3]) + w:u8(src.channels) + w:u16le(spec[1]) + w:u32le(0) + end + local take = math.min(n - i, framesPerBlock - blockFrames) + local at = w:reserve(take * frameBytes) + Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) + w.pos = at + take * frameBytes + blockFrames += take + i += take + local len = blockFrames * frameBytes + 12 + w:setU8(blockAt + 1, len % 256) + w:setU8(blockAt + 2, (len // 256) % 256) + w:setU8(blockAt + 3, len // 65536) + end + end + if src.err then + return nil, src.err + end + w:u8(0) -- terminator + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local a, err = Voc.decode(r, opts) + if not a then + return nil, err + end + local dec = Pcm.audioDecoder(a) :: any + dec.source = a.meta.source + return dec, nil +end + +return Voc diff --git a/src/Formats/codecs/Pcm/Convert.luau b/src/Formats/codecs/Pcm/Convert.luau new file mode 100644 index 0000000..5d88d6e --- /dev/null +++ b/src/Formats/codecs/Pcm/Convert.luau @@ -0,0 +1,308 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to +-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the +-- classic Sun g711.c algorithm, written from the spec). +-- +-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). +-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +local Convert = {} + +local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 +local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 +local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 +local floor = math.floor +local byteswap = bit32.byteswap + +local SIZE: { [string]: number } = { + u8 = 1, + s8 = 1, + s16le = 2, + s16be = 2, + s24le = 3, + s24be = 3, + s32le = 4, + s32be = 4, + f32le = 4, + f32be = 4, + f64le = 8, + f64be = 8, + alaw = 1, + ulaw = 1, +} +Convert.SIZE = SIZE +-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) +Convert.BITS = { + u8 = 8, + s8 = 8, + s16le = 16, + s16be = 16, + s24le = 24, + s24be = 24, + s32le = 32, + s32be = 32, + f32le = 32, + f32be = 32, + f64le = 64, + f64be = 64, + alaw = 16, + ulaw = 16, +} + +-- ------------------------------------------------------------------------------------------------ G.711 +local ALAW = table.create(256, 0) -- code -> linear s16 +local ULAW = table.create(256, 0) +for code = 0, 255 do + -- A-law + local a = bit32.bxor(code, 0x55) + local t = bit32.band(a, 0x0F) * 16 + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg == 0 then + t += 8 + elseif seg == 1 then + t += 0x108 + else + t = (t + 0x108) * 2 ^ (seg - 1) + end + ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t + -- mu-law + local u = bit32.bxor(code, 0xFF) + local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) + ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 +end + +local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } +local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } +local function segment(v: number, ends: { number }): number + for i = 1, 8 do + if v <= ends[i] then + return i - 1 + end + end + return 8 +end + +-- linear s16 -> A-law code +local function alawEncode(pcm: number): number + local mask + local v = floor(pcm / 8) -- 13-bit magnitude domain + if v >= 0 then + mask = 0xD5 + else + mask = 0x55 + v = -v - 1 + end + local seg = segment(v, SEG_AEND) + local aval + if seg >= 8 then + aval = 0x7F + else + aval = seg * 16 + if seg < 2 then + aval += bit32.band(floor(v / 2), 0x0F) + else + aval += bit32.band(floor(v / 2 ^ seg), 0x0F) + end + end + return bit32.bxor(aval, mask) +end + +-- linear s16 -> mu-law code +local function ulawEncode(pcm: number): number + local v = floor(pcm / 4) -- 14-bit + local mask + if v < 0 then + v = -v + mask = 0x7F + else + mask = 0xFF + end + if v > 8159 then + v = 8159 + end + v += 0x21 + local seg = segment(v, SEG_UEND) + local uval + if seg >= 8 then + uval = 0x7F + else + uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) + end + return bit32.bxor(uval, mask) +end +Convert.alawEncode = alawEncode +Convert.ulawEncode = ulawEncode +Convert.ALAW = ALAW +Convert.ULAW = ULAW + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] +function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local p = so + i * 2 + local v = readu8(src, p) * 256 + readu8(src, p + 1) + if v >= 32768 then + v -= 65536 + end + writef32(dst, d + i * 4, v / 32768) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi8(src, so + i) / 128) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + local v = byteswap(readu32(src, so + i * 4)) + if v >= 2147483648 then + v -= 4294967296 + end + writef32(dst, d + i * 4, v / 2147483648) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readf64(src, so + i * 8)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + local p = so + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, p + 4))) + writeu32(tmp, 4, byteswap(readu32(src, p))) + writef32(dst, d + i * 4, readf64(tmp, 0)) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) + end + else + return false + end + return true +end + +-- ------------------------------------------------------------------------------------------------ encode +local function q(x: number, s: number): number + local v = floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] +function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 32768) % 65536 + writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v % 256) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v // 65536) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v // 65536) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v % 256) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef64(dst, d + i * 8, readf32(src, so + i * 4)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + writef64(tmp, 0, readf32(src, so + i * 4)) + local p = d + i * 8 + writeu32(dst, p, byteswap(readu32(tmp, 4))) + writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) + end + else + return false + end + return true +end + +return Convert diff --git a/src/Formats/codecs/Pcm.luau b/src/Formats/codecs/Pcm/init.luau similarity index 56% rename from src/Formats/codecs/Pcm.luau rename to src/Formats/codecs/Pcm/init.luau index 077f6dc..8d60d05 100644 --- a/src/Formats/codecs/Pcm.luau +++ b/src/Formats/codecs/Pcm/init.luau @@ -1,20 +1,28 @@ --!strict --- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples. --- An encoder accepts a Types.Audio (fully decoded) or a --- Types.Decoder (streamed); Pcm.source turns either into one pull interface, so encoders stream in blocks without --- caring which they got. Also the float <-> integer sample conversions (the same rounding and clipping everywhere). +-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. +-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one +-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au, +-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder. -- -- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else -- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read +-- local audio = Pcm.collect(src) -- read everything into a Types.Audio +-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder +-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio +-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer +-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert) -- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] -- local x = Pcm.fromInt(s16, 16) -- s / 32768 --- local audio = Pcm.collect(src) -- read everything into a Types.Audio -- +-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. -- Never throws (a decoder's read that throws is caught and ends the stream). local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Convert = require("@formats/codecs/Pcm/Convert") local Pcm = {} +Pcm.Convert = Convert export type Source = { sampleRate: number, @@ -128,6 +136,81 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) return a, nil end +-- ------------------------------------------------------------------------------------------------ decoders +-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming +-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf) +function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then + return nil, Err.new(Err.ARG, "bad raw PCM layout") + end + local pos = 0 + local frameBytes = channels * size + local dec = { + sampleRate = sampleRate, + channels = channels, + frames = frames, + duration = frames / sampleRate, + bitrate = sampleRate * frameBytes * 8, + tags = tags or {}, + } + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.clamp(math.floor(n), 0, frames - pos) + local bytes = n * channels * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + if n > 0 then + Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) + pos += n + end + return b, n + end + function dec.seek(_self: any, seconds: number) + local f = math.floor(seconds * sampleRate + 0.5) + pos = if f ~= f then 0 else math.clamp(f, 0, frames) + end + function dec.position(_self: any): number + return pos / sampleRate + end + return dec :: any, nil +end + +-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) +function Pcm.audioDecoder(a: Types.Audio): Types.Decoder + local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any + d.bitrate = a.sampleRate * a.channels * 32 + return d +end + +-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples +function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + local ch = src.channels + local total = 0 + local tmp: buffer? = nil + while true do + local b, n = src:read(8192, tmp) + if n <= 0 then + break + end + tmp = b + local at = w:reserve(n * ch * size) + Convert.encode(b, 0, n * ch, fmt, w.buf, at) + w.pos = at + n * ch * size + total += n + end + if src.err then + return nil, src.err + end + return total, nil +end + +-- ------------------------------------------------------------------------------------------------ conversions -- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) function Pcm.toInt(x: number, bits: number): number local s = 2 ^ (bits - 1) diff --git a/tests/audio/aiff.luau b/tests/audio/aiff.luau new file mode 100644 index 0000000..079f34a --- /dev/null +++ b/tests/audio/aiff.luau @@ -0,0 +1,183 @@ +-- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C +-- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks; +-- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. +-- Fixtures: tools/fixtures/aiff.py. +local T = require("@tests/T") +local Aiff = require("@formats/audio/aiff") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/aiff_cases") +local Enc = require("@tests/gen/aiff_enc") +local Sig = require("@tests/gen/aiff_sig") + +local t = T.suite("aiff") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +-- max |a - b| over n f32 samples (a at byte ao, b at byte bo) +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +-- the contract +t:eq(Aiff.name, "aiff", "name") +t:eq(Aiff.category, "audio", "category") +t:check(Aiff.caps.decode and Aiff.caps.encode and table.find(Aiff.extensions, "aif") ~= nil, "caps / extensions") + +-- reference files: decode, stream, seek +for _, c in Cases do + local a, err = Aiff.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.kind == "audio" and a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + local n = c.frames * c.channels + t:check(maxDiff(a.samples, 0, ref, 0, n) < 1e-6, c.name .. ": samples match ffmpeg") + -- streaming in odd chunks + local dec = Aiff.open(reader(c.data)) :: Types.Decoder + local got, out = 0, buffer.create(0) + local ok = true + while true do + local b, k = dec:read(777, out) + if k == 0 then + break + end + out = b + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(1000 / c.rate) + t:check(math.abs(dec:position() - 1000 / c.rate) < 1e-9, c.name .. ": position") + local b, k = dec:read(50) + t:check(k == 50 and maxDiff(b, 0, ref, 1000 * c.channels * 4, 50 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- details of particular files +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end +do + local a = Aiff.decode(reader(case("ffmpeg-tags").data)) :: Types.Audio + t:eq(a.tags.title, "Song Name", "NAME chunk") + t:eq(a.tags.artist, "Some One", "AUTH chunk") + local fl = Aiff.decode(reader(case("ffmpeg-fl32").data)) :: Types.Audio + t:check(fl.meta.source.aifc and fl.meta.source.compression == "fl32", "fl32 meta") + -- a 12-bit sample size: samples sit left-justified in 16-bit containers + local s16 = case("sox-aiff-s16") + local q = string.find(s16.data, "COMM", 1, true) :: number + local d12 = string.sub(s16.data, 1, q + 13) .. "\0\12" .. string.sub(s16.data, q + 16) + local s12 = Aiff.decode(reader(d12)) :: Types.Audio + t:check(s12.meta.source.bitDepth == 12 and maxDiff(s12.samples, 0, buffer.fromstring(s16.ref), 0, s16.frames * 2) < 1e-6, "12-bit sample size") + local sw = Aiff.info(reader(case("ffmpeg-sowt").data)) + t:check(sw and sw.compression == "sowt" and sw.format == "s16le", "info: sowt") + -- inside a bigger buffer + local c = case("ffmpeg-s16be") + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local a2 = Aiff.decode(Bytes.reader(big, 5, #c.data)) :: Types.Audio + t:check(a2 and maxDiff(a2.samples, 0, buffer.fromstring(c.ref), 0, c.frames * c.channels) < 1e-6, "decode from a sub-range") + -- truncated sample data: the frames present + local cut = string.sub(c.data, 1, #c.data - 1001) + local a3 = Aiff.decode(reader(cut)) :: Types.Audio + t:check(a3 and a3.frames < c.frames and a3.frames > 0 and a3.meta.source.truncated, "truncated SSND") +end + +-- our encoder: ffmpeg decodes every sample format (fixture step), within the format's step; streamed == from Audio +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, sowt16 = 0.5 / 32768, ["aifc-s16"] = 0.5 / 32768, s24 = 0.5 / 8388608, sowt24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Aiff.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +-- encoder: tags, odd sizes, errors +do + local a = Types.Audio.new(44100, 1, 3) + buffer.writef32(a.samples, 0, 0.5) + buffer.writef32(a.samples, 4, -1) + buffer.writef32(a.samples, 8, 2) -- clips + a.tags = { title = "odd", artist = "me", comment = "x" } + local b = Aiff.encode(a, { sampleFormat = "s8" }) :: buffer + local back = Aiff.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 3 and back.tags.title == "odd" and back.tags.artist == "me" and back.tags.comment == "x", "odd length + tags") + t:check(buffer.readf32(back.samples, 0) == 0.5 and buffer.readf32(back.samples, 4) == -1 and buffer.readf32(back.samples, 8) == 127 / 128, "s8 values, clipping") + t:eq(buffer.len(b) % 2, 0, "chunks padded to even sizes") + t:check(Aiff.info(Bytes.reader(b)).sampleRate == 44100, "80-bit rate round trip") + local empty = Aiff.encode(Types.Audio.new(8000, 2, 0)) :: buffer + local e0 = Aiff.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty audio") + local _, e1 = Aiff.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Aiff.encode(a, { sampleFormat = "s12" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Aiff.encode(a, { sampleFormat = "f32", littleEndian = true }) + t:check(e3 and e3.code == Err.ARG, "littleEndian float: ARG") + local _, e5 = Aiff.encode(a, { sampleFormat = "s24", littleEndian = true }) + t:check(e5 and e5.code == Err.ARG, "littleEndian 24-bit: ARG") + t:eq(Aiff.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Aiff.sniff(reader("RIFF....WAVE")), 0, "sniff wav") + t:eq(Aiff.sniff(reader("")), 0, "sniff nothing") +end + +-- errors +do + local _, e = Aiff.decode(reader("FORM\0\0\0\4WAVE")) + t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e)) + local c = case("ffmpeg-fl32").data + local p = string.find(c, "fl32", 1, true) :: number + local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4) + local _, e2 = Aiff.decode(reader(ima)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2)) + local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30))) + t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3)) + local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxFrames: LIMIT") +end + +-- fuzz +do + local samples = {} + for i, c in Cases do + if i % 3 == 1 then + table.insert(samples, string.sub(c.data, 1, 600)) + end + end + t:fuzz("decode", function(b: buffer) + return Aiff.decode(Bytes.reader(b)) + end, samples, { mutations = 30, keepHeader = 0 }) + t:fuzz("open + read", function(b: buffer) + local d = Aiff.open(Bytes.reader(b)) + if d then + d:read(100) + d:seek(0.001) + d:read(100) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/au.luau b/tests/audio/au.luau new file mode 100644 index 0000000..c38e8c5 --- /dev/null +++ b/tests/audio/au.luau @@ -0,0 +1,147 @@ +-- audio/au tests: files written by ffmpeg and sox in every encoding (8 / 16 / 24 / 32-bit, float, double, mu-law, +-- A-law, an annotation) against ffmpeg's decode; streaming reads and seeks; our encoder's output for every encoding +-- decoded by ffmpeg (fixture step) and by us; an unknown data size; errors; fuzz. Fixtures: tools/fixtures/au.py. +local T = require("@tests/T") +local Au = require("@formats/audio/au") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/au_cases") +local Enc = require("@tests/gen/au_enc") +local Sig = require("@tests/gen/au_sig") + +local t = T.suite("au") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +t:eq(Au.name, "au", "name") +t:eq(Au.category, "audio", "category") +t:check(Au.caps.decode and Au.caps.encode and table.find(Au.extensions, "snd") ~= nil, "caps / extensions") + +for _, c in Cases do + local a, err = Au.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Au.open(reader(c.data)) :: Types.Decoder + local got, ok = 0, true + while true do + local b, k = dec:read(1000) + if k == 0 then + break + end + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(700 / c.rate) + local b, k = dec:read(40) + t:check(k == 40 and maxDiff(b, 0, ref, 700 * c.channels * 4, 40 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +do + local a = Au.decode(reader(case("sox-comment").data)) :: Types.Audio + t:check(a.tags.comment ~= nil and string.find(a.tags.comment, "hello sun", 1, true) ~= nil, "annotation as comment") + -- an unknown data size (0xFFFFFFFF) runs to the end of the file + local c = case("ffmpeg-s16be") + local unk = string.sub(c.data, 1, 8) .. "\255\255\255\255" .. string.sub(c.data, 13) + local a2 = Au.decode(reader(unk)) :: Types.Audio + t:check(a2 and a2.frames == c.frames, "unknown data size") + local cut = Au.decode(reader(string.sub(c.data, 1, #c.data - 400))) :: Types.Audio + t:check(cut and cut.frames == c.frames - 100 and cut.meta.source.truncated, "truncated data") + local big = buffer.create(#c.data + 3) + buffer.writestring(big, 3, c.data) + local a3 = Au.decode(Bytes.reader(big, 3, #c.data)) :: Types.Audio + t:check(a3 and maxDiff(a3.samples, 0, buffer.fromstring(c.ref), 0, c.frames * 2) < 1e-6, "decode from a sub-range") +end + +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, s24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Au.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(8000, 1, 2) + buffer.writef32(a.samples, 0, 0.25) + buffer.writef32(a.samples, 4, -0.25) + a.tags = { comment = "annotated!" } + local b = Au.encode(a) :: buffer + t:eq(bit32.byteswap(buffer.readu32(b, 4)) % 8, 0, "data offset is a multiple of 8") + local back = Au.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 2 and back.tags.comment == "annotated!" and buffer.readf32(back.samples, 0) == 0.25, "comment + samples") + local _, e1 = Au.encode(42 :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Au.encode(a, { sampleFormat = "u8" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local frac = Types.Audio.new(8000.5, 1, 1) + local _, e3 = Au.encode(frac) + t:check(e3 and e3.code == Err.ARG, "fractional rate: ARG") + t:eq(Au.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Au.sniff(reader("FORM")), 0, "sniff other") + -- G.721 ADPCM (encoding 23): unsupported + local adpcm = string.sub(buffer.tostring(b), 1, 12) .. "\0\0\0\23" .. string.sub(buffer.tostring(b), 17) + local _, e4 = Au.decode(reader(adpcm)) + t:check(e4 and e4.code == Err.UNSUPPORTED, "encoding 23: UNSUPPORTED") + local _, e5 = Au.decode(reader(".snd\0\0\0\24")) + t:check(e5 and e5.code == Err.CORRUPT, "short header: CORRUPT") + local _, e6 = Au.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 5 }) + t:check(e6 and e6.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for i, c in Cases do + if i % 2 == 1 then + table.insert(samples, string.sub(c.data, 1, 400)) + end + end + t:fuzz("decode", function(b: buffer) + return Au.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) + t:fuzz("open + read", function(b: buffer) + local d = Au.open(Bytes.reader(b)) + if d then + d:read(64) + d:seek(1e9) + d:read(64) + d:seek(-1) + d:read(64) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/voc.luau b/tests/audio/voc.luau new file mode 100644 index 0000000..129c6b6 --- /dev/null +++ b/tests/audio/voc.luau @@ -0,0 +1,129 @@ +-- audio/voc tests: files written by ffmpeg (type 1 + 8 blocks for 8-bit, type 9 otherwise) and sox against ffmpeg's +-- decode; silence / text / continuation blocks and repeat markers built here; streaming reads and seeks; our +-- encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. +-- Fixtures: tools/fixtures/voc.py. +local T = require("@tests/T") +local Voc = require("@formats/audio/voc") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/voc_cases") +local Enc = require("@tests/gen/voc_enc") +local Sig = require("@tests/gen/voc_sig") + +local t = T.suite("voc") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +t:eq(Voc.name, "voc", "name") +t:eq(Voc.category, "audio", "category") +t:check(Voc.caps.decode and Voc.caps.encode, "caps") + +for _, c in Cases do + local a, err = Voc.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, string.format("%s: format %d Hz x %d, want %d x %d", c.name, a.sampleRate, a.channels, c.rate, c.channels)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Voc.open(reader(c.data)) :: Types.Decoder + dec:seek(500 / c.rate) + local b, k = dec:read(64) + t:check(k == 64 and maxDiff(b, 0, ref, 500 * c.channels * 4, 64 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- hand-built blocks: text, type 1 u8, silence, continuation, repeat markers, terminator +do + local hdr = "Creative Voice File\26\26\0\10\1\41\17" + local function blk(typ: number, payload: string): string + local n = #payload + return string.char(typ, n % 256, (n // 256) % 256, n // 65536) .. payload + end + local data = hdr + .. blk(5, "made by hand\0") + .. blk(1, string.char(156, 0) .. string.char(128, 192, 64)) -- 10 kHz, 3 samples + .. blk(3, string.char(4, 0, 156)) -- 5 frames of silence + .. blk(6, string.char(2, 0)) -- repeat start (ignored) + .. blk(2, string.char(255, 0)) -- continuation + .. blk(7, "") -- repeat end + .. blk(4, string.char(1, 0)) -- marker + .. "\0" + local a, err = Voc.decode(reader(data)) + t:check(a, "hand-built: " .. tostring(err)) + t:check(a.sampleRate == 10000 and a.channels == 1 and a.frames == 10, "hand-built: 10 kHz, 3 + 5 + 2 frames") + t:eq(a.tags.comment, "made by hand", "text block") + local want = { 0, 0.5, -0.5, 0, 0, 0, 0, 0, 127 / 128, -1 } + local ok = true + for i, v in want do + ok = ok and buffer.readf32(a.samples, (i - 1) * 4) == v + end + t:check(ok, "hand-built samples") + -- no terminator, a block cut short: the data present + local cut = Voc.decode(reader(string.sub(data, 1, 26 + 17 + 4 + 2 + 2))) + t:check(cut and cut.frames == 2 and cut.meta.source.truncated, "cut in a block") + -- Creative ADPCM: unsupported + local _, e = Voc.decode(reader(hdr .. blk(1, string.char(156, 1) .. "\0\0") .. "\0")) + t:check(e and e.code == Err.UNSUPPORTED, "ADPCM: UNSUPPORTED") + local _, e2 = Voc.decode(reader(hdr .. blk(2, "\0\0") .. "\0")) + t:check(e2 and e2.code == Err.CORRUPT, "continuation first: CORRUPT") + local _, e3 = Voc.decode(reader(hdr .. "\0")) + t:check(e3 and e3.code == Err.CORRUPT, "no sound: CORRUPT") + local _, e4 = Voc.decode(reader("Creative Voice Fil")) + t:check(e4 and e4.code == Err.CORRUPT, "short: CORRUPT") + t:eq(Voc.sniff(reader(data)), 1, "sniff") + t:eq(Voc.sniff(reader(".snd")), 0, "sniff other") +end + +local TOL = { s16 = 0.5 / 32768, ["s16-mono"] = 0.5 / 32768, u8 = 0.5 / 128, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Voc.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(22050, 2, 1) + a.tags = { comment = "hi" } + local b = Voc.encode(a) :: buffer + local back = Voc.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 1 and back.tags.comment == "hi", "one frame + comment") + local _, e1 = Voc.encode(nil :: any) + t:check(e1 and e1.code == Err.ARG, "encode nil: ARG") + local _, e2 = Voc.encode(a, { sampleFormat = "s24" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Voc.decode(reader(Cases[1].data), { maxFrames = 5 }) + t:check(e3 and e3.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for _, c in Cases do + table.insert(samples, string.sub(c.data, 1, 300)) + end + t:fuzz("decode", function(b: buffer) + return Voc.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py index cf0f16f..b9680c3 100644 --- a/tools/fixtures/_audio.py +++ b/tools/fixtures/_audio.py @@ -192,3 +192,83 @@ def luau(ctx, code): return out[:-1] if out.endswith(b"\n") else out finally: os.unlink(path) + + +def emit_signal(ctx, name, samples, rate, ch): + """emit tests/gen/.luau = { rate, channels, frames, data = f32le bytes } (the input encoders are tested on)""" + ctx.emit(name, {"rate": rate, "channels": ch, "frames": len(samples) // ch, "data": f32le(samples)}) + + +def encode_luau(ctx, module, sigmod, opts_lua="nil", source="audio"): + """encode the emitted signal module `sigmod` with require("@formats/").encode(audio, opts) in Luau; returns + the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/Pcm.audioDecoder) instead of the Audio.""" + code = """ +local S = require("@tests/gen/%s") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local M = require("@formats/%s") +local a = Types.Audio.new(S.rate, S.channels, S.frames) +buffer.writestring(a.samples, 0, S.data) +local src: any = a +if "%s" == "decoder" then src = Pcm.audioDecoder(a) end +local out, err = M.encode(src, %s) +if not out then error("encode failed: " .. tostring(err)) end +print(buffer.tostring(out)) +""" % (sigmod, module, source, opts_lua) + return luau(ctx, code) + + +def max_diff(a, b): + if len(a) != len(b): + return float("inf") + return max((abs(x - y) for x, y in zip(a, b)), default=0.0) + + +def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000): + """The fixtures of an uncompressed container (aiff, au, voc): + made = [(name, packages, argv)]: reference tools write files from {in} (a stereo / mono 16-bit or float WAV of + the test signal; argv may use {in_mono}, {in_float}) into {out}; each file is decoded by ffmpeg as the + reference (f32le) + encodes = [(name, opts_lua, channels)]: our encoder's output (in the fixture step) decoded by ffmpeg, compared + against the f32 input (max abs difference, which the test bounds by the format's quantization step) + Emits _cases (files + references), _sig / _sig1 (the inputs, stereo / mono) and _enc.""" + stereo = signal("music", sig_rate, 2, sig_frames, seed=3) + mono = signal("sweep", sig_rate, 1, sig_frames, seed=4) + emit_signal(ctx, fmt + "_sig", stereo, sig_rate, 2) + emit_signal(ctx, fmt + "_sig1", mono, sig_rate, 1) + inputs = {"{in}": wav(stereo, sig_rate, 2, 16), "{in_mono}": wav(mono, sig_rate, 1, 16), + "{in_float}": wav(stereo, sig_rate, 2, float_=True)} + cases = [] + for name, packages, argv in made: + d = tempfile.mkdtemp(prefix="fmt-audio-") + try: + paths = {} + for key, data in inputs.items(): + paths[key] = os.path.join(d, key.strip("{}") + ".wav") + with open(paths[key], "wb") as f: + f.write(data) + out = os.path.join(d, "out." + fmt) + args = [] + for a in argv: + for key, p in paths.items(): + a = a.replace(key, p) + args.append(a.replace("{out}", out)) + ctx.nix(packages, args) + with open(out, "rb") as f: + data = f.read() + finally: + shutil.rmtree(d, ignore_errors=True) + rate, ch, ref = ffdecode(ctx, data, ext=fmt) + cases.append({"name": name, "data": data, "rate": rate, "channels": ch, "frames": len(ref) // ch, "ref": f32le(ref)}) + ctx.emit(fmt + "_cases", cases) + results = [] + for name, opts_lua, ch in encodes: + sig = stereo if ch == 2 else mono + out = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua) + streamed = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua, source="decoder") + rate, dch, dec = ffdecode(ctx, out, ext=fmt) + errs = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], out, fmt) + results.append({"name": name, "opts": opts_lua, "channels": dch, "rate": rate, "frames": len(dec) // max(1, dch), + "maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"), + "bytes": len(out), "sameStreamed": out == streamed, "data": out}) + ctx.emit(fmt + "_enc", results) diff --git a/tools/fixtures/aiff.py b/tools/fixtures/aiff.py new file mode 100644 index 0000000..15fbdb2 --- /dev/null +++ b/tools/fixtures/aiff.py @@ -0,0 +1,51 @@ +# AIFF / AIFF-C fixtures (tools/fixtures.py): files written by ffmpeg and sox in every sample format we read, each +# with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded by ffmpeg in the +# fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/aiff_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/aiff_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/aiff_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "aiff", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-sowt", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-fl32", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-fl64", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-48k-6ch", "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-af", "aresample=48000,pan=5.1|c0=c0|c1=c1|c2=c0|c3=c1|c4=c0|c5=c1", "-c:a", "pcm_s16be", "-f", "aiff", "-y", "{out}"]), + ("ffmpeg-tags", "ffmpeg", ff("pcm_s16be", extra=("-metadata", "title=Song Name", "-metadata", "author=Some One", "-metadata", "comment=hello"))), + ("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]), + ("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]), + ("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ("sowt16", '{ littleEndian = true }', 2), + ("aifc-s16", '{ aifc = true }', 2), + ] + A.pcm_fixtures(ctx, "aiff", made, encodes) diff --git a/tools/fixtures/au.py b/tools/fixtures/au.py new file mode 100644 index 0000000..eb34539 --- /dev/null +++ b/tools/fixtures/au.py @@ -0,0 +1,47 @@ +# Sun AU fixtures (tools/fixtures.py): files written by ffmpeg and sox in every encoding we read, each with ffmpeg's +# f32 decode as the reference; our encoder's output for every encoding, decoded by ffmpeg in the fixture step +# (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/au_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/au_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/au_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/au", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "au", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-f32be", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-f64be", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("sox-comment", "sox", ["sox", "{in}", "--comment", "hello sun", "-t", "au", "{out}"]), + ("sox-ulaw-8k", "sox", ["sox", "{in_mono}", "-r", "8000", "-e", "mu-law", "-t", "au", "{out}"]), + ("sox-s16", "sox", ["sox", "{in}", "-t", "au", "{out}"]), + ("sox-f32", "sox", ["sox", "{in_float}", "-e", "floating-point", "-b", "32", "-t", "au", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ] + A.pcm_fixtures(ctx, "au", made, encodes) diff --git a/tools/fixtures/voc.py b/tools/fixtures/voc.py new file mode 100644 index 0000000..b207bd8 --- /dev/null +++ b/tools/fixtures/voc.py @@ -0,0 +1,39 @@ +# Creative VOC fixtures (tools/fixtures.py): files written by ffmpeg (type 1 + type 8 blocks for 8-bit, type 9 for the +# rest) and sox, each with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded +# by ffmpeg in the fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/voc_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/voc_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/voc_sig*.luau the encoder inputs +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/voc", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "voc", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-u8-stereo", "ffmpeg", ff("pcm_u8")), + ("ffmpeg-u8-mono", "ffmpeg", ff("pcm_u8", "{in_mono}")), + ("ffmpeg-s16", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-s16-mono-44k", "ffmpeg", ff("pcm_s16le", "{in_mono}", ("-ar", "44100"))), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw", "{in_mono}")), + ("sox-u8-mono-11k", "sox", ["sox", "{in_mono}", "-r", "11025", "-b", "8", "-t", "voc", "{out}"]), + ("sox-u8-stereo", "sox", ["sox", "{in}", "-b", "8", "-t", "voc", "{out}"]), + ("sox-s16-stereo", "sox", ["sox", "{in}", "-b", "16", "-t", "voc", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("u8", '{ sampleFormat = "u8" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 1), + ] + A.pcm_fixtures(ctx, "voc", made, encodes) From d7c2d2eeb54cde6323651ab3b740f008ffddc9be Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:44:56 -0500 Subject: [PATCH 08/28] ws-music: music/sf2 + SoundFont tests vs FluidSynth (envelope r 0.995, band spectra r >= 0.969, pitch peaks within 0.6%), gain ramp per block, bench lines tools/bench.sh: also generates the midi + sf2 fixtures (the bench renders their songs). licenses: TinySoundFont MIT row in NOTICE.md. --- docs/FORMATS.md | 3 + licenses/NOTICE.md | 1 + src/Formats/codecs/SoundFont/Parse.luau | 10 +- src/Formats/codecs/SoundFont/Synth.luau | 14 +- src/Formats/music/midi/Smf.luau | 2 +- tests/music/sf2.luau | 338 ++++++++++++++++++++++++ tools/bench.luau | 60 +++++ tools/bench.sh | 2 +- tools/fixtures/_sf2_features.py | 61 +++++ tools/fixtures/sf2.py | 227 ++++++++++++++++ 10 files changed, 707 insertions(+), 11 deletions(-) create mode 100644 tests/music/sf2.luau create mode 100644 tools/fixtures/_sf2_features.py create mode 100644 tools/fixtures/sf2.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..453281d 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,7 +6,10 @@ 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` | +| music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | +| music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | 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/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..b69b7e3 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -5,6 +5,7 @@ | `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 | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | +| `src/Formats/codecs/SoundFont/` (Synth, the zone merging in Parse) | port of TinySoundFont v0.9 (tsf.h) by Bernhard Schelling, based on SFZero by Steve Folta | MIT: [TinySoundFont-LICENSE.txt](TinySoundFont-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/SoundFont/Parse.luau index 8e4f60a..90cdfcc 100644 --- a/src/Formats/codecs/SoundFont/Parse.luau +++ b/src/Formats/codecs/SoundFont/Parse.luau @@ -29,7 +29,7 @@ export type SoundFont = { meta: { [string]: any }, } -local GEN_INSTRUMENT, GEN_KEYRANGE, GEN_VELRANGE, GEN_SAMPLEID = 41, 43, 44, 53 +local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 -- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address -- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) @@ -235,7 +235,7 @@ local LAYOUT: { [string]: { number } } = { igen = { 2, 2 }, shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, } -local RECSIZE = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } +local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } local INFO_NAMES = { isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", @@ -296,7 +296,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) if layout and not hydra[sid] then local rs = RECSIZE[sid] local n = sub:remaining() // rs - local recs = table.create(n) + local recs: { { number } } = table.create(n) for i = 1, n do local rec = {} for _, w in layout do @@ -487,7 +487,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) for _, p in presets do (p :: any)._order = nil end - local headers = table.create(nShdr) + local headers: { { [string]: any } } = table.create(nShdr) for i = 1, nShdr do local sh = shdr[i] headers[i] = { @@ -503,7 +503,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) type = sh[10], } end - local instruments = table.create(nInst) + local instruments: { { name: string, zones: number } } = table.create(nInst) for i = 1, nInst do instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } end diff --git a/src/Formats/codecs/SoundFont/Synth.luau b/src/Formats/codecs/SoundFont/Synth.luau index 0bde0cd..c133423 100644 --- a/src/Formats/codecs/SoundFont/Synth.luau +++ b/src/Formats/codecs/SoundFont/Synth.luau @@ -8,7 +8,7 @@ -- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, -- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not -- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. --- Differences from tsf.h: a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. +-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. -- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, -- the sample buffer has a zero pad sample, the output range is checked before mixing). local Synth = {} @@ -734,7 +734,11 @@ local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSa if updateVibLfo then lfoProcess(v.viblfo, block) end - local gl, gr = gainMono * v.panL, gainMono * v.panR + -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) + local gainNext = noteGain * v.amp.level + local step = (gainNext - gainMono) / block + local panL, panR = v.panL, v.panR + local g = gainMono local k = block while k > 0 and pos < endD do k -= 1 @@ -748,8 +752,10 @@ local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSa z2 = val * a0 - b2 * y val = y end - writef32(out, o, readf32(out, o) + val * gl) - writef32(out, o + 4, readf32(out, o + 4) + val * gr) + val *= g + g += step + writef32(out, o, readf32(out, o) + val * panL) + writef32(out, o + 4, readf32(out, o + 4) + val * panR) o += 8 pos += pitchRatio if pos >= loopEndD and isLooping then diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau index 4c0ec1f..ed69595 100644 --- a/src/Formats/music/midi/Smf.luau +++ b/src/Formats/music/midi/Smf.luau @@ -25,7 +25,7 @@ export type WriteOptions = { } local function bytesOf(b: buffer, p: number, n: number): { number } - local t = table.create(n) + local t: { number } = table.create(n) for i = 0, n - 1 do t[i + 1] = readu8(b, p + i) end diff --git a/tests/music/sf2.luau b/tests/music/sf2.luau new file mode 100644 index 0000000..057b30e --- /dev/null +++ b/tests/music/sf2.luau @@ -0,0 +1,338 @@ +-- music/sf2 + codecs/SoundFont tests: a self-made SF2 parsed (INFO, presets, sample headers, instruments, generator +-- merging with preset / instrument global zones, 16-bit and sm24 samples), a test song rendered through it compared +-- with FluidSynth's render (loudness envelope and per-segment band spectra by correlation, pitch peaks), bad files, +-- the built-in fallback waveform set, and the fuzz no-throw pass. Fixtures: tools/fixtures/sf2.py. +local T = require("@tests/T") +local Sf2 = require("@formats/music/sf2") +local Midi = require("@formats/music/midi") +local SoundFont = require("@formats/codecs/SoundFont") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/sf2_cases") + +local t = T.suite("sf2") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- the contract +t:eq(Sf2.name, "sf2", "name") +t:eq(Sf2.category, "music", "category") +t:check(Sf2.caps.decode and not Sf2.caps.encode, "caps") +t:eq(Sf2.sniff(reader(Fx.sf2)), 1, "sniff") +t:eq(Sf2.sniff(reader("RIFF\0\0\0\0WAVE")), 0, "sniff WAVE") + +-- parse +local sf, err = Sf2.decode(reader(Fx.sf2)) +t:check(sf, "decode: " .. tostring(err)) +local E = Fx.expect +t:eq(sf.kind, "soundfont", "kind") +t:eq(sf.info.name, E.info.name, "INAM") +t:eq(sf.info.engine, E.info.engine, "isng") +t:eq(sf.meta.source.version, E.info.version, "ifil") +t:eq(#sf.presets, #E.presets, "preset count") +for i, p in E.presets do + t:eq(sf.presets[i].name, p.name, "preset " .. i .. " name") + t:eq(sf.presets[i].bank, p.bank, "preset " .. i .. " bank") + t:eq(sf.presets[i].preset, p.preset, "preset " .. i .. " number") +end +t:eq(#sf.sampleHeaders, #E.samples, "sample headers") +for i, s in E.samples do + for k, v in s do + t:eq(sf.sampleHeaders[i][k], v, "sample " .. i .. " " .. k) + end +end +for i, n in E.instruments do + t:eq(sf.instruments[i].name, n, "instrument " .. i) +end +local function preset(name: string): any + for _, p in sf.presets do + if p.name == name then + return p + end + end + return nil +end +do + local sine, saw, drums = preset("Sine"), preset("Saw"), preset("Drums") + t:eq(#sine.regions, 1, "Sine: the preset global zone is not a region") + t:check(math.abs(sine.regions[1].attenuation - 30 * 0.04) < 1e-9, "Sine: the preset global zone's attenuation applies") + t:check(math.abs(sine.regions[1].aRelease - 0.2) < 0.001, "Sine: release in seconds") + t:check(math.abs(sine.regions[1].aSustain - 10 ^ (-6 / 20)) < 1e-6, "Sine: sustain 60 cB = -6 dB") + t:eq(sine.regions[1].loopMode, 1, "Sine: looped") + t:eq(sine.regions[1].keycenter, 69, "Sine: root key from the sample header") + t:eq(sine.regions[1].tune, -4, "Sine: pitch correction") + t:eq(#saw.regions, 1, "Saw: the instrument global zone is not a region") + t:check(math.abs(saw.regions[1].filterFc - math.floor(1200 * math.log(2500 / 8.176, 2) + 0.5)) <= 1, "Saw: the instrument global zone's filter applies") + t:eq(saw.regions[1].modEnvToFilterFc, 2400, "Saw: mod env to filter") + t:eq(#drums.regions, 4, "Drums: four key zones") + local groups = 0 + for _, r in drums.regions do + t:check(math.abs(r.aRelease - 0.05) < 0.001, "Drums: release from the instrument global zone") + if r.group == 1 then + groups += 1 + end + end + t:eq(groups, 2, "Drums: two hats in exclusive class 1") + t:eq(drums.regions[1].lokey, 35, "Drums: key range lo") + t:eq(drums.regions[1].hikey, 36, "Drums: key range hi") +end +-- samples: 16-bit, and 24-bit with sm24 +do + local sf24 = Sf2.decode(reader(Fx.sf2_24)) + t:check(sf24 and sf24.meta.source.sm24, "sm24 read") + t:eq(sf.meta.source.sm24, false, "no sm24") + for _, v in E.values do + local i, hi, lo = v[1], v[2], v[3] + local a = buffer.readf32(sf.samples, i * 4) + local b = buffer.readf32(sf24.samples, i * 4) + t:check(math.abs(a - hi / 32767) < 1e-6, "16-bit sample " .. i) + t:check(math.abs(b - (hi * 256 + lo) / 8388607) < 1e-6, "24-bit sample " .. i) + end + t:eq(buffer.len(sf.samples), (sf.sampleCount + 1) * 4, "samples: one pad sample") +end + +-- ------------------------------------------------------------------------------------------------ vs FluidSynth +local F = Fx.fluid +local song = Midi.decode(reader(Fx.song)) +t:check(song, "song decodes") +local dec = assert(Midi.render(song, { soundfont = sf, tail = 2 })) +local frames = math.min(dec.frames, F.frames) +local mono = table.create(frames, 0) +do + local got = 0 + while got < frames do + local b, n = dec:read(math.min(8192, frames - got)) + if n == 0 then + break + end + for i = 0, n - 1 do + mono[got + i + 1] = (buffer.readf32(b, i * 8) + buffer.readf32(b, i * 8 + 4)) * 0.5 + end + got += n + end + t:eq(got, frames, "rendered the compared length") +end + +local function pearson(a: { number }, b: { number }): number + local n = math.min(#a, #b) + local ma, mb = 0, 0 + for i = 1, n do + ma += a[i] + mb += b[i] + end + ma /= n + mb /= n + local sab, saa, sbb = 0, 0, 0 + for i = 1, n do + local x, y = a[i] - ma, b[i] - mb + sab += x * y + saa += x * x + sbb += y * y + end + return sab / math.sqrt(saa * sbb + 1e-30) +end + +-- in-place radix-2 FFT of re / im (1-based arrays of length n, a power of two) +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 0, n - 2 do + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + local m = n // 2 + while m >= 1 and j >= m do + j -= m + m //= 2 + end + j += m + end + local len = 2 + while len <= n do + local ang = -2 * math.pi / len + local wr, wi = math.cos(ang), math.sin(ang) + for s = 0, n - 1, len do + local cr, ci = 1, 0 + for k = 0, len // 2 - 1 do + local a, b = s + k + 1, s + k + len // 2 + 1 + local xr = re[b] * cr - im[b] * ci + local xi = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - xr, im[a] - xi + re[a], im[a] = re[a] + xr, im[a] + xi + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + end + end + len *= 2 + end +end + +local function power(start: number, n: number): { number } + local re, im = table.create(n, 0), table.create(n, 0) + for i = 0, n - 1 do + re[i + 1] = (mono[start + i + 1] or 0) * (0.5 - 0.5 * math.cos(2 * math.pi * i / n)) + end + fft(re, im, n) + local p = table.create(n // 2 + 1, 0) + for k = 0, n // 2 do + p[k + 1] = re[k + 1] ^ 2 + im[k + 1] ^ 2 + end + return p +end + +local rate = F.rate +-- the loudness envelope (50 ms RMS) +local env = {} +for i = 0, frames - 2205, 2205 do + local s = 0 + for k = 1, 2205 do + local v = mono[i + k] + s += v * v + end + table.insert(env, math.sqrt(s / 2205)) +end +local envCorr = pearson(env, F.env) +local ENV_MIN = 0.95 +t:check(envCorr > ENV_MIN, string.format("loudness envelope correlation %.3f > %.2f", envCorr, ENV_MIN)) +t:note("loudness envelope vs FluidSynth: r = %.3f (%d windows)", envCorr, #env) + +-- per-segment band spectra +local BAND_MIN = 0.93 +local worstBand = 1 +for si, seg in F.segments do + local acc = table.create(24, 0) + local count = 0 + for s = math.floor(seg[1] * rate), math.floor(seg[2] * rate) - 2048, 1024 do + local p = power(s, 2048) + for k = 0, 1024 do + local f = k * rate / 2048 + for b = 1, 24 do + if f >= F.edges[b] and f < F.edges[b + 1] then + acc[b] += p[k + 1] + break + end + end + end + count += 1 + end + local db = table.create(24, 0) + for b = 1, 24 do + db[b] = 10 * math.log10(acc[b] / math.max(count, 1) + 1e-12) + end + local r = pearson(db, F.bands[si]) + worstBand = math.min(worstBand, r) + t:check(r > BAND_MIN, string.format("segment %d band spectrum correlation %.3f > %.2f", si, r, BAND_MIN)) + t:note("segment %d (%g-%g s) band spectrum vs FluidSynth: r = %.3f", si, seg[1], seg[2], r) +end + +-- pitch peaks (vibrato square, a note bent an octave with an RPN 0 range of 12, the saw melody's first note) +for wi, w in F.windows do + local acc = table.create(4097, 0) + for s = math.floor(w[1] * rate), math.floor(w[2] * rate) - 8192, 2048 do + local p = power(s, 8192) + for k = 1, 4097 do + acc[k] += p[k] + end + end + local best, bk = -1, 2 + for k = 2, 4096 do + if acc[k] > best then + best, bk = acc[k], k + end + end + local y0, y1, y2 = math.log(acc[bk - 1] + 1e-30), math.log(acc[bk] + 1e-30), math.log(acc[bk + 1] + 1e-30) + local hz = ((bk - 1) + 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)) * rate / 8192 + local ratio = hz / F.peaks[wi] + t:check(math.abs(ratio - 1) < 0.015, string.format("window %d peak %.1f Hz vs FluidSynth %.1f Hz", wi, hz, F.peaks[wi])) + t:note("window %g-%g s: peak %.1f Hz (FluidSynth %.1f Hz)", w[1], w[2], hz, F.peaks[wi]) +end + +-- ------------------------------------------------------------------------------------------------ bad files +local function bad(data: string, code: string, label: string) + local ok, v, e = pcall(Sf2.decode, reader(data)) + t:check(ok, label .. ": threw " .. tostring(v)) + t:check(v == nil and Err.is(e) and e.code == code, label .. ": " .. tostring(e)) +end +bad("RIFX\0\0\0\0sfbk", Err.CORRUPT, "not RIFF") +bad("RIFF\4\0\0\0WAVE", Err.CORRUPT, "not sfbk") +bad("RIFF\4\0\0\0sfbk", Err.CORRUPT, "no chunks") +bad(string.sub(Fx.sf2, 1, 40), Err.CORRUPT, "truncated in INFO") +local lim, lerr = Sf2.decode(reader(Fx.sf2), { maxSamples = 100 }) +t:check(lim == nil and lerr.code == Err.LIMIT, "maxSamples: LIMIT") +local lim2, lerr2 = Sf2.decode(reader(Fx.sf2), { maxRegions = 3 }) +t:check(lim2 == nil and lerr2.code == Err.LIMIT, "maxRegions: LIMIT") +local p, perr = SoundFont.parse(42 :: any) +t:check(p == nil and perr.code == Err.ARG, "parse: bad argument") + +-- ------------------------------------------------------------------------------------------------ fallback +do + local fb = SoundFont.fallback() + t:eq(#fb.presets, 129, "fallback: 128 programs + a drum kit") + local s = SoundFont.synth(nil, 22050) + local Synth = SoundFont.Synth + local out = buffer.create(2205 * 8) + for program = 0, 127, 8 do + Synth.reset(s) + Synth.midi(s, 0xC0, program, 0) + Synth.midi(s, 0x90, 60, 100) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + local v = buffer.readf32(out, i * 4) + t:check(v == v and math.abs(v) < 4, "fallback: finite samples") + e += v * v + end + t:check(e > 0.01, "fallback program " .. program .. " sounds") + end + for _, key in { 35, 36, 38, 42, 46, 49, 51, 60 } do + Synth.reset(s) + Synth.midi(s, 0x99, key, 120) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + e += buffer.readf32(out, i * 4) ^ 2 + end + t:check(e > 0.01, "fallback drum " .. key .. " sounds") + end + -- exclusive class: a closed hat cuts the open hat + Synth.reset(s) + Synth.midi(s, 0x99, 46, 120) + t:eq(Synth.active(s), 1, "open hat") + Synth.midi(s, 0x99, 42, 120) + Synth.render(s, out, 0, 2205) + t:eq(Synth.active(s), 1, "closed hat ends the open hat (exclusive class)") + -- render range clipping: never writes past the buffer + Synth.render(s, out, 2200, 100000) + Synth.render(s, out, -5, 10) + t:check(true, "out-of-range render requests are clipped") +end + +-- the fuzz no-throw pass (parse, then a few notes through whatever parsed) +t:fuzz("decode", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + for ch = 0, 15 do + SoundFont.Synth.midi(s, 0xC0 + ch, ch * 8, 0) + SoundFont.Synth.midi(s, 0x90 + ch, 30 + ch * 5, 100) + end + local out = buffer.create(512 * 8) + SoundFont.Synth.render(s, out, 0, 512) + end +end, { Fx.sf2 }, { mutations = 60, garbage = 100 }) +-- mutations inside the hydra (the last ~1 KB) exercise the zone / index clamping +t:fuzz("hydra", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + SoundFont.Synth.midi(s, 0x90, 60, 100) + SoundFont.Synth.midi(s, 0x99, 36, 100) + local out = buffer.create(256 * 8) + SoundFont.Synth.render(s, out, 0, 256) + end +end, { Fx.sf2 }, { mutations = 200, garbage = 0, keepHeader = #Fx.sf2 - 1200 }) + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 9f6aef7..a353be8 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -56,3 +56,63 @@ do Png.encode(img) end) end + +-- MIDI through the SoundFont synth (tools/fixtures/sf2.py's test song; tools/fixtures/midi.py's "song" through the +-- built-in waveform set): seconds of stereo 44.1 kHz audio rendered per second of CPU +do + local Midi = require("@formats/music/midi") + local Sf2 = require("@formats/music/sf2") + local SF = require("@tests/gen/sf2_cases") + local MC = require("@tests/gen/midi_cases") + local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2)))) + local function realtime(label: string, data: string, font: any) + local song = assert(Midi.decode(Bytes.reader(buffer.fromstring(data)))) + local best = math.huge + local frames = 0 + for _ = 1, 3 do + local dec = assert(Midi.render(song, { soundfont = font, tail = 0 })) + local out = buffer.create(4096 * 8) + local t0 = os.clock() + frames = 0 + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, label, best * 1000, frames / 44100 / best)) + end + realtime("midi render sf2 (test song)", SF.song, sf) + for _, c in MC do + if c.name == "song" then + realtime("midi render fallback", c.data, nil) + end + end +end +-- the synth's per-voice cost: 32 sustained, filtered, looped voices (sf2 saw preset with a mod env) for 2 s +do + local SoundFont = require("@formats/codecs/SoundFont") + local Sf2 = require("@formats/music/sf2") + local SF = require("@tests/gen/sf2_cases") + local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2)))) + local frames = 88200 + local out = buffer.create(frames * 8) + local best = math.huge + for _ = 1, 3 do + local s = SoundFont.synth(sf, 44100) + SoundFont.Synth.midi(s, 0xC0, 1, 0) + for k = 0, 31 do + SoundFont.Synth.midi(s, 0x90, 40 + k, 100) + end + buffer.fill(out, 0, 0) + local t0 = os.clock() + for f = 0, frames - 1, 1024 do + SoundFont.Synth.render(s, out, f, 1024) + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f M voice-samples/s", runtime, "synth 32 voices x 2 s", best * 1000, 32 * frames / best / 1e6)) +end diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..f7164e0 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 midi sf2 > /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 diff --git a/tools/fixtures/_sf2_features.py b/tools/fixtures/_sf2_features.py new file mode 100644 index 0000000..09f39fb --- /dev/null +++ b/tools/fixtures/_sf2_features.py @@ -0,0 +1,61 @@ +# Audio features of a WAV on stdin (run by tools/fixtures/sf2.py through ctx.python(["numpy"], ...); not a generator). +# tests/music/sf2.luau computes the same features from formats-luau's render and compares them: +# env RMS of the mono mix per 50 ms window (2205 frames) +# bands per 2 s segment: mean power in 24 log-spaced bands (60 Hz .. 16 kHz) of 2048-point Hann frames (hop 1024), +# in dB +# peaks the strongest frequency (parabolic interpolation) of the mean 8192-point Hann spectrum in a few windows +import io, json, sys, wave +import numpy as np + +w = wave.open(io.BytesIO(sys.stdin.buffer.read())) +rate, ch, width, n = w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes() +raw = w.readframes(n) +assert width == 2, width +x = np.frombuffer(raw, dtype="= edges[k]) & (freqs < edges[k + 1])].sum() + frames += 1 + return [float(10 * np.log10(v / max(frames, 1) + 1e-12)) for v in acc] + + +PN = 8192 +phan = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(PN) / PN) +WINDOWS = [(4.2, 5.4), (8.05, 8.45), (8.55, 8.95), (2.02, 2.33)] + + +def peak(a, b): + acc = np.zeros(PN // 2 + 1) + for s in range(int(a * rate), int(b * rate) - PN + 1, PN // 4): + acc += np.abs(np.fft.rfft(mono[s:s + PN] * phan)) ** 2 + k = int(np.argmax(acc[1:-1])) + 1 + y0, y1, y2 = np.log(acc[k - 1] + 1e-30), np.log(acc[k] + 1e-30), np.log(acc[k + 1] + 1e-30) + d = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2) + return float((k + d) * rate / PN) + + +json.dump({ + "rate": rate, + "frames": len(mono), + "env": env, + "edges": edges, + "segments": [list(s) for s in SEGMENTS], + "bands": [bands(a, b) for a, b in SEGMENTS], + "windows": [list(wd) for wd in WINDOWS], + "peaks": [peak(a, b) for a, b in WINDOWS], +}, sys.stdout) diff --git a/tools/fixtures/sf2.py b/tools/fixtures/sf2.py new file mode 100644 index 0000000..638d874 --- /dev/null +++ b/tools/fixtures/sf2.py @@ -0,0 +1,227 @@ +# SoundFont fixtures (tools/fixtures.py): a small self-made SF2 (band-limited sine / saw / square loops + a noise +# burst; melodic presets with envelopes, a filter + mod envelope, vibrato, a preset global zone, an instrument global +# zone, a drum kit on bank 128 with exclusive classes), a 12.5 s test song (SMF written here) that plays each preset in +# its own 2 s segment (chords, pitch bend with an RPN 0 range of 12, sustain pedal, CC7 / CC11), the song rendered by +# FluidSynth (nixpkgs#fluidsynth, reverb and chorus off) and analysed with numpy (tools/fixtures/_sf2_features.py): +# tests/gen/sf2_cases.luau { sf2, sf2_24 (the same with an sm24 chunk), song, fluid = { env, bands, peaks }, +# expect = { presets, samples, instruments, info, values } } +import json, math, os, random, struct, subprocess, tempfile + +INPUTS = ["tools/fixtures/_sf2_features.py"] +RATE = 44100 +PERIOD = 100 # 441 Hz loops +CYCLES = 50 + + +def tc(sec): + return int(round(1200 * math.log2(sec))) + + +def hz_cents(hz): + return int(round(1200 * math.log2(hz / 8.176))) + + +def wave(kind, rng): + n = PERIOD * CYCLES + out = [] + for i in range(n): + ph = 2 * math.pi * i / PERIOD + if kind == "sine": + v = math.sin(ph) * 0.8 + elif kind == "saw": + v = sum(math.sin(k * ph) / k for k in range(1, 50)) * 0.45 + else: + v = sum(math.sin(k * ph) / k for k in range(1, 50, 2)) * 0.6 + out.append(v) + return out + + +def chunk(cid, data): + pad = b"\x00" if len(data) % 2 else b"" + return cid + struct.pack("> 8, x & 255 + pcm += struct.pack(" root 69, correction -4 makes it play 440 Hz-ish at key 69 + headers.append((name, start, end, start, end, RATE, 69, -4, 0, 1)) + if len(pcm24) % 2: + pcm24 += b"\x00" + info = lst(b"INFO", [chunk(b"ifil", struct.pack(">= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def song(): + tpq, us = 480, 500000 # 1 beat = 0.5 s + ev = [] # (seconds, bytes) + + def at(sec, *b): + ev.append((sec, bytes(b))) + at(0, 0xC0, 0) + at(0, 0xC1, 1) + at(0, 0xC2, 2) + # seg 0: a sine chord + for n in (60, 64, 67): + at(0.0, 0x90, n, 127) + at(1.5, 0x80, n, 0) + # seg 1: a saw melody (filter + mod env) + for k, n in enumerate((48, 52, 55, 60)): + at(2.0 + 0.4 * k, 0x91, n, 127) + at(2.35 + 0.4 * k, 0x81, n, 0) + # seg 2: a square with vibrato + at(4.0, 0x92, 69, 127) + at(5.5, 0x82, 69, 0) + # seg 3: drums (hats cut each other: exclusive class) + for sec, n in ((6.0, 36), (6.25, 42), (6.5, 38), (6.75, 42), (7.0, 46), (7.25, 42), (7.5, 36)): + at(sec, 0x99, n, 127) + at(sec + 0.1, 0x89, n, 0) + # seg 4: sine with a pitch-bend range of 12 (RPN 0), a bend up an octave, the sustain pedal + at(7.9, 0xB0, 101, 0) + at(7.9, 0xB0, 100, 0) + at(7.9, 0xB0, 6, 12) + at(8.0, 0x90, 72, 127) + at(8.5, 0xE0, 0x7F, 0x7F) + at(9.0, 0xE0, 0x00, 0x40) + at(9.1, 0xB0, 64, 127) + at(9.2, 0x80, 72, 0) + at(9.6, 0xB0, 64, 0) + # seg 5: saw with volume and expression changes + at(10.0, 0x91, 57, 127) + at(10.75, 0xB1, 7, 60) + at(11.25, 0xB1, 11, 64) + at(11.6, 0x81, 57, 0) + ev.sort(key=lambda e: e[0]) + body, last = bytearray(), 0 + body += b"\x00\xff\x51\x03" + struct.pack(">I", us)[1:] + for sec, b in ev: + tick = int(round(sec * tpq * 1e6 / us)) + body += vlq(tick - last) + b + last = tick + end = int(round(12.5 * tpq * 1e6 / us)) + body += vlq(end - last) + b"\xff\x2f\x00" + return b"MThd" + struct.pack(">IHHH", 6, 0, 1, tpq) + b"MTrk" + struct.pack(">I", len(body)) + bytes(body) + + +def generate(ctx): + sf2, expect = build_sf2(False) + sf2_24, _ = build_sf2(True) + mid = song() + with tempfile.TemporaryDirectory() as d: + fp, mp, wp = os.path.join(d, "t.sf2"), os.path.join(d, "t.mid"), os.path.join(d, "t.wav") + with open(fp, "wb") as f: + f.write(sf2) + with open(mp, "wb") as f: + f.write(mid) + ctx.nix("fluidsynth", ["fluidsynth", "-ni", "-q", "-R", "0", "-C", "0", "-g", "0.5", "-r", "44100", "-F", wp, fp, mp]) + with open(wp, "rb") as f: + wav = f.read() + fluid = json.loads(ctx.python(["numpy"], ctx.read("tools/fixtures/_sf2_features.py").decode(), input=wav)) + ctx.emit("sf2_cases", {"sf2": sf2, "sf2_24": sf2_24, "song": mid, "fluid": fluid, "expect": expect}) From da534ce5076cb5b2149a1314f0b35e01ed9d9884 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:47:40 -0500 Subject: [PATCH 09/28] ws-music: codecs/Tracker engine (player, mixer, pcm, tables) + music/mod read/write/render, tested against openmpt123 --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/codecs/Tracker/Mixer.luau | 173 +++ src/Formats/codecs/Tracker/Pcm.luau | 132 ++ src/Formats/codecs/Tracker/Player.luau | 1837 ++++++++++++++++++++++++ src/Formats/codecs/Tracker/Tables.luau | 113 ++ src/Formats/codecs/Tracker/init.luau | 513 +++++++ src/Formats/music/mod/init.luau | 361 +++++ tests/music/_similar.luau | 201 +++ tests/music/mod.luau | 77 + tools/fixtures/_tracker.py | 495 +++++++ tools/fixtures/mod.py | 104 ++ 12 files changed, 4020 insertions(+) create mode 100644 src/Formats/codecs/Tracker/Mixer.luau create mode 100644 src/Formats/codecs/Tracker/Pcm.luau create mode 100644 src/Formats/codecs/Tracker/Player.luau create mode 100644 src/Formats/codecs/Tracker/Tables.luau create mode 100644 src/Formats/codecs/Tracker/init.luau create mode 100644 src/Formats/music/mod/init.luau create mode 100644 tests/music/_similar.luau create mode 100644 tests/music/mod.luau create mode 100644 tools/fixtures/_tracker.py create mode 100644 tools/fixtures/mod.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..e815f98 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,7 +6,9 @@ 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` | +| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | 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/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..d245f17 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "mod", + category = "music", + path = "music/mod", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/mod") + end, + }, } return list diff --git a/src/Formats/codecs/Tracker/Mixer.luau b/src/Formats/codecs/Tracker/Mixer.luau new file mode 100644 index 0000000..193a034 --- /dev/null +++ b/src/Formats/codecs/Tracker/Mixer.luau @@ -0,0 +1,173 @@ +--!strict +--!native +-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample +-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole +-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code). +-- +-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker) +-- validates the sample buffers' sizes. +local floor, ceil, min = math.floor, math.ceil, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local Mixer = {} + +-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) +local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) + local data: buffer = v.data + local nch = v.nch + local inc = v.inc + if not (inc > 0 and inc < 1e6) then + return + end + local len = v.len + local hi = len - 1 + local i = 0 + local guard = 0 + while i < n do + guard += 1 + if guard > n + 64 then + return + end + local s, e, t + if v.keyOn and v.susT > 0 then + s, e, t = v.susS, v.susE, v.susT + elseif v.loopT > 0 then + s, e, t = v.loopS, v.loopE, v.loopT + else + s, e, t = 0, len, 0 + end + local p = v.p + local dir = v.dir + local count + if dir > 0 then + local lim = if t == 2 then e - 1 else e + if p >= lim then + if t == 0 then + v.active = false + return + elseif t == 1 then + p = s + (p - e) % (e - s) + else + p = 2 * (e - 1) - p + if p < s then + p = s + end + v.dir = -1 + end + v.p = p + continue + end + count = ceil((lim - p) / inc) + else + if p < s then + p = 2 * s - p + if p > e - 1 then + p = e - 1 + end + v.p = p + v.dir = 1 + continue + end + count = floor((p - s) / inc) + 1 + end + if count < 1 then + count = 1 + end + local m = min(n - i, count) + local step = inc * dir + if out == nil then + v.p = p + step * m + i += m + continue + end + local wrapJ = if t == 1 then s else e - 1 + local gl, gr = v.gl, v.gr + local rl = v.rampN + local dl, dr = 0, 0 + local tl, tr = v.tl, v.tr + if rl > 0 then + dl, dr = (tl - gl) / rl, (tr - gr) / rl + end + local fOn = v.fOn + local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 + local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r + local o = (off + i) * 8 + for _ = 1, m do + local idx = floor(p) + if idx > hi then + idx = hi + elseif idx < 0 then + idx = 0 + end + local j = idx + 1 + if j >= e then + j = wrapJ + end + if j > hi then + j = hi + end + local xl, xr + if nch == 1 then + local a = readf32(data, idx * 4) + if linear then + local b = readf32(data, j * 4) + xl = a + (b - a) * (p - idx) + else + xl = a + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + end + xr = xl + else + local al = readf32(data, idx * 8) + local ar = readf32(data, idx * 8 + 4) + if linear then + local f = p - idx + xl = al + (readf32(data, j * 8) - al) * f + xr = ar + (readf32(data, j * 8 + 4) - ar) * f + else + xl, xr = al, ar + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + y = xr * fa + y1r * fb0 + y2r * fb1 + y2r, y1r = y1r, y + xr = y + end + end + if rl > 0 then + gl += dl + gr += dr + rl -= 1 + if rl == 0 then + gl, gr = tl, tr + end + end + writef32(out, o, readf32(out, o) + xl * gl) + writef32(out, o + 4, readf32(out, o + 4) + xr * gr) + o += 8 + p += step + end + v.p = p + v.gl, v.gr, v.rampN = gl, gr, rl + v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r + i += m + end + local _ = ramp +end + +-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions +function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) + for _, v in st.voices do + if v.active and v.data then + mixVoice(v, out, off, n, linear, 0) + end + end +end + +return Mixer diff --git a/src/Formats/codecs/Tracker/Pcm.luau b/src/Formats/codecs/Tracker/Pcm.luau new file mode 100644 index 0000000..30c59c8 --- /dev/null +++ b/src/Formats/codecs/Tracker/Pcm.luau @@ -0,0 +1,132 @@ +--!strict +--!native +-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, +-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back. +-- +-- Never throws: reads past the source are refused up front (decode returns nil). +local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 +local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 +local floor = math.floor + +local Pcm = {} + +export type Spec = { + bits: number, -- 8 | 16 + signed: boolean, + delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) + channels: number?, -- 1 (default) | 2 + planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved + bigEndian: boolean?, +} + +-- bytes(frames, spec) -> the size of the raw data +function Pcm.bytes(frames: number, spec: Spec): number + return frames * (spec.channels or 1) * (spec.bits // 8) +end + +-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short +function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local total = frames * nch + if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then + return nil + end + local out = buffer.create(total * 4) + local planar = spec.planar and nch == 2 + for c = 0, nch - 1 do + local acc = 0 + for i = 0, frames - 1 do + local k = if planar then c * frames + i else i * nch + c + local v + if bps == 1 then + if spec.signed then + v = readi8(buf, off + k) + else + v = readu8(buf, off + k) - 128 + end + if spec.delta then + acc = (acc + v + 128) % 256 - 128 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 128) + else + local p = off + k * 2 + if spec.bigEndian then + v = readu8(buf, p) * 256 + readu8(buf, p + 1) + if spec.signed and v >= 32768 then + v -= 65536 + end + elseif spec.signed then + v = readi16(buf, p) + else + v = readu16(buf, p) + end + if not spec.signed then + v -= 32768 + end + if spec.delta then + acc = (acc + v + 32768) % 65536 - 32768 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 32768) + end + end + end + return out +end + +-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) +function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local out = buffer.create(frames * nch * bps) + local planar = spec.planar and nch == 2 + local avail = buffer.len(samples) // 4 + for c = 0, nch - 1 do + local prev = 0 + for i = 0, frames - 1 do + local si = i * nch + c + local x = if si < avail then readf32(samples, si * 4) else 0 + local k = if planar then c * frames + i else i * nch + c + if bps == 1 then + local v = math.clamp(floor(x * 128 + 0.5), -128, 127) + local w = v + if spec.delta then + w = (v - prev) % 256 + prev = v + else + w = if spec.signed then v % 256 else v + 128 + end + writeu8(out, k, w) + else + local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) + local w = v + if spec.delta then + w = (v - prev + 32768) % 65536 - 32768 + prev = v + elseif not spec.signed then + w = v + 32768 + if w >= 32768 then + w -= 65536 + end + end + writei16(out, k * 2, w) + end + end + end + return out +end + +-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 +function Pcm.bitsNeeded(samples: buffer): number + for i = 0, buffer.len(samples) // 4 - 1 do + local x = readf32(samples, i * 4) * 128 + if x ~= floor(x) then + return 16 + end + end + return 8 +end + +return Pcm diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau new file mode 100644 index 0000000..df4350b --- /dev/null +++ b/src/Formats/codecs/Tracker/Player.luau @@ -0,0 +1,1837 @@ +--!strict +--!native +-- codecs/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, +-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric +-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes, +-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song +-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, +-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/Tracker/Mixer. +-- +-- Never throws: the module is validated by codecs/Tracker before a player is made, and every table lookup here is +-- guarded. +local Tables = require("@formats/codecs/Tracker/Tables") + +local wave64, autoWave = Tables.wave64, Tables.autoWave +local AMIGA = Tables.AMIGA +local AMIGA_PAL = Tables.AMIGA_PAL +local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs +local readu8 = buffer.readu8 + +local Player = {} + +local MOD, S3M, XM, IT = 1, 2, 3, 4 +Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT +local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } + +local MAX_VOICES = 96 -- channels + IT background voices + +-- ------------------------------------------------------------------------------------------------ state +local function newVoice(): any + return { + active = false, + chan = 0, + bg = false, + data = nil :: buffer?, + nch = 1, + len = 0, + loopS = 0, + loopE = 0, + loopT = 0, + susS = 0, + susE = 0, + susT = 0, + p = 0, + dir = 1, + inc = 0, + smp = nil :: any, + smpIdx = 0, + ins = nil :: any, + insIdx = 0, + note = 0, + vol = 0, + pan = 128, + chanVol = 64, + period = 0, + periodOut = 0, + base = 8363, + keyOn = true, + fading = false, + fade = 65536, + volEnvPos = 0, + panEnvPos = 0, + pitchEnvPos = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + envVol = 64, + envPan = 0, + envPitch = 0, + avPos = 0, + avAmp = 0, + gl = 0, + gr = 0, + tl = 0, + tr = 0, + started = false, + cutoff = 127, + reso = 0, + fOn = false, + fa = 1, + fb0 = 0, + fb1 = 0, + y1l = 0, + y2l = 0, + y1r = 0, + y2r = 0, + tremorMute = false, + surround = false, + rampN = 0, + order = 0, -- allocation age + } +end + +local function newChannel(i: number, pan: number, vol: number): any + return { + idx = i, + voice = nil :: any, + note = 0, + realNote = 0, + insIdx = 0, + smpIdx = 0, + smp = nil :: any, + vol = 0, + pan = pan, + chanVol = vol, + period = 0, + target = 0, + portaSpeed = 0, + base = 8363, + finetune = nil :: number?, + fx = 0, + param = 0, + vcmd = 0, + -- memories + mPortaUp = 0, + mPortaDn = 0, + mFineUp = 0, + mFineDn = 0, + mXFineUp = 0, + mXFineDn = 0, + mVolSlide = 0, + mFineVolUp = 0, + mFineVolDn = 0, + mOffset = 0, + mHighOffset = 0, + mPanSlide = 0, + mGVolSlide = 0, + mRetrig = 0, + mTremor = 0, + mArp = 0, + mS3M = 0, + mEF = 0, + mChanVolSlide = 0, + mTempo = 0, + mVolCol = 0, + mS = 0, + vibSpeed = 0, + vibDepth = 0, + vibPos = 0, + vibWave = 0, + tremSpeed = 0, + tremDepth = 0, + tremPos = 0, + tremWave = 0, + panbSpeed = 0, + panbDepth = 0, + panbPos = 0, + panbWave = 0, + vibDelta = 0, + tremDelta = 0, + panbDelta = 0, + arp = 0, + loopRow = 0, + loopCount = 0, + retrigCount = 0, + tremorCount = 0, + tremorOn = true, + delayTick = -1, + dNote = 0, + dIns = 0, + dVol = 0, + cutTick = -1, + keyOffTick = -1, + nna = -1, + surround = false, + cutoff = 127, + reso = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + muted = false, + triggered = false, + } +end + +-- new(module, opts) -> player state (module validated by the caller) +function Player.new(m: any, sampleRate: number, opts: any): any + local fmt = FAMILY[m.format] or MOD + local st: any = { + m = m, + fmt = fmt, + sr = sampleRate, + nch = m.channels, + speed = m.speed, + tempo = m.tempo, + gvol = m.globalVolume, + linear = m.linear, + insMode = m.instrumentMode and #m.instruments > 0, + oldFx = m.flags.oldEffects or false, + compatG = m.flags.compatGxx or false, + fastSlides = m.flags.fastSlides or false, + amigaLimits = m.flags.amigaLimits or false, + ord = 0, + row = 0, + tick = 0, + pat = nil :: any, + patIdx = -1, + patDelay = 0, + patDelayRep = 0, + fineDelay = 0, + jumpOrd = -1, + breakRow = -1, + loopJump = -1, + ended = false, + visited = {} :: { [number]: boolean }, + chans = {}, + voices = {}, + age = 0, + tickFrames = 0, + frac = 0, + separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), + master = 1, + rows = 0, + ramp = 64, + amiga = if fmt == MOD then AMIGA_PAL else AMIGA, + loopAllowed = opts and opts.loop or false, + } + for i = 1, m.channels do + local pan = m.channelPan[i] or 128 + local cv = m.channelVolume[i] or 64 + local c = newChannel(i, pan, cv) + c.muted = m.channelMute[i] or false + if pan == 512 then -- surround marker + c.pan = 128 + c.surround = true + end + st.chans[i] = c + end + for i = 1, MAX_VOICES do + st.voices[i] = newVoice() + end + st.master = Player.masterGain(m, fmt) + Player.startOrder(st, 0, 0) + return st +end + +-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at +-- volume 64 on one centred channel) +function Player.masterGain(m: any, fmt: number): number + if fmt == IT then + return 0.5 * (m.mixVolume or 48) / 48 + elseif fmt == S3M then + return 0.5 * (m.mixVolume or 48) / 48 + end + -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) + return 2 / clamp(m.channels, 2, 8) +end + +-- ------------------------------------------------------------------------------------------------ orders and rows +-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended +function Player.startOrder(st: any, ord: number, row: number) + local m = st.m + local order = m.order + local n = #order + local guard = 0 + local o = ord + while true do + guard += 1 + if guard > n + 2 then + st.ended = true + return + end + if o >= n then + o = m.restart or 0 + if o >= n or o < 0 then + o = 0 + end + if n == 0 then + st.ended = true + return + end + end + local p = order[o + 1] + if p == 255 then + o = n -- the end marker: wrap to the restart position + elseif p == 254 or m.patterns[p + 1] == nil then + o += 1 + else + st.ord = o + st.patIdx = p + st.pat = m.patterns[p + 1] + st.row = if row < st.pat.rows then row else 0 + return + end + end +end + +local function advanceRow(st: any) + if st.stopAfterRow then + st.ended = true + return + end + local loopRow = st.loopJump + if st.jumpOrd >= 0 or st.breakRow >= 0 then + local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 + local r = if st.breakRow >= 0 then st.breakRow else 0 + st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + Player.startOrder(st, o, r) + return + end + if loopRow >= 0 then + st.loopJump = -1 + -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check + for r = loopRow, st.row do + st.visited[st.ord * 1024 + r] = nil + end + st.row = loopRow + return + end + st.row += 1 + if st.row >= st.pat.rows then + Player.startOrder(st, st.ord + 1, 0) + end +end + +-- ------------------------------------------------------------------------------------------------ pitch +-- the period of a note for a sample (see codecs/Tracker for the two period spaces) +local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number) + local base, ref, tr + if st.fmt == MOD or st.fmt == XM then + base, ref = 8363, 49 + tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 + else + base, ref, tr = smp.c5speed or 8363, 61, 0 + if base <= 0 then + base = 8363 + end + end + local plin = (ref - note) * 64 - tr + if st.fmt == MOD then + -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) + local ftp = (ft or smp.finetune or 0) / 16 + return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base + end + if st.linear then + return plin, base + end + return 1712 * 8363 / base * 2 ^ (plin / 768), base +end + +local function arpPeriod(st: any, period: number, semis: number): number + if semis == 0 then + return period + end + if st.linear then + return period - semis * 64 + end + return period * 2 ^ (-semis / 12) +end + +local function clampPeriod(st: any, c: any) + if st.linear then + c.period = clamp(c.period, -6000, 6000) + elseif st.amigaLimits then + c.period = clamp(c.period, 113 * 4, 856 * 4) + else + c.period = clamp(c.period, 1, 1e6) + end +end + +-- ------------------------------------------------------------------------------------------------ voices +local function allocVoice(st: any): any + local best, bestScore = nil, math.huge + for _, v in st.voices do + if not v.active then + return v + end + if v.bg then + local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 + if s < bestScore then + best, bestScore = v, s + end + end + end + if best then + best.active = false + return best + end + return st.voices[1] -- unreachable while MAX_VOICES > channels: every channel holds one foreground voice +end + +local function keyOff(st: any, v: any) + if not v or not v.active then + return + end + v.keyOn = false + local ins = v.ins + if st.fmt == XM then + if not (ins and ins.volEnv and ins.volEnv.enabled) then + v.vol = 0 + local c = st.chans[v.chan] + if c and c.voice == v then + c.vol = 0 + end + else + v.fading = true + end + elseif st.fmt == IT then + if ins then + local env = ins.volEnv + if not (env and env.enabled and v.volEnvOn) or env.loop then + v.fading = true + end + end + end +end + +local function noteFade(v: any) + if v and v.active then + v.fading = true + end +end + +local function cutVoice(v: any) + if v then + v.active = false + end +end + +-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c +local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: boolean) + local v = c.voice + if v == nil or v.bg then + v = allocVoice(st) + c.voice = v + end + local wasActive = v.active + v.active = smp.length > 0 and smp.data ~= nil + v.chan = c.idx + v.bg = false + v.smp = smp + v.smpIdx = smpIdx + v.data = smp.data + v.nch = smp.channels or 1 + v.len = smp.length + v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType + v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 + v.p = 0 + v.dir = 1 + v.ins = ins + v.insIdx = insIdx + v.note = note + v.period = period + v.periodOut = period + v.base = base + st.age += 1 + v.order = st.age + if not keepEnv then + v.keyOn = true + v.fading = false + v.fade = 65536 + v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 + v.avPos, v.avAmp = 0, 0 + v.envVol, v.envPan, v.envPitch = 64, 0, 0 + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 + end + if not wasActive then + v.gl, v.gr = 0, 0 + end + return v +end + +-- IT new note actions on the channel's current voice (and duplicate checks on all its voices) +local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) + -- duplicate check: voices of this channel playing the same instrument + if ins and ins.dct and ins.dct > 0 then + for _, u in st.voices do + if u.active and u.chan == c.idx and u.insIdx == insIdx then + local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 + if dup then + local a = ins.dca or 0 + if a == 0 then + cutVoice(u) + elseif a == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + end + end + local v = c.voice + if v == nil or not v.active then + return + end + local nna = c.nna + if nna < 0 then + nna = if v.ins then (v.ins.nna or 0) else 0 + end + if nna == 0 then + -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) + v.active = false + return + end + v.bg = true + c.voice = nil + if nna == 2 then + keyOff(st, v) + elseif nna == 3 then + noteFade(v) + end +end + +-- ------------------------------------------------------------------------------------------------ triggering +local function isPorta(st: any, fx: number, vcmd: number): boolean + local f = st.fmt + if f == MOD then + return fx == 3 or fx == 5 + elseif f == XM then + return fx == 3 or fx == 5 or (vcmd >= 0xF0) + end + -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) + return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) +end + +-- the sample and real note for an instrument number + note +local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) + local m = st.m + if st.insMode then + local ins = m.instruments[insIdx] + if not ins or note < 1 or note > 120 then + return nil, 0, ins, note + end + local si = ins.sampleMap[note] or 0 + local rn = ins.noteMap[note] or note + local smp = m.samples[si] + return smp, si, ins, rn + end + local smp = m.samples[insIdx] + return smp, insIdx, nil, note +end + +local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) + if smp then + c.vol = smp.volume + if smp.pan then + c.pan = smp.pan + c.surround = false + end + end + if ins and st.fmt == IT then + if ins.pan and not (smp and smp.pan) then + c.pan = ins.pan + c.surround = false + end + if ins.cutoff then + c.cutoff = ins.cutoff + end + if ins.resonance then + c.reso = ins.resonance + end + end +end + +local function sampleOffset(st: any, c: any, v: any) + local f = st.fmt + local fx, param = c.fx, c.param + local off = -1 + if (f == MOD or f == XM) and fx == 9 then + if param > 0 then + c.mOffset = param + end + off = (if f == XM then c.mOffset else param) * 256 + elseif (f == S3M or f == IT) and fx == 15 then + if param > 0 then + c.mOffset = param + end + off = c.mOffset * 256 + (if f == IT then c.mHighOffset * 65536 else 0) + end + if off > 0 and v and v.active then + if off >= v.len then + if v.loopT > 0 and f ~= MOD then + off = v.loopS + elseif f == MOD and v.loopT > 0 then + off = v.loopS + else + v.active = false + return + end + end + v.p = off + end +end + +-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell +local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) + local f = st.fmt + local m = st.m + local porta = isPorta(st, c.fx, vcmd) + local hasNote = note >= 1 and note <= 120 + if insIdx > 0 then + local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil + if valid then + local prev = c.insIdx + c.insIdx = insIdx + local n = if hasNote then note else c.note + local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) + setInstrumentDefaults(st, c, smp, ins) + if not hasNote then + local v = c.voice + if f == XM and v and v.active and (prev == insIdx) then + -- an instrument number alone restarts the envelopes (FT2) + v.keyOn, v.fading, v.fade = true, false, 65536 + v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 + elseif (f == MOD or f == S3M) and smp then + c.smp, c.smpIdx = smp, insIdx + end + end + elseif f == XM and hasNote then + -- an empty instrument: the note stops the channel + c.insIdx = insIdx + if c.voice then + c.voice.active = false + end + hasNote = false + end + end + if hasNote then + local useIns = c.insIdx + local smp, smpIdx, ins, realNote = resolve(st, useIns, note) + if smp == nil then + if (f == MOD or f == S3M) and c.smp then + smp, smpIdx = c.smp, c.smpIdx + end + end + if smp then + local ft = c.finetune + local period, base = notePeriod(st, realNote, smp, ft) + local v = c.voice + if porta and v and v.active then + c.target = period + if st.fmt == IT or st.fmt == S3M then + c.note = note + end + else + if f == IT and st.insMode then + newNoteAction(st, c, ins, useIns, realNote, smpIdx) + end + local keep = f == XM and insIdx == 0 and c.voice ~= nil + c.triggered = true + c.retrigCount = 0 + v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + c.period, c.target, c.base = period, period, base + c.note, c.realNote = note, realNote + c.smp, c.smpIdx = smp, smpIdx + if insIdx > 0 or f == MOD or f == S3M then + -- volume was set by the instrument; MOD / S3M keep the channel volume + end + if c.vibWave < 4 then + c.vibPos = 0 + end + if c.tremWave < 4 then + c.tremPos = 0 + end + v.cutoff, v.reso = c.cutoff, c.reso + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + c.nna = -1 + sampleOffset(st, c, v) + end + elseif f == IT or f == XM then + -- a note mapped to no sample cuts + if c.voice and not porta then + if f == IT and st.insMode then + newNoteAction(st, c, nil, 0, note, 0) + end + if c.voice then + c.voice.active = false + end + end + end + elseif note == 255 then + if f == S3M or f == MOD then + cutVoice(c.voice) + elseif c.voice then + keyOff(st, c.voice) + end + elseif note == 254 then + cutVoice(c.voice) + if f ~= IT then + c.vol = 0 + end + elseif note == 253 then + noteFade(c.voice) + end + -- the volume column's set-volume / set-panning parts (the rest runs with the effects) + if vcmd > 0 then + if f == S3M then + c.vol = min(vcmd - 1, 64) + elseif f == XM then + if vcmd >= 0x10 and vcmd <= 0x50 then + c.vol = vcmd - 0x10 + elseif vcmd >= 0xC0 and vcmd <= 0xCF then + c.pan = (vcmd - 0xC0) * 16 + end + elseif f == IT then + local v = vcmd - 1 + if v <= 64 then + c.vol = v + elseif v >= 128 and v <= 192 then + c.pan = (v - 128) * 4 + c.surround = false + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ effect helpers +local function volSlideMod(c: any, param: number) + local x, y = param // 16, param % 16 + if x > 0 then + c.vol = min(64, c.vol + x) + else + c.vol = max(0, c.vol - y) + end +end + +local function tonePorta(st: any, c: any, speed: number) + if c.target == 0 or c.period == c.target then + return + end + if c.period < c.target then + c.period = min(c.period + speed, c.target) + else + c.period = max(c.period - speed, c.target) + end +end + +local function vibrato(st: any, c: any, scale: number) + c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale + c.vibPos = (c.vibPos + c.vibSpeed) % 64 +end + +local function tremolo(c: any, scale: number) + c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) + c.tremPos = (c.tremPos + c.tremSpeed) % 64 +end + +local function retrigVoice(st: any, c: any) + local v = c.voice + if v and v.smp then + v.active = v.smp.length > 0 + v.p = 0 + v.dir = 1 + end +end + +local function retrigVolume(c: any, x: number) + if x == 0 or x == 8 then + return + end + local mul = Tables.RETRIG_MUL[x + 1] + if mul ~= 1 then + c.vol = floor(c.vol * mul) + else + c.vol += Tables.RETRIG_ADD[x + 1] + end + c.vol = clamp(c.vol, 0, 64) +end + +-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; +-- fast: normal parts on tick 0 too) +local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number + local x, y = param // 16, param % 16 + if y == 0xF and x > 0 then + if tick == 0 then + return min(hi, value + x) + end + return value + elseif x == 0xF and y > 0 then + if tick == 0 then + return max(0, value - y) + end + return value + end + if tick == 0 and not fast then + return value + end + if y == 0 then + return min(hi, value + x) + elseif x == 0 then + return max(0, value - y) + end + return value +end + +-- ------------------------------------------------------------------------------------------------ MOD / XM effects +local function fxModXm(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local xm = st.fmt == XM + local x, y = param // 16, param % 16 + if fx == 0 then + if param ~= 0 then + local k = tick % 3 + c.arp = if k == 1 then x elseif k == 2 then y else 0 + end + elseif fx == 1 then + if xm and param > 0 then + c.mPortaUp = param + end + if tick > 0 then + c.period -= (if xm then c.mPortaUp else param) * 4 + clampPeriod(st, c) + end + elseif fx == 2 then + if xm and param > 0 then + c.mPortaDn = param + end + if tick > 0 then + c.period += (if xm then c.mPortaDn else param) * 4 + clampPeriod(st, c) + end + elseif fx == 3 or fx == 5 then + if fx == 3 and param > 0 then + c.portaSpeed = param + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif fx == 4 or fx == 6 then + if fx == 4 then + if x > 0 then + c.vibSpeed = x + end + if y > 0 then + c.vibDepth = y + end + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif fx == 7 then + if x > 0 then + c.tremSpeed = x + end + if y > 0 then + c.tremDepth = y + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 8 then + if tick == 0 then + c.pan = param + c.surround = false + end + elseif fx == 0xB then + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 0xC then + if tick == 0 then + c.vol = min(param, 64) + end + elseif fx == 0xD then + if tick == 0 then + local r = x * 10 + y + if r > 63 then + r = 0 + end + st.breakRow = r + end + elseif fx == 0xE then + if x == 1 then + if xm and y > 0 then + c.mFineUp = y + end + if tick == 0 then + c.period -= (if xm then c.mFineUp else y) * 4 + clampPeriod(st, c) + end + elseif x == 2 then + if xm and y > 0 then + c.mFineDn = y + end + if tick == 0 then + c.period += (if xm then c.mFineDn else y) * 4 + clampPeriod(st, c) + end + elseif x == 4 then + c.vibWave = y % 8 + elseif x == 6 then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + end + end + end + elseif x == 7 then + c.tremWave = y % 8 + elseif x == 8 then + if tick == 0 and not xm then + c.pan = y * 17 + c.surround = false + end + elseif x == 9 then + if y > 0 and tick > 0 and tick % y == 0 then + retrigVoice(st, c) + end + elseif x == 0xA then + if xm and y > 0 then + c.mFineVolUp = y + end + if tick == 0 then + c.vol = min(64, c.vol + (if xm then c.mFineVolUp else y)) + end + elseif x == 0xB then + if xm and y > 0 then + c.mFineVolDn = y + end + if tick == 0 then + c.vol = max(0, c.vol - (if xm then c.mFineVolDn else y)) + end + elseif x == 0xC then + if tick == y then + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 0xF then + if tick == 0 then + if param == 0 then + if not xm then + st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) + end + elseif param < 32 then + st.speed = param + else + st.tempo = param + end + end + elseif fx == 16 then -- G + if tick == 0 then + st.gvol = min(param, 64) * 2 + end + elseif fx == 17 then -- H + if param > 0 then + c.mGVolSlide = param + end + if tick > 0 then + local p = c.mGVolSlide + local px, py = p // 16, p % 16 + if px > 0 then + st.gvol = min(128, st.gvol + px * 2) + else + st.gvol = max(0, st.gvol - py * 2) + end + end + elseif fx == 20 then -- K + if tick == param then + keyOff(st, c.voice) + end + elseif fx == 21 then -- L + if tick == 0 and c.voice then + c.voice.volEnvPos = param + c.voice.panEnvPos = param + end + elseif fx == 25 then -- P + if param > 0 then + c.mPanSlide = param + end + if tick > 0 then + local p = c.mPanSlide + local px, py = p // 16, p % 16 + if px > 0 then + c.pan = min(255, c.pan + px) + else + c.pan = max(0, c.pan - py) + end + end + elseif fx == 27 then -- R + if x > 0 then + c.mRetrig = c.mRetrig % 16 + x * 16 + end + if y > 0 then + c.mRetrig = (c.mRetrig // 16) * 16 + y + end + local interval = c.mRetrig % 16 + if tick == 0 and c.triggered then + c.retrigCount = 0 + else + c.retrigCount += 1 + end + if interval > 0 and c.retrigCount >= interval then + c.retrigCount = 0 + retrigVolume(c, c.mRetrig // 16) + retrigVoice(st, c) + end + elseif fx == 29 then -- T + if param > 0 then + c.mTremor = param + end + elseif fx == 33 then -- X + if x == 1 then + if y > 0 then + c.mXFineUp = y + end + if tick == 0 then + c.period -= c.mXFineUp + clampPeriod(st, c) + end + elseif x == 2 then + if y > 0 then + c.mXFineDn = y + end + if tick == 0 then + c.period += c.mXFineDn + clampPeriod(st, c) + end + end + end + -- the volume slide half of 5xy / 6xy and Axy + if fx == 0xA or fx == 5 or fx == 6 then + if xm then + if param > 0 then + c.mVolSlide = param + end + if tick > 0 then + volSlideMod(c, c.mVolSlide) + end + elseif tick > 0 then + volSlideMod(c, param) + end + end + -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks + if fx == 29 and tick > 0 then + local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 + c.tremorCount = (c.tremorCount + 1) % (on + off) + c.tremorOn = c.tremorCount < on + end +end + +-- the XM volume column (everything but set volume / set panning, done by trigger) +local function volColXm(st: any, c: any, tick: number) + local v = c.vcmd + if v < 0x60 then + return + end + local hi, lo = v // 16, v % 16 + if hi == 6 then + if tick > 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 7 then + if tick > 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 8 then + if tick == 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 9 then + if tick == 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 0xA then + if lo > 0 then + c.vibSpeed = lo + end + elseif hi == 0xB then + if lo > 0 then + c.vibDepth = lo + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif hi == 0xD then + if tick > 0 then + c.pan = max(0, c.pan - lo) + end + elseif hi == 0xE then + if tick > 0 then + c.pan = min(255, c.pan + lo) + end + elseif hi == 0xF then + if lo > 0 then + c.portaSpeed = lo * 16 + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ S3M / IT effects +-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects +local function mem(st: any, c: any, field: string, param: number): number + if st.fmt == S3M then + if param > 0 then + c.mS3M = param + end + return c.mS3M + end + if param > 0 then + c[field] = param + end + return c[field] +end + +local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) + if p >= 0xF0 then + if tick == 0 then + c.period += sign * (p % 16) * 4 + end + elseif p >= 0xE0 then + if tick == 0 then + c.period += sign * (p % 16) + end + elseif tick > 0 then + c.period += sign * p * 4 + end + clampPeriod(st, c) +end + +local function fxS3mIt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local it = st.fmt == IT + if fx == 1 then -- A speed + if tick == 0 and param > 0 then + st.speed = param + end + elseif fx == 2 then -- B jump + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 3 then -- C break + if tick == 0 then + st.breakRow = if it then param else (param // 16) * 10 + param % 16 + end + elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) + local p = mem(st, c, "mVolSlide", param) + c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) + elseif fx == 5 then -- E porta down + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, 1) + elseif fx == 6 then -- F porta up + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, -1) + elseif fx == 9 then -- I tremor + local p = mem(st, c, "mTremor", param) + if tick > 0 or not it then + local on, off = p // 16, p % 16 + if it and st.oldFx or not it then + on, off = on + 1, off + 1 + end + on, off = max(on, 1), max(off, 1) + c.tremorCount = (c.tremorCount + 1) % (on + off) + c.tremorOn = c.tremorCount < on + end + elseif fx == 10 then -- J arpeggio + local p = mem(st, c, "mArp", param) + local k = tick % 3 + c.arp = if k == 1 then p // 16 elseif k == 2 then p % 16 else 0 + elseif fx == 13 then -- M channel volume + if tick == 0 and param <= 64 then + c.chanVol = param + end + elseif fx == 14 then -- N channel volume slide + local p = mem(st, c, "mChanVolSlide", param) + c.chanVol = dSlide(c.chanVol, p, tick, false, 64) + elseif fx == 16 then -- P panning slide (0..64 scale x 4) + local p = mem(st, c, "mPanSlide", param) + local pan64 = c.pan / 4 + local x, y = p // 16, p % 16 + if y == 0xF and x > 0 then + if tick == 0 then + pan64 = max(0, pan64 - x) + end + elseif x == 0xF and y > 0 then + if tick == 0 then + pan64 = min(64, pan64 + y) + end + elseif tick > 0 then + if y == 0 then + pan64 = max(0, pan64 - x) + elseif x == 0 then + pan64 = min(64, pan64 + y) + end + end + c.pan = pan64 * 4 + c.surround = false + elseif fx == 17 then -- Q retrigger + volume change + local p = mem(st, c, "mRetrig", param) + local interval = p % 16 + if interval > 0 then + if tick == 0 and c.retrigCount <= 0 then + c.retrigCount = interval + end + if tick > 0 then + c.retrigCount -= 1 + if c.retrigCount <= 0 then + c.retrigCount = interval + retrigVolume(c, p // 16) + retrigVoice(st, c) + end + end + end + elseif fx == 18 then -- R tremolo + if param // 16 > 0 then + c.tremSpeed = param // 16 + end + if param % 16 > 0 then + c.tremDepth = param % 16 + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 19 then -- S extended + local p = if it then mem(st, c, "mS", param) else mem(st, c, "mS", param) + local x, y = p // 16, p % 16 + if x == 3 then + c.vibWave = y % 8 + elseif x == 4 then + c.tremWave = y % 8 + elseif x == 5 then + c.panbWave = y % 8 + elseif x == 6 then + if tick == 0 then + st.fineDelay += y + end + elseif x == 7 then + if tick == 0 then + if y <= 2 then + for _, u in st.voices do + if u.active and u.bg and u.chan == c.idx then + if y == 0 then + cutVoice(u) + elseif y == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + elseif y <= 6 then + c.nna = y - 3 + else + local v = c.voice + if v then + if y == 7 then + v.volEnvOn = false + elseif y == 8 then + v.volEnvOn = true + elseif y == 9 then + v.panEnvOn = false + elseif y == 10 then + v.panEnvOn = true + elseif y == 11 then + v.pitchEnvOn = false + elseif y == 12 then + v.pitchEnvOn = true + end + end + end + end + elseif x == 8 then + if tick == 0 then + c.pan = y * 17 + c.surround = false + end + elseif x == 9 then + if tick == 0 and y == 1 then + c.surround = true + end + elseif x == 0xA then + if tick == 0 then + c.mHighOffset = y + end + elseif x == 0xB then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + elseif it then + c.loopRow = st.row + 1 + end + end + end + elseif x == 0xC then + local at = if y == 0 and it then 1 else y + if tick == at and (y > 0 or it) then + if it then + cutVoice(c.voice) + end + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 20 then -- T tempo + if param >= 0x20 then + if tick == 0 then + st.tempo = param + end + elseif it then + if param > 0 then + c.mTempo = param + end + local p = c.mTempo + if tick > 0 then + if p >= 0x10 then + st.tempo = min(255, st.tempo + (p - 0x10)) + else + st.tempo = max(32, st.tempo - p) + end + end + end + elseif fx == 22 then -- V global volume + if tick == 0 then + if it then + if param <= 128 then + st.gvol = param + end + else + st.gvol = min(param, 64) * 2 + end + end + elseif fx == 23 then -- W global volume slide + local p = mem(st, c, "mGVolSlide", param) + st.gvol = dSlide(st.gvol, p, tick, false, 128) + elseif fx == 24 then -- X panning + if tick == 0 then + if it then + c.pan = param + c.surround = false + elseif param <= 0x80 then + c.pan = param * 2 + c.surround = false + elseif param == 0xA4 then + c.surround = true + end + end + elseif fx == 25 then -- Y panbrello + if param // 16 > 0 then + c.panbSpeed = param // 16 + end + if param % 16 > 0 then + c.panbDepth = param % 16 + end + c.panbDelta = wave64(c.panbWave % 4, c.panbPos // 4) * c.panbDepth / 16 + c.panbPos = (c.panbPos + c.panbSpeed) % 256 + elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) + if tick == 0 then + if param < 0x80 then + c.cutoff = param + elseif param < 0x90 then + c.reso = (param - 0x80) * 8 + end + if c.voice then + c.voice.cutoff, c.voice.reso = c.cutoff, c.reso + end + end + end + -- tone portamento (G, L) + if fx == 7 or fx == 12 then + if fx == 7 then + if st.fmt == S3M then + if param > 0 then + c.portaSpeed = param + end + elseif st.compatG then + if param > 0 then + c.portaSpeed = param + end + else + if param > 0 then + c.mEF = param + end + c.portaSpeed = c.mEF + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end + -- vibrato (H, U, K) + if fx == 8 or fx == 21 or fx == 11 then + if fx ~= 11 then + if param // 16 > 0 then + c.vibSpeed = param // 16 + end + if param % 16 > 0 then + c.vibDepth = param % 16 + end + end + local scale = if fx == 21 then 2 / 255 else 8 / 255 + if it and not st.oldFx then + scale /= 2 + end + if tick > 0 or (it and not st.oldFx) then + vibrato(st, c, scale) + end + end +end + +-- the IT volume column (value stored + 1): slides, portamento, vibrato +local function volColIt(st: any, c: any, tick: number) + local v = c.vcmd - 1 + if v < 65 then + return + end + if v <= 74 then + local p = v - 65 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 84 then + local p = v - 75 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 94 then + local p = v - 85 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 104 then + local p = v - 95 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 114 then + local p = (v - 105) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period += c.mEF * 4 + clampPeriod(st, c) + end + elseif v <= 124 then + local p = (v - 115) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period -= c.mEF * 4 + clampPeriod(st, c) + end + elseif v >= 193 and v <= 202 then + local p = Tables.IT_VOLPORTA[v - 192] or 0 + if p > 0 then + if st.compatG then + c.portaSpeed = p + else + c.mEF = p + c.portaSpeed = p + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif v >= 203 and v <= 212 then + local d = v - 203 + if d > 0 then + c.vibDepth = d + end + if tick > 0 or not st.oldFx then + vibrato(st, c, if st.oldFx then 8 / 255 else 4 / 255) + end + end +end + +-- ------------------------------------------------------------------------------------------------ rows and ticks +local function noteDelayOf(st: any, fx: number, param: number): number + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then + return param % 16 + elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then + return param % 16 + end + return 0 +end + +local function finetuneOf(st: any, fx: number, param: number): number? + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then + local y = param % 16 + if st.fmt == MOD then + return (if y >= 8 then y - 16 else y) * 16 + end + return (y - 8) * 16 + end + return nil +end + +local function runEffects(st: any, c: any, tick: number) + c.vibDelta, c.arp = 0, 0 + if st.fmt == MOD or st.fmt == XM then + fxModXm(st, c, tick) + if st.fmt == XM then + volColXm(st, c, tick) + end + else + if st.fmt == IT then + volColIt(st, c, tick) + end + fxS3mIt(st, c, tick) + end + -- keep the tremolo / panbrello offsets only while their effect runs + local fx = c.fx + if st.fmt == MOD or st.fmt == XM then + if fx ~= 7 then + c.tremDelta = 0 + end + if fx ~= 29 then + c.tremorOn = true + end + else + if fx ~= 18 then + c.tremDelta = 0 + end + if fx ~= 9 then + c.tremorOn = true + end + if fx ~= 25 then + c.panbDelta = 0 + end + end +end + +local function processRow(st: any) + local m = st.m + local pat = st.pat + local nch = st.nch + local data = pat.data + local base = st.row * nch * 5 + st.visited[st.ord * 1024 + st.row] = true + st.rows += 1 + for i = 1, nch do + local c = st.chans[i] + local o = base + (i - 1) * 5 + local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) + if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then + fx = 255 + end + c.fx, c.param, c.vcmd = fx, param, vcmd + c.cutTick, c.keyOffTick = -1, -1 + c.triggered = false + if fx ~= 29 and fx ~= 9 then + c.tremorCount = 0 + end + local delay = noteDelayOf(st, fx, param) + c.finetune = finetuneOf(st, fx, param) + if delay > 0 then + c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd + else + c.delayTick = -1 + trigger(st, c, note, ins, vcmd) + end + runEffects(st, c, 0) + end + local _ = m +end + +local function updateEnvelope(env: any, pos: number, keyOn: boolean): (number, number, boolean) + -- returns value, next position, ended + local ticks, values = env.ticks, env.values + local n = #ticks + if n == 0 then + return 0, pos, true + end + local value + if pos <= ticks[1] then + value = values[1] + elseif pos >= ticks[n] then + value = values[n] + else + local i = 1 + while i < n and ticks[i + 1] <= pos do + i += 1 + end + local t0, t1 = ticks[i], ticks[i + 1] + if t1 > t0 then + value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) + else + value = values[i + 1] + end + end + local nextPos = pos + 1 + local ended = false + if keyOn and env.sustain and ticks[env.susEnd] and nextPos > ticks[env.susEnd] then + nextPos = ticks[env.susStart] or nextPos + elseif env.loop and ticks[env.loopEnd] and nextPos > ticks[env.loopEnd] then + nextPos = ticks[env.loopStart] or nextPos + elseif nextPos > ticks[n] then + nextPos = ticks[n] + ended = true + end + return value, nextPos, ended +end + +-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter +local function updateVoice(st: any, v: any) + local ins = v.ins + local it = st.fmt == IT + local envVol, envPan, envPitch = 64, 0, 0 + local filterEnv = nil + if ins then + local e = ins.volEnv + if e and e.enabled and v.volEnvOn then + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn) + envVol, v.volEnvPos = val, np + if ended and it then + if val <= 0 then + v.active = false + return + end + v.fading = true + end + end + e = ins.panEnv + if e and e.enabled and v.panEnvOn then + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn) + envPan, v.panEnvPos = val, np + end + e = ins.pitchEnv + if e and e.enabled and v.pitchEnvOn then + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn) + v.pitchEnvPos = np + if e.filter then + filterEnv = val + else + envPitch = val + end + end + if v.fading then + local fo = ins.fadeout or 0 + v.fade -= if it then fo * 64 else fo * 2 + if v.fade <= 0 then + v.fade = 0 + v.active = false + return + end + end + end + v.envVol = envVol + -- auto-vibrato: XM per instrument, IT per sample + local avSrc = if it then v.smp else ins + local avDelta = 0 + if avSrc and (avSrc.vibDepth or 0) > 0 then + local depth = avSrc.vibDepth + local sweep = avSrc.vibSweep or 0 + if it then + -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps + local target = depth * 256 + if sweep == 0 then + v.avAmp = target + elseif v.avAmp < target then + v.avAmp = min(target, v.avAmp + sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 + else + if sweep == 0 then + v.avAmp = depth * 256 + elseif v.keyOn then + v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) + end + v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 + end + -- frequency + local P = v.periodOut + avDelta + local freq + if st.linear then + freq = v.base * 2 ^ (-P / 768) + else + freq = if P > 0 then st.amiga / P else 0 + end + if envPitch ~= 0 then + freq *= 2 ^ (envPitch / 24) + end + v.inc = freq / st.sr + -- volume + local smp = v.smp + local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 + if it then + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) + end + if v.tremorMute then + vol = 0 + end + -- panning + local pan = v.pan + if envPan ~= 0 then + local range = 128 - abs(pan - 128) + pan += envPan * range / 32 + end + if it and ins and (ins.pps or 0) ~= 0 then + pan += (v.note - (ins.ppc or 60) - 1) * ins.pps / 2 + end + pan = clamp(pan, 0, 256) + pan = clamp(128 + (pan - 128) * st.separation, 0, 256) + local g = vol * st.master + if v.surround then + v.tl, v.tr = g * 0.5, -g * 0.5 + else + v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 + end + v.rampN = st.ramp + -- IT resonant filter + local cutoff = v.cutoff + if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then + local cc = cutoff + if filterEnv ~= nil then + cc = cutoff * (filterEnv + 32) / 64 + end + local fhz = 110 * 2 ^ (0.25 + cc / 24) + fhz = clamp(fhz, 120, min(20000, st.sr / 2)) + local dmp = 10 ^ (-v.reso * (24 / 128) / 20) + local fc = fhz * 2 * math.pi / st.sr + local d = (1 - 2 * dmp) * fc + if d > 2 then + d = 2 + end + d = (2 * dmp - d) / fc + local e = 1 / (fc * fc) + local den = 1 + d + e + v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den + v.fOn = not (cc >= 127 and v.reso == 0) + else + v.fOn = false + end +end + +-- tick(st) -> frames to mix for this tick (0 when the song ended) +function Player.tick(st: any): number + if st.ended then + return 0 + end + local tick = st.tick + if tick == 0 and st.patDelayRep == 0 then + local key = st.ord * 1024 + st.row + if st.visited[key] and not st.loopAllowed then + st.ended = true + return 0 + end + if st.visited[key] then + -- looping on: forget the song so far, keep playing + table.clear(st.visited) + end + st.fineDelay = 0 + processRow(st) + else + local t = tick % st.speed + local rep = tick >= st.speed or st.patDelayRep > 0 + for i = 1, st.nch do + local c = st.chans[i] + if c.delayTick == tick and not rep then + c.delayTick = -1 + trigger(st, c, c.dNote, c.dIns, c.dVol) + end + if rep and t == 0 then + c.vibDelta, c.arp = 0, 0 + else + runEffects(st, c, if t == 0 then 1 else t) + end + end + end + if st.ended then + return 0 + end + -- channel -> foreground voice + for i = 1, st.nch do + local c = st.chans[i] + local v = c.voice + if v and v.active and v.chan == i and not v.bg then + local P = arpPeriod(st, c.period, c.arp) + c.vibDelta + v.period, v.periodOut, v.base = c.period, P, c.base + v.vol = clamp(c.vol + c.tremDelta, 0, 64) + if c.muted then + v.vol = 0 + end + v.pan = clamp(c.pan + c.panbDelta, 0, 256) + v.surround = c.surround + v.chanVol = c.chanVol + v.tremorMute = not c.tremorOn + v.cutoff, v.reso = c.cutoff, c.reso + end + end + for _, v in st.voices do + if v.active then + updateVoice(st, v) + end + end + -- frames for this tick: 2.5 / tempo seconds, rounded per tick as OpenMPT / FT2 do + local frames = floor(st.sr * 2.5 / max(1, st.tempo) + 0.5) + -- advance + st.tick += 1 + if st.tick >= st.speed + st.fineDelay then + st.tick = 0 + if st.patDelayRep < st.patDelay then + st.patDelayRep += 1 + else + st.patDelay, st.patDelayRep = 0, 0 + advanceRow(st) + end + end + return frames +end + +return Player diff --git a/src/Formats/codecs/Tracker/Tables.luau b/src/Formats/codecs/Tracker/Tables.luau new file mode 100644 index 0000000..c621ec1 --- /dev/null +++ b/src/Formats/codecs/Tracker/Tables.luau @@ -0,0 +1,113 @@ +--!strict +--!native +-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the +-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M +-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker +-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). +local Tables = {} + +-- the ProTracker half-sine (32 steps, 0..255) +local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } + +-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) +local RANDOM: { number } = {} +do + local s = 12345 + for i = 1, 64 do + s = (s * 1103515245 + 12345) % 2147483648 + RANDOM[i] = (s // 65536) % 511 - 255 + end +end +function Tables.wave64(kind: number, pos: number): number + local p = pos % 64 + if kind == 1 then + return 255 - p * 8 + elseif kind == 2 then + return if p < 32 then 255 else -255 + elseif kind == 3 then + return RANDOM[p + 1] + end + local v = SINE32[(p % 32) + 1] + return if p >= 32 then -v else v +end + +-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. +-- IT: 0 sine, 1 ramp down, 2 square, 3 random. +local SINE256: { number } = {} +for i = 0, 255 do + SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) +end +function Tables.autoWave(kind: number, pos: number, it: boolean): number + local p = pos % 256 + if it then + if kind == 1 then + return 64 - (p + 1) // 2 + elseif kind == 2 then + return if p < 128 then 64 else -64 + elseif kind == 3 then + return RANDOM[(p % 64) + 1] // 4 + end + return SINE256[p + 1] + end + if kind == 1 then + return if p < 128 then 64 else -64 + elseif kind == 2 then + return 64 - (p + 1) // 2 + elseif kind == 3 then + return (p + 1) // 2 - 64 + end + return SINE256[p + 1] +end + +-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: +-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at +-- its base rate (8363 Hz). +local PERIODS = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, +} +Tables.PERIODS = PERIODS +Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) + +-- periodToNote(period) -> note (1..120), 0 for period 0 +function Tables.periodToNote(period: number): number + if period <= 0 then + return 0 + end + -- exact match first, then the nearest note on a log scale + for i = 1, #PERIODS do + if PERIODS[i] == period then + return i + Tables.PERIOD_FIRST_NOTE - 1 + end + end + local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) + return math.clamp(n, 1, 120) +end + +-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends +function Tables.noteToPeriod(note: number): number + local i = note - Tables.PERIOD_FIRST_NOTE + 1 + if i >= 1 and i <= #PERIODS then + return PERIODS[i] + end + return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) +end + +-- IT volume column "g" (tone portamento) speeds +Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } + +-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value +Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } +Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } + +-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate +-- (FT2 / ST3 period units, 4x ProTracker's) +Tables.AMIGA = 8363 * 1712 +-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) +Tables.AMIGA_PAL = 7093789.2 / 2 * 4 + +return Tables diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/Tracker/init.luau new file mode 100644 index 0000000..8412ef1 --- /dev/null +++ b/src/Formats/codecs/Tracker/init.luau @@ -0,0 +1,513 @@ +--!strict +-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read +-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio +-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM +-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. +-- +-- local Tracker = require("@formats/codecs/Tracker") +-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder +-- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- +-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): +-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks +-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) +-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) +-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) +-- linear linear frequency slides (XM / IT flag) or Amiga periods +-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column +-- is a sample number (MOD, S3M, IT sample mode) +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) } +-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, +-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } +-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels +-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = +-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 +-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the +-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; +-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1 +-- (0 = none). Tracker.cell / Tracker.setCell read and write cells. +-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, +-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), +-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), +-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / +-- vibRate (IT auto-vibrato) } +-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, +-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, +-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, +-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), +-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } +-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, +-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } +-- +-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768). +-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add +-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: +-- base = c5speed, ref 61. +-- +-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects +-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Player = require("@formats/codecs/Tracker/Player") +local Mixer = require("@formats/codecs/Tracker/Mixer") +local Pcm = require("@formats/codecs/Tracker/Pcm") +local Tables = require("@formats/codecs/Tracker/Tables") + +local Tracker = {} + +Tracker.Pcm = Pcm +Tracker.Tables = Tables + +export type Envelope = { + enabled: boolean, + ticks: { number }, + values: { number }, + loop: boolean, + loopStart: number, + loopEnd: number, + sustain: boolean, + susStart: number, + susEnd: number, + carry: boolean?, + filter: boolean?, +} + +export type Pattern = { rows: number, data: buffer } + +export type RenderOptions = { + sampleRate: number?, -- default 44100 + interpolation: ("linear" | "none")?, -- default "linear" + stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre) + loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false + maxDuration: number?, -- seconds; the render stops there (default 3600) +} + +local CELL = 5 + +-- ------------------------------------------------------------------------------------------------ constructors +-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults +function Tracker.newModule(format: string, channels: number): any + local m = { + kind = "music", + format = format, + title = "", + channels = channels, + speed = 6, + tempo = 125, + globalVolume = 128, + mixVolume = 48, + order = {}, + restart = 0, + linear = format == "xm" or format == "it", + instrumentMode = format == "xm" or format == "it", + flags = {}, + channelPan = {}, + channelVolume = {}, + channelMute = {}, + patterns = {}, + instruments = {}, + samples = {}, + meta = {}, + render = Tracker.renderMethod, + } + for i = 1, channels do + m.channelVolume[i] = 64 + if format == "mod" then + local k = (i - 1) % 4 + m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width + else + m.channelPan[i] = 128 + end + end + return m +end + +-- newPattern(rows, channels) -> an empty Pattern +function Tracker.newPattern(rows: number, channels: number): Pattern + return { rows = rows, data = buffer.create(rows * channels * CELL) } +end + +-- newSample() -> an empty Sample +function Tracker.newSample(name: string?): any + return { + name = name or "", + data = buffer.create(0), + length = 0, + channels = 1, + bits = 8, + loopStart = 0, + loopEnd = 0, + loopType = 0, + susStart = 0, + susEnd = 0, + susType = 0, + volume = 64, + globalVolume = 64, + pan = nil :: number?, + c5speed = 8363, + relativeNote = 0, + finetune = 0, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.newEnvelope(): Envelope + return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } +end + +-- newInstrument() -> an Instrument mapping every note to sample 0 (none) +function Tracker.newInstrument(name: string?): any + local sm, nm = table.create(120, 0), table.create(120, 0) + for i = 1, 120 do + nm[i] = i + end + return { + name = name or "", + sampleMap = sm, + noteMap = nm, + volEnv = nil :: Envelope?, + panEnv = nil :: Envelope?, + pitchEnv = nil :: Envelope?, + fadeout = 0, + nna = 0, + dct = 0, + dca = 0, + globalVolume = 128, + pan = nil :: number?, + pps = 0, + ppc = 60, + cutoff = nil :: number?, + resonance = nil :: number?, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, +-- channel 1-based); nil when out of range +function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number) + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return nil, 0, 0, 0, 0 + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) +end + +-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) +function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return false + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + buffer.writeu8(d, o, note % 256) + buffer.writeu8(d, o + 1, ins % 256) + buffer.writeu8(d, o + 2, vol % 256) + buffer.writeu8(d, o + 3, fx % 256) + buffer.writeu8(d, o + 4, param % 256) + return true +end + +-- ------------------------------------------------------------------------------------------------ validation +local function num(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v >= lo and v <= hi +end + +local function fixEnvelope(e: any): (any, string?) + if e == nil then + return nil + end + if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then + return nil, "bad envelope" + end + local n = math.min(#e.ticks, #e.values) + local last = -1 + for i = 1, n do + local t, v = e.ticks[i], e.values[i] + if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then + -- points must go forward: keep the valid prefix + n = i - 1 + break + end + last = t + end + for i = #e.ticks, n + 1, -1 do + e.ticks[i] = nil + end + for i = #e.values, n + 1, -1 do + e.values[i] = nil + end + if n == 0 then + e.enabled = false + end + local function idx(v: any): number + return if num(v, 1, math.max(1, n)) then math.floor(v) else 1 + end + e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) + e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) + if e.loopEnd < e.loopStart then + e.loop = false + end + if e.susEnd < e.susStart then + e.sustain = false + end + return e +end + +local function fixLoop(s: number, e: number, t: number, len: number): (number, number, number) + if not num(t, 0, 2) or t == 0 then + return 0, 0, 0 + end + s, e = math.floor(math.clamp(s, 0, len)), math.floor(math.clamp(e, 0, len)) + if e - s < 1 then + return 0, 0, 0 + end + if t == 2 and e - s < 2 then + t = 1 + end + return s, e, t +end + +-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and +-- numbers into range (in place) +function Tracker.validate(m: any): (boolean?, Err.Err?) + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "not a module") + end + if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format)) + end + if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad channel count") + end + if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then + return nil, Err.new(Err.ARG, "module without order / patterns / samples") + end + m.instruments = if type(m.instruments) == "table" then m.instruments else {} + m.flags = if type(m.flags) == "table" then m.flags else {} + m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {} + m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {} + m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {} + for i = 1, m.channels do + local p = m.channelPan[i] + if p ~= 512 and not num(p, 0, 256) then + m.channelPan[i] = 128 + end + if not num(m.channelVolume[i], 0, 64) then + m.channelVolume[i] = 64 + end + end + m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6 + m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125 + m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128 + m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48 + m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0 + for i, o in m.order do + if not num(o, 0, 255) then + return nil, Err.new(Err.ARG, "bad order entry " .. i) + end + end + for i, p in m.patterns do + if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then + return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) + end + end + for i, s in m.samples do + if type(s) ~= "table" then + return nil, Err.new(Err.ARG, "bad sample " .. i) + end + local nch = if s.channels == 2 then 2 else 1 + s.channels = nch + if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then + return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") + end + s.length = math.floor(s.length) + s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) + s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) + s.volume = if num(s.volume, 0, 64) then s.volume else 64 + s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64 + if s.pan ~= nil and not num(s.pan, 0, 256) then + s.pan = nil + end + s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363 + s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0 + s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0 + end + for i, ins in m.instruments do + if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then + return nil, Err.new(Err.ARG, "bad instrument " .. i) + end + for n = 1, 120 do + if not num(ins.sampleMap[n], 0, 1e6) then + ins.sampleMap[n] = 0 + end + if not num(ins.noteMap[n], 1, 120) then + ins.noteMap[n] = n + end + end + local err + ins.volEnv, err = fixEnvelope(ins.volEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.panEnv, err = fixEnvelope(ins.panEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0 + ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128 + if ins.pan ~= nil and not num(ins.pan, 0, 256) then + ins.pan = nil + end + if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then + ins.cutoff = nil + end + if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then + ins.resonance = nil + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ rendering +local Decoder = {} +Decoder.__index = Decoder + +-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err +function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) + local ok, err = Tracker.validate(m) + if not ok then + return nil, err + end + local sr = opts and opts.sampleRate or 44100 + local maxFrames = (opts and opts.maxDuration or 3600) * sr + local st = Player.new(m, sr, { stereoSeparation = 100 }) + local frames = 0 + while frames < maxFrames do + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + frames += f + end + return math.min(frames, maxFrames) / sr +end + +local function newPlayer(self: any) + self.st = Player.new(self.module, self.sampleRate, self.opts) + self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) + self.left = 0 + self.pos = 0 +end + +-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err +function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local o: RenderOptions = opts or {} + local sr = o.sampleRate or 44100 + if type(sr) ~= "number" or sr < 1000 or sr > 384000 then + return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") + end + local seconds, err = Tracker.duration(m, o) + if not seconds then + return nil, err + end + local frames = math.floor(seconds * sr + 0.5) + local self = setmetatable({ + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = m.title or "" }, + module = m, + opts = o, + linear = o.interpolation ~= "none", + maxFrames = (o.maxDuration or 3600) * sr, + st = nil :: any, + left = 0, + pos = 0, + }, Decoder) + newPlayer(self) + return self :: any, nil +end + +-- the Module method: module:render(opts) +function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder + local dec = Tracker.render(self, opts) + return dec :: any +end + +-- run(self, out?, n) -> frames produced (out nil: advance without mixing) +local function run(self: any, out: buffer?, n: number): number + local st = self.st + local done = 0 + while done < n do + if self.left <= 0 then + if self.pos + done >= self.maxFrames then + break + end + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + self.left = f + if f == 0 then + continue + end + end + local k = math.min(self.left, n - done) + Mixer.mix(st, out, done, k, self.linear) + self.left -= k + done += k + end + self.pos += done + return done +end + +-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end) +function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(tonumber(n) or 0)) + local o = out + if o == nil or buffer.len(o) < n * 8 then + o = buffer.create(n * 8) + else + buffer.fill(o, 0, 0, n * 8) + end + local got = run(self, o, n) + return o :: buffer, got +end + +-- seek(seconds): replays the song silently up to the position (sample positions included) +function Decoder.seek(self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) + newPlayer(self) + local chunk = 65536 + while self.pos < target do + local got = run(self, nil, math.min(chunk, target - self.pos)) + if got == 0 then + break + end + end + -- the gains ramp in from silence after a seek + for _, v in self.st.voices do + v.gl, v.gr = 0, 0 + end +end + +function Decoder.position(self: any): number + return self.pos / self.sampleRate +end + +return Tracker diff --git a/src/Formats/music/mod/init.luau b/src/Formats/music/mod/init.luau new file mode 100644 index 0000000..7f4eb88 --- /dev/null +++ b/src/Formats/music/mod/init.luau @@ -0,0 +1,361 @@ +--!strict +-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, +-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through +-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" +-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). +-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter +-- (E0x), PowerPacker-packed files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Mod = { + name = "mod", + category = "music", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) +} +export type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local Pcm = Tracker.Pcm +local Tables = Tracker.Tables + +local FIXED: { [string]: number } = { + ["M.K."] = 4, + ["M!K!"] = 4, + ["M&K!"] = 4, + ["N.T."] = 4, + ["FLT4"] = 4, + ["FLT8"] = 8, + ["CD81"] = 8, + ["OKTA"] = 8, + ["OCTA"] = 8, + ["EXO4"] = 4, + ["EXO8"] = 8, +} + +-- channels from the 4-byte signature at 1080, or nil +local function signatureChannels(sig: string): number? + local fixed = FIXED[sig] + if fixed then + return fixed + end + local d = string.match(sig, "^(%d)CHN$") + if d then + local n = tonumber(d) :: number + return if n >= 1 then n else nil + end + local dd = string.match(sig, "^(%d%d)C[HN]$") + if dd then + local n = tonumber(dd) :: number + return if n >= 1 and n <= 32 then n else nil + end + local t = string.match(sig, "^TDZ(%d)$") + if t then + local n = tonumber(t) :: number + return if n >= 1 then n else nil + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mod.sniff(r: Bytes.Reader): number + if r:size() < 1084 then + return 0 + end + local sig = r:peek(4, 1080) + if signatureChannels(sig) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + local size = r:size() + local sig = if size >= 1084 then r:peek(4, 1080) else "" + local channels = signatureChannels(sig) + local nsamples = 31 + if not channels then + -- a 15-sample Soundtracker module (no signature): only when the header is plausible + nsamples, channels = 15, 4 + end + local nch = channels :: number + local m = Tracker.newModule("mod", nch) + m.title = r:fixed(20) + local lengths: { number } = {} + for i = 1, nsamples do + local s = Tracker.newSample(r:fixed(22)) + local len = r:u16be() * 2 + local ft = r:u8() % 16 + local vol = r:u8() + local ls = r:u16be() * 2 + local ll = r:u16be() * 2 + if r.err then + return nil, r.err + end + if nsamples == 15 and (vol > 64 or ft ~= 0) then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") + end + s.finetune = (if ft >= 8 then ft - 16 else ft) * 16 + s.volume = math.min(vol, 64) + s.bits = 8 + if ll > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 + end + lengths[i] = len + m.samples[i] = s + end + local songLength = r:u8() + local restart = r:u8() + local order: { number } = {} + local maxPat = 0 + for i = 1, 128 do + local p = r:u8() + order[i] = p + maxPat = math.max(maxPat, p) + end + if r.err then + return nil, r.err + end + if songLength == 0 or songLength > 128 or maxPat >= 128 then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") + end + if nsamples == 31 then + r:skip(4) + end + for i = 1, songLength do + m.order[i] = order[i] + end + m.restart = if restart < songLength then restart else 0 + m.meta.signature = if nsamples == 31 then sig else nil + m.flags.amigaLimits = nch == 4 + -- patterns + local npat = maxPat + 1 + local patBytes = 64 * nch * 4 + if not r:need(npat * patBytes) then + return nil, r.err + end + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, nch) + local base = r.pos + p * patBytes + local d = pat.data + for i = 0, 64 * nch - 1 do + local o = base + i * 4 + local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) + local period = (b0 % 16) * 256 + b1 + local ins = (b0 // 16) * 16 + b2 // 16 + local q = i * 5 + buffer.writeu8(d, q, Tables.periodToNote(period)) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 3, b2 % 16) + buffer.writeu8(d, q + 4, b3) + end + m.patterns[p + 1] = pat + end + r:skip(npat * patBytes) + -- sample data (8-bit signed; the last samples of a truncated file are cut short) + local total = 0 + for i = 1, nsamples do + local s = m.samples[i] + local len = math.min(lengths[i], r:remaining()) + total += len * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) + end + r:skip(len) + s.data, s.length = data, len + if s.loopEnd > len then + s.loopEnd = len + if s.loopEnd - s.loopStart < 2 then + s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 + end + end + end + m.meta.source = { format = "mod", samples = nsamples } + m.render = Tracker.renderMethod + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to +-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. +function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "mod" and m.format ~= "xm" then + return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") + end + local nch = m.channels + if nch > 32 then + return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") + end + -- the sample for each instrument number + local smpOf: { any } = {} + if m.format == "xm" then + for i, ins in m.instruments do + local first = 0 + for n = 1, 120 do + local s = ins.sampleMap[n] + if s ~= 0 then + if first ~= 0 and s ~= first then + return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") + end + first = s + end + end + smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) + end + else + for i, s in m.samples do + smpOf[i] = s + end + end + if #smpOf > 31 then + return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order == 0 or #order > 128 then + return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") + end + local npat = #m.patterns + if npat > 100 then + return nil, Err.new(Err.ARG, "too many patterns for MOD") + end + for p, pat in m.patterns do + if pat.rows ~= 64 then + return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") + end + end + local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) + writeName(w, m.title or "", 20) + local datas: { buffer } = {} + for i = 1, 31 do + local s = smpOf[i] + if s then + local len = math.min(s.length, 131070) + local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) + if s.channels == 2 then + -- mix stereo samples down + local mono = buffer.create(len * 4) + for k = 0, len - 1 do + buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) + end + pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) + end + local even = len + len % 2 + local padded = buffer.create(even) + buffer.copy(padded, 0, pcm, 0, len) + datas[i] = padded + writeName(w, s.name or "", 22) + w:u16be(even // 2) + local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) + w:u8(ft % 16) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + if s.loopType > 0 and s.loopEnd <= even then + w:u16be(s.loopStart // 2) + w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2)) + else + w:u16be(0) + w:u16be(1) + end + else + w:fill(0, 22) + w:u16be(0) + w:u8(0) + w:u8(0) + w:u16be(0) + w:u16be(1) + end + end + w:u8(#order) + w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127) + for i = 1, 128 do + w:u8(order[i] or 0) + end + local sig + if nch == 4 then + sig = if npat > 64 then "M!K!" else "M.K." + elseif nch < 10 then + sig = nch .. "CHN" + else + sig = nch .. "CH" + end + w:string(sig) + for p = 1, npat do + local d = m.patterns[p].data + for i = 0, 64 * nch - 1 do + local q = i * 5 + local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) + local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0 + if period > 4095 then + period = 0 + end + if fx > 15 then + fx, param = 0, 0 + end + if ins > 31 then + ins = 0 + end + w:u8((ins // 16) * 16 + period // 256) + w:u8(period % 256) + w:u8((ins % 16) * 16 + fx) + w:u8(param) + end + end + for i = 1, 31 do + if datas[i] then + w:bytes(datas[i]) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mod.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mod diff --git a/tests/music/_similar.luau b/tests/music/_similar.luau new file mode 100644 index 0000000..b234d86 --- /dev/null +++ b/tests/music/_similar.luau @@ -0,0 +1,201 @@ +-- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and +-- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left, +-- right and mid, and 20 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides. +local S = {} + +local SR, HOP, BANDS = 44100, 2048, 20 +local F_LO, F_HI = 100, 16000 +S.SR = SR + +local WINDOW = table.create(HOP, 0) +for i = 0, HOP - 1 do + WINDOW[i + 1] = 0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) +end +local BAND_OF = table.create(HOP // 2, -1) +for b = 1, HOP // 2 - 1 do + local f = b * SR / HOP + if f >= F_LO and f < F_HI then + BAND_OF[b + 1] = math.min(BANDS - 1, math.floor(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS)) + end +end + +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 1, n - 1 do + local bit = n // 2 + while bit > 0 and j >= bit and (j // bit) % 2 == 1 do + j -= bit + bit //= 2 + end + j += bit + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + end + local size = 2 + while size <= n do + local ang = -2 * math.pi / size + local wr, wi = math.cos(ang), math.sin(ang) + local half = size // 2 + for start = 0, n - 1, size do + local cr, ci = 1, 0 + for k = 0, half - 1 do + local a, b = start + k + 1, start + k + half + 1 + local tr = re[b] * cr - im[b] * ci + local ti = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - tr, im[a] - ti + re[a], im[a] = re[a] + tr, im[a] + ti + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + end + end + size *= 2 + end +end + +-- features(samples (interleaved stereo f32 buffer), frames) -> { frames, rmsL, rmsR, rmsM, bands } +function S.features(buf: buffer, frames: number): any + local n = frames // HOP + local out = { frames = n, rmsL = {}, rmsR = {}, rmsM = {}, bands = {} } + local re, im = table.create(HOP, 0), table.create(HOP, 0) + for k = 0, n - 1 do + local sl, sr, sm = 0, 0, 0 + for i = 0, HOP - 1 do + local o = ((k * HOP + i) * 2) * 4 + local l, r = buffer.readf32(buf, o), buffer.readf32(buf, o + 4) + local m = (l + r) / 2 + sl += l * l + sr += r * r + sm += m * m + re[i + 1] = m * WINDOW[i + 1] + im[i + 1] = 0 + end + table.insert(out.rmsL, math.sqrt(sl / HOP)) + table.insert(out.rmsR, math.sqrt(sr / HOP)) + table.insert(out.rmsM, math.sqrt(sm / HOP)) + fft(re, im, HOP) + local e = table.create(BANDS, 0) + for b = 1, HOP // 2 - 1 do + local j = BAND_OF[b + 1] + if j >= 0 then + e[j + 1] += re[b + 1] * re[b + 1] + im[b + 1] * im[b + 1] + end + end + for j = 1, BANDS do + table.insert(out.bands, math.sqrt(e[j])) + end + end + return out +end + +-- renderAll(decoder, maxFrames) -> interleaved buffer, frames +function S.renderAll(dec: any, maxFrames: number): (buffer, number) + local total = math.min(dec.frames, maxFrames) + local out = buffer.create(math.max(1, total) * 8) + local pos = 0 + local chunk = buffer.create(4096 * 8) + while pos < total do + local _, n = dec:read(math.min(4096, total - pos), chunk) + if n == 0 then + break + end + buffer.copy(out, pos * 8, chunk, 0, n * 8) + pos += n + end + return out, pos +end + +local function db(x: number): number + return 20 * math.log10(x + 1e-6) +end + +-- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames: +-- gainDb total mid energy ratio in dB (ours / ref) +-- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either) +-- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB) +-- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks) +function S.compare(a: any, b: any): any + local n = math.min(a.frames, b.frames) + local ea, eb = 0, 0 + for k = 1, n do + ea += a.rmsM[k] ^ 2 + eb += b.rmsM[k] ^ 2 + end + local gainDb = 10 * math.log10((ea + 1e-12) / (eb + 1e-12)) + local xs, ys = {}, {} + for k = 1, n do + local x, y = db(a.rmsM[k]), db(b.rmsM[k]) + if x > -60 or y > -60 then + table.insert(xs, x) + table.insert(ys, y) + end + end + local mx, my = 0, 0 + for i = 1, #xs do + mx += xs[i] + my += ys[i] + end + mx /= math.max(1, #xs) + my /= math.max(1, #ys) + local sxy, sxx, syy = 0, 0, 0 + for i = 1, #xs do + sxy += (xs[i] - mx) * (ys[i] - my) + sxx += (xs[i] - mx) ^ 2 + syy += (ys[i] - my) ^ 2 + end + local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1 + local cs, cn = 0, 0 + local bal, bn = 0, 0 + for k = 1, n do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + cs += if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0 + cn += 1 + end + local la, ra, lb, rb = a.rmsL[k], a.rmsR[k], b.rmsL[k], b.rmsR[k] + if lb + rb > 0.01 then + bal += math.abs((la - ra) / (la + ra + 1e-9) - (lb - rb) / (lb + rb)) + bn += 1 + end + end + return { + gainDb = gainDb, + envCorr = envCorr, + spectral = if cn > 0 then cs / cn else 1, + balance = if bn > 0 then bal / bn else 0, + frames = n, + } +end + +-- worst(ours, ref, count) -> the blocks with the lowest spectral similarity (for debugging): { {block, sim} } +function S.worst(a: any, b: any, count: number): { { number } } + local list = {} + for k = 1, math.min(a.frames, b.frames) do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + table.insert(list, { k, if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0, db(a.rmsM[k]), db(b.rmsM[k]) }) + end + end + table.sort(list, function(x, y) + return x[2] < y[2] + end) + local out = {} + for i = 1, math.min(count, #list) do + out[i] = list[i] + end + return out +end + +return S diff --git a/tests/music/mod.luau b/tests/music/mod.luau new file mode 100644 index 0000000..f873981 --- /dev/null +++ b/tests/music/mod.luau @@ -0,0 +1,77 @@ +-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Mod = require("@formats/music/mod") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/mod_cases") + +local t = T.suite("mod") + +t:eq(Mod.name, "mod", "name") +t:eq(Mod.category, "music", "category") +t:check(Mod.caps.decode and Mod.caps.encode, "caps") + +local function load(data: string): any + return Mod.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 1.5, envCorr = 0.95, spectral = 0.93, balance = 0.05, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(Mod.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-6s gain %+.2f dB, envelope r %.3f, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envCorr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envCorr < THRESH.envCorr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envCorr > THRESH.envCorr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") + -- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files) + local out, werr = Mod.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Mod.decode(Bytes.reader(out :: buffer)) + t:check(m2, c.name .. ": re-decode") + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = Mod.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py new file mode 100644 index 0000000..d1c5609 --- /dev/null +++ b/tools/fixtures/_tracker.py @@ -0,0 +1,495 @@ +# Tracker fixture helpers (used by tools/fixtures/{mod,s3m,xm,it}.py): small writers for MOD, S3M, XM and IT +# (including IT 2.14 / 2.15 sample compression), synthesized samples, reference renders through openmpt123 (nix +# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 20 log-spaced band +# magnitudes of the mid signal), computed the same way in tests/music/_similar.luau. Every module is generated here +# (no third-party files), so the fixtures carry no licence. +import json, math, os, struct, subprocess, tempfile + +SR = 44100 +HOP = 2048 +BANDS = 20 +F_LO, F_HI = 100.0, 16000.0 + + +# ---------------------------------------------------------------------------------------------- samples +def synth(kind, n, period, amp=0.9, seed=1, decay=None): + """float samples in [-1, 1]: sine / square / saw / tri / noise / pluck""" + out = [] + s = seed + for i in range(n): + ph = (i % period) / period + if kind == "sine": + v = math.sin(2 * math.pi * ph) + elif kind == "square": + v = 1.0 if ph < 0.5 else -1.0 + elif kind == "saw": + v = 2 * ph - 1 + elif kind == "tri": + v = 4 * ph - 1 if ph < 0.5 else 3 - 4 * ph + else: # noise + s = (s * 1103515245 + 12345) % 2147483648 + v = (s / 2147483648) * 2 - 1 + if decay: + v *= math.exp(-i / decay) + out.append(v * amp) + return out + + +def s8(xs): + return bytes((max(-128, min(127, int(round(x * 127)))) & 255) for x in xs) + + +def u8(xs): + return bytes(max(0, min(255, int(round(x * 127)) + 128)) for x in xs) + + +def s16(xs): + return b"".join(struct.pack("= 128 else b + out.append((v - prev) & 255) + prev = v + return bytes(out) + + +def delta16(raw): + out, prev = bytearray(), 0 + for i in range(0, len(raw), 2): + v = struct.unpack_from("HBBHH", len(s["data"]) // 2, s.get("finetune", 0) & 15, + s.get("volume", 64), ls // 2, ll // 2) + else: + out += b"\0" * 22 + struct.pack(">HBBHH", 0, 0, 0, 0, 1) + out += bytes([len(orders), restart]) + bytes(orders) + b"\0" * (128 - len(orders)) + out += b"M.K." if channels == 4 else (b"%dCHN" % channels if channels < 10 else b"%dCH" % channels) + for pat in patterns: + for row in pat: + for (note, ins, fx, param) in row: + p = mod_period(note) + out += bytes([(ins & 0xF0) | (p >> 8), p & 255, ((ins & 15) << 4) | fx, param]) + for s in samples: + out += s["data"] + return bytes(out) + + +# ---------------------------------------------------------------------------------------------- S3M +def write_s3m(title, samples, orders, patterns, channels, speed=6, tempo=125, gvol=64, mvol=48 | 128, pans=None, + flags=0, cwt=0x1320, chanset=None): + """samples: [{name, data (u8 bytes), volume, c2spd, loop: (start, end) | None}]; + patterns: [[row: [(note, ins, vol, cmd, info)] * channels] * 64] with note 0 = none, 254 = cut, else S3M byte + (octave << 4 | semitone); vol None = none; cmd 0 = none (A = 1).""" + ordn = list(orders) + [255] + if len(ordn) % 2: + ordn.append(255) + nins, npat = len(samples), len(patterns) + head = bytearray(name(title, 28) + bytes([0x1A, 16, 0, 0])) + head += struct.pack("> 16 + struct.pack_into(" the S3M note byte""" + n = note - 13 + return (n // 12) << 4 | (n % 12) + + +# ---------------------------------------------------------------------------------------------- XM +def env_bytes(points): + b = bytearray() + for (x, y) in points[:12]: + b += struct.pack("= 128 else b for b in raw] + else: + vals = [struct.unpack_from("= 8: + data.append(acc & 255) + acc >>= 8 + nbits -= 8 + if nbits: + data.append(acc & 255) + out += struct.pack("> 1 + while j & bit: + j ^= bit + bit >>= 1 + j |= bit + if i < j: + re[i], re[j] = re[j], re[i] + im[i], im[j] = im[j], im[i] + size = 2 + while size <= n: + ang = -2 * math.pi / size + wr, wi = math.cos(ang), math.sin(ang) + for start in range(0, n, size): + cr, ci = 1.0, 0.0 + half = size // 2 + for k in range(half): + a, b = start + k, start + k + half + tr = re[b] * cr - im[b] * ci + ti = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - tr, im[a] - ti + re[a], im[a] = re[a] + tr, im[a] + ti + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + size *= 2 + + +EDGES = [F_LO * (F_HI / F_LO) ** (j / BANDS) for j in range(BANDS + 1)] +WINDOW = [0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) for i in range(HOP)] + + +def features(left, right): + """{frames, rmsL, rmsR, rmsM, bands (frames * BANDS magnitudes)} of a stereo signal""" + n = len(left) // HOP + out = {"frames": n, "rmsL": [], "rmsR": [], "rmsM": [], "bands": []} + for k in range(n): + o = k * HOP + L, R = left[o:o + HOP], right[o:o + HOP] + M = [(a + b) / 2 for a, b in zip(L, R)] + out["rmsL"].append(math.sqrt(sum(x * x for x in L) / HOP)) + out["rmsR"].append(math.sqrt(sum(x * x for x in R) / HOP)) + out["rmsM"].append(math.sqrt(sum(x * x for x in M) / HOP)) + re = [M[i] * WINDOW[i] for i in range(HOP)] + im = [0.0] * HOP + fft(re, im) + e = [0.0] * BANDS + for b in range(1, HOP // 2): + f = b * SR / HOP + if f < F_LO or f >= F_HI: + continue + j = min(BANDS - 1, int(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS)) + e[j] += re[b] * re[b] + im[b] * im[b] + out["bands"] += [math.sqrt(x) for x in e] + return out + + +def duration(ctx, data, ext): + """openmpt123 --info's song length in seconds""" + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "song." + ext) + with open(p, "wb") as f: + f.write(data) + info = ctx.nix("libopenmpt", ["openmpt123", "--info", p]).decode(errors="replace") + for line in info.splitlines(): + if line.startswith("Duration"): + secs = 0.0 + for part in line.split(":", 1)[1].strip().split(":"): + secs = secs * 60 + float(part) + return secs + raise RuntimeError("openmpt123 --info: no duration") + + +def reference(ctx, data, ext, extra=()): + left, right = openmpt(ctx, data, ext, extra) + f = features(left, right) + f["duration"] = duration(ctx, data, ext) + return f diff --git a/tools/fixtures/mod.py b/tools/fixtures/mod.py new file mode 100644 index 0000000..6b63f81 --- /dev/null +++ b/tools/fixtures/mod.py @@ -0,0 +1,104 @@ +# MOD fixtures (tools/fixtures.py): generated ProTracker modules exercising the effects, rendered by openmpt123. +# tests/gen/mod_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, fx=0, param=0): + p[row][ch] = (note, ins, fx, param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "loop": (0, 64)}, + {"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64)}, + {"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 64}, + {"name": "tri ft", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 56, "finetune": 3, "loop": (0, 32)}, + ] + + +def song_basic(): + a, b = empty(4), empty(4) + mel = [49, 53, 56, 61, 56, 53, 51, 49] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0) + put(a, 0, 2, 49, 3, 0x1, 0x02) + put(a, 16, 2, 0, 0, 0x2, 0x03) + put(a, 32, 2, 61, 3, 0xC, 0x30) + put(a, 33, 2, 0, 0, 0xA, 0x02) + put(a, 48, 2, 0, 0, 0xA, 0x40) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2) + put(a, 60, 3, 61, 4, 0xE, 0xC2) + # pattern b: portamento, vibrato, tremolo, offsets, retrig, delay, fine slides, speed change, break + put(b, 0, 0, 49, 1) + put(b, 4, 0, 61, 0, 0x3, 0x08) + put(b, 8, 0, 0, 0, 0x3, 0x00) + put(b, 12, 0, 49, 0, 0x5, 0x02) + put(b, 16, 0, 56, 5, 0x4, 0x46) + put(b, 20, 0, 0, 0, 0x6, 0x01) + put(b, 24, 0, 0, 0, 0x4, 0x8F) + put(b, 0, 1, 37, 2, 0x7, 0x48) + put(b, 8, 1, 0, 0, 0x7, 0x00) + put(b, 16, 1, 44, 2, 0xE, 0x12) + put(b, 17, 1, 0, 0, 0xE, 0x12) + put(b, 20, 1, 0, 0, 0xE, 0x24) + put(b, 24, 1, 0, 0, 0xE, 0xB8) + put(b, 28, 1, 0, 0, 0xE, 0xA4) + put(b, 0, 3, 49, 4, 0x9, 0x08) + put(b, 8, 3, 49, 4, 0xE, 0x93) + put(b, 16, 3, 56, 4, 0xE, 0xD3) + put(b, 24, 2, 49, 3, 0xF, 0x03) + put(b, 32, 2, 51, 3, 0xF, 0x90) + put(b, 40, 2, 53, 3, 0xF, 0x06) + put(b, 40, 3, 61, 4, 0x9, 0x04) + put(b, 44, 0, 49, 5, 0xE, 0x53) + put(b, 48, 0, 0, 0, 0xD, 0x00) + return T.write_mod("basic", samples(), [0, 1], [a, b]) + + +def song_loops(): + a, b, c = empty(4), empty(4), empty(4) + put(a, 0, 0, 49, 1, 0xF, 0x04) + put(a, 4, 0, 0, 0, 0xE, 0x60) + put(a, 5, 1, 61, 2) + put(a, 8, 0, 53, 1, 0xE, 0x62) + put(a, 16, 0, 56, 1, 0xE, 0xE3) + put(a, 17, 2, 37, 3, 0xA, 0x01) + put(a, 32, 0, 0, 0, 0xD, 0x16) + put(b, 16, 0, 61, 1) + put(b, 20, 3, 49, 4, 0xF, 0x70) + put(b, 24, 0, 0, 0, 0xB, 0x02) + put(c, 0, 1, 50, 5) + put(c, 4, 1, 0, 0, 0xB, 0x01) + return T.write_mod("loops", samples(), [0, 1, 2], [a, b, c]) + + +def song_8ch(): + a = empty(8) + for ch in range(8): + put(a, ch * 2, ch, 37 + ch * 5, 1 + ch % 3, 0x8, ch * 32) + put(a, 32, 0, 61, 5, 0xE, 0x84) + put(a, 32, 7, 49, 4, 0x8, 0xFF) + put(a, 63, 0, 0, 0, 0xF, 0x00) + return T.write_mod("eight", samples(), [0], [a], channels=8) + + +def generate(ctx): + cases = [] + for nm, data in (("basic", song_basic()), ("loops", song_loops()), ("8ch", song_8ch())): + ref = T.reference(ctx, data, "mod") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("mod_cases", cases) + From 042a782f2f87007283f6393d723d2b9cb596db45 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:53:10 -0500 Subject: [PATCH 10/28] ws-audio: audio/vorbis decoder: stb_vorbis 1.22 port (setup, codebooks, floor 1, residue 0/1/2, coupling) on containers/Ogg + codecs/Mdct, libvorbis-exact trimming, granule-exact seek, packetDecoder for other containers; tests vs oggdec (counts, 1 LSB) + ffmpeg (SNR 138 dB), seeks, fuzz; bench line --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/stb_vorbis-LICENSE.txt | 41 ++ src/Formats/Registry.luau | 12 + src/Formats/audio/vorbis/Codebook.luau | 394 +++++++++++++++++ src/Formats/audio/vorbis/Packet.luau | 586 +++++++++++++++++++++++++ src/Formats/audio/vorbis/Setup.luau | 429 ++++++++++++++++++ src/Formats/audio/vorbis/Tables.luau | 37 ++ src/Formats/audio/vorbis/init.luau | 448 +++++++++++++++++++ tests/audio/vorbis.luau | 193 ++++++++ tools/bench.luau | 10 + tools/bench.sh | 2 +- tools/fixtures/vorbis.py | 57 +++ 13 files changed, 2210 insertions(+), 1 deletion(-) create mode 100644 licenses/stb_vorbis-LICENSE.txt create mode 100644 src/Formats/audio/vorbis/Codebook.luau create mode 100644 src/Formats/audio/vorbis/Packet.luau create mode 100644 src/Formats/audio/vorbis/Setup.luau create mode 100644 src/Formats/audio/vorbis/Tables.luau create mode 100644 src/Formats/audio/vorbis/init.luau create mode 100644 tests/audio/vorbis.luau create mode 100644 tools/fixtures/vorbis.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f0aab69..7f04fd3 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -11,6 +11,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | +| audio | vorbis | .ogg .oga | yes | - | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index b35f084..b4980ac 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -9,6 +9,7 @@ | `src/Formats/audio/mp3/` | mp3-luau c755bbf (same author), a port of minimp3 by lieff (https://github.com/lieff/minimp3) | minimp3: CC0 1.0, [minimp3-CC0.txt](minimp3-CC0.txt) | | `tests/fixtures/mp3/` | made by ffmpeg (libmp3lame / mp2) from a synthetic signal; `*.ref` are minimp3 decodes of them | test data, no third-party content | | `src/Formats/audio/opus/` (Decoder, Celt, Silk, Mdct, RangeDecoder, Packet, CeltTables, SilkTables) | opus-luau dd2b4e5 (same author): a port of the libopus 1.6 decoder (git bafd40dcbd50; tables generated from its sources); the stereo downmix weights follow opusfile | libopus BSD 3-clause (Xiph.Org, Skype, Octasic, J.-M. Valin, T. B. Terriberry, CSIRO, G. Maxwell, M. Borgerding, E. de Castro Lopo, Mozilla, Amazon), opusfile BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | +| `src/Formats/audio/vorbis/` (Setup, Codebook, Packet, Tables) | a Luau port of stb_vorbis 1.22 by Sean Barrett (https://github.com/nothings/stb): setup parsing, codebooks, floor 1, residues, coupling (the IMDCT is codecs/Mdct; the timing follows libvorbis / the spec) | public domain or MIT (dual): [stb_vorbis-LICENSE.txt](stb_vorbis-LICENSE.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/licenses/stb_vorbis-LICENSE.txt b/licenses/stb_vorbis-LICENSE.txt new file mode 100644 index 0000000..6e4b8d2 --- /dev/null +++ b/licenses/stb_vorbis-LICENSE.txt @@ -0,0 +1,41 @@ +stb_vorbis.c v1.22 (https://github.com/nothings/stb), by Sean Barrett and contributors. +Ported to Luau in src/Formats/audio/vorbis/ (decoder). + +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d3b10be..400adba 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -86,6 +86,18 @@ local list: { Entry } = { return require("@formats/audio/voc") end, }, + { + name = "vorbis", + category = "audio", + path = "audio/vorbis", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255 }, + load = function() + return require("@formats/audio/vorbis") + end, + }, { name = "wav", category = "audio", diff --git a/src/Formats/audio/vorbis/Codebook.luau b/src/Formats/audio/vorbis/Codebook.luau new file mode 100644 index 0000000..19c0da5 --- /dev/null +++ b/src/Formats/audio/vorbis/Codebook.luau @@ -0,0 +1,394 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3): +-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack), +-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see +-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side +-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search. +-- +-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition); +-- an invalid codeword also sets eop and decodes to -1. +local Codebook = {} + +local readu8 = buffer.readu8 +local floor = math.floor + +local POW = table.create(41, 0) +for i = 0, 40 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ bit reader +export type Br = { + buf: buffer, + pos: number, -- next byte to load + limit: number, + acc: number, -- loaded, unread bits (LSB first) + cnt: number, + pad: number, -- how many of the top bits of acc are past the end of the packet + eop: boolean, -- read past the end of the packet +} + +function Codebook.reader(buf: buffer, offset: number, size: number): Br + return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } +end + +-- bits(br, n) -> the next n (0..32) bits as an unsigned number +local function bits(br: Br, n: number): number + if n == 0 then + return 0 + end + local acc, cnt = br.acc, br.cnt + if cnt < n then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= n + br.pos = p + end + local m = POW[n + 1] + local v = acc % m + br.acc = (acc - v) / m + cnt -= n + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + end + return v +end +Codebook.bits = bits + +-- ilog(x): the number of bits needed to hold x (0 for x <= 0) +local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end +Codebook.ilog = ilog + +-- float32_unpack (spec 9.2.2) +local function float32Unpack(x: number): number + local mantissa = x % 2097152 + local sign = x >= 2147483648 + local exp = floor((x % 2147483648) / 2097152) + local v = mantissa * 2 ^ (exp - 788) + return if sign then -v else v +end + +-- ------------------------------------------------------------------------------------------------ codebooks +export type Book = { + dims: number, + entries: number, + fastBits: number, + fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid + fastSym: { number }, -- symbol, or the tree node to continue from + c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none + c1: { number }, + lookup: number, -- 0, 1, 2 + vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded) + used: number, -- entries with a codeword +} + +local MAX_ENTRIES = 2 ^ 20 +local MAX_VQ = 2 ^ 22 + +-- lookup1_values(entries, dims): the largest r with r^dims <= entries +local function lookup1Values(entries: number, dims: number): number + local r = floor(math.exp(math.log(entries) / dims)) + if floor((r + 1) ^ dims) <= entries then + r += 1 + end + if (r + 1) ^ dims <= entries then + return -1 + end + if floor(r ^ dims) > entries then + return -1 + end + return r +end + +-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table +local function build(book: Book, lengths: { number }): string? + local n = book.entries + local c0, c1 = book.c0, book.c1 + local nodes = 1 + c0[1], c1[1] = 0, 0 + local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none) + local first = true + local used = 0 + local maxLen = 0 + for i = 0, n - 1 do + local len = lengths[i + 1] + if len > 0 then + local code: number + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + if z == 0 then + return "over-subscribed codebook" + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- walk the MSB-first code into the tree + local node = 1 + for d = 1, len do + local bit = floor(code / POW[33 - d]) % 2 + local child = if bit == 0 then c0[node] else c1[node] + if d == len then + if child ~= 0 then + return "ambiguous codeword" + end + if bit == 0 then + c0[node] = -(i + 1) + else + c1[node] = -(i + 1) + end + else + if child < 0 then + return "ambiguous codeword" + elseif child == 0 then + nodes += 1 + c0[nodes], c1[nodes] = 0, 0 + child = nodes + if bit == 0 then + c0[node] = child + else + c1[node] = child + end + end + node = child + end + end + used += 1 + if len > maxLen then + maxLen = len + end + end + end + book.used = used + -- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree + local fb = math.clamp(maxLen, 1, 10) + book.fastBits = fb + local size = POW[fb + 1] + local fl, fs = table.create(size, -1), table.create(size, 0) + for idx = 0, size - 1 do + local node = 1 + local v = idx + for d = 1, fb do + local bit = v % 2 + v = (v - bit) / 2 + local child = if bit == 0 then c0[node] else c1[node] + if child < 0 then + fl[idx + 1], fs[idx + 1] = d, -child - 1 + break + elseif child == 0 then + break -- invalid (-1) + end + node = child + if d == fb then + fl[idx + 1], fs[idx + 1] = 0, node + end + end + end + book.fastLen, book.fastSym = fl, fs + return nil +end + +-- read(br) -> Book | nil, message: one codebook from the setup header +function Codebook.read(br: Br): (Book?, string?) + if bits(br, 24) ~= 0x564342 then + return nil, "bad codebook sync" + end + local dims = bits(br, 16) + local entries = bits(br, 24) + local ordered = bits(br, 1) + if br.eop then + return nil, "setup header ends in a codebook" + end + if dims == 0 and entries ~= 0 then + return nil, "codebook with 0 dimensions" + end + if entries > MAX_ENTRIES then + return nil, "codebook with " .. entries .. " entries" + end + local lengths = table.create(entries, 0) + if ordered == 1 then + local cur = 0 + local len = bits(br, 5) + 1 + while cur < entries do + local num = bits(br, ilog(entries - cur)) + if len >= 32 or cur + num > entries or br.eop then + return nil, "bad ordered codebook lengths" + end + for k = cur + 1, cur + num do + lengths[k] = len + end + cur += num + len += 1 + end + else + local sparse = bits(br, 1) + for j = 1, entries do + if sparse == 0 or bits(br, 1) == 1 then + local l = bits(br, 5) + 1 + if l == 32 then + return nil, "codeword length 32" + end + lengths[j] = l + end + end + end + if br.eop then + return nil, "setup header ends in a codebook" + end + local book: Book = { + dims = dims, + entries = entries, + fastBits = 1, + fastLen = {}, + fastSym = {}, + c0 = {}, + c1 = {}, + lookup = 0, + vq = nil, + used = 0, + } + local err = build(book, lengths) + if err then + return nil, err + end + local lookup = bits(br, 4) + if lookup > 2 then + return nil, "lookup type " .. lookup + end + book.lookup = lookup + if lookup > 0 then + local minimum = float32Unpack(bits(br, 32)) + local delta = float32Unpack(bits(br, 32)) + local valueBits = bits(br, 4) + 1 + local seq = bits(br, 1) == 1 + local nvalues + if lookup == 1 then + nvalues = lookup1Values(entries, dims) + if nvalues < 0 then + return nil, "bad lookup1 size" + end + else + nvalues = entries * dims + end + if nvalues == 0 then + return nil, "empty lookup table" + end + if entries * dims > MAX_VQ or nvalues > MAX_VQ then + return nil, "lookup table too large" + end + local mults = table.create(nvalues, 0) + for j = 1, nvalues do + mults[j] = bits(br, valueBits) + end + if br.eop then + return nil, "setup header ends in a lookup table" + end + -- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation") + local vq = table.create(entries * dims, 0) + for e = 0, entries - 1 do + local last = 0 + local div = 1 + for k = 0, dims - 1 do + local off + if lookup == 1 then + off = floor(e / div) % nvalues + div *= nvalues + else + off = e * dims + k + end + local v = mults[off + 1] * delta + minimum + last + if seq then + last = v + end + vq[e * dims + k + 1] = v + end + end + book.vq = vq + end + return book, nil +end + +-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set) +local function decode(br: Br, book: Book): number + local fb = book.fastBits + local acc, cnt = br.acc, br.cnt + if cnt < fb then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= fb + br.pos = p + br.acc, br.cnt = acc, cnt + end + local idx = acc % POW[fb + 1] + 1 + local l = book.fastLen[idx] + if l > 0 then + local m = POW[l + 1] + br.acc = (acc - acc % m) / m + cnt -= l + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + return -1 + end + return book.fastSym[idx] + elseif l == 0 then + bits(br, fb) + local node = book.fastSym[idx] + local c0, c1 = book.c0, book.c1 + while true do + local child = if bits(br, 1) == 0 then c0[node] else c1[node] + if br.eop then + return -1 + end + if child < 0 then + return -child - 1 + elseif child == 0 then + br.eop = true + return -1 + end + node = child + end + end + br.eop = true + return -1 +end +Codebook.decode = decode + +return Codebook diff --git a/src/Formats/audio/vorbis/Packet.luau b/src/Formats/audio/vorbis/Packet.luau new file mode 100644 index 0000000..ca69d79 --- /dev/null +++ b/src/Formats/audio/vorbis/Packet.luau @@ -0,0 +1,586 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 +-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add. +-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue / +-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis: +-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so +-- granule positions count exactly the samples returned (the first packet returns none). +-- +-- local st = Packet.new(ident, setup) +-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet +-- Packet.reset(st) -- forget the overlap (after a seek / a gap) +-- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only +-- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1. +local Codebook = require("@formats/audio/vorbis/Codebook") +local Setup = require("@formats/audio/vorbis/Setup") +local Tables = require("@formats/audio/vorbis/Tables") +local Mdct = require("@formats/codecs/Mdct") + +local Packet = {} + +local bits, decode = Codebook.bits, Codebook.decode +local ilog = Codebook.ilog +local INV_DB = Tables +local RANGE = { 256, 128, 86, 64 } + +export type State = { + channels: number, + n0: number, + n1: number, + setup: Setup.Setup, + plans: { [number]: Mdct.Plan }, + slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2) + spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor) + frame: { { number } }, -- per channel: n windowed time samples + tail: { { number } }, -- per channel: the previous frame from its centre on + tailLen: number, + prevN: number, -- the previous block size, 0 = no previous frame + out: { { number } }, -- per channel: the returned samples + finalY: { { number } }, + step2: { number }, + inter: { number }, -- residue type 2 interleaved scratch + zero: { boolean }, + reallyZero: { boolean }, + partClass: { { { number } } }, +} + +function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? + local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels + local plans: { [number]: Mdct.Plan } = {} + local slopes: { [number]: { number } } = {} + for _, n in { n0, n1 } do + local p = Mdct.new(n) + if not p then + return nil + end + plans[n] = p + local w = Mdct.window("vorbis", n) :: { number } + local half = table.create(n // 2, 0) + for i = 1, n // 2 do + half[i] = w[i] + end + slopes[n // 2] = half + end + local function arrays(len: number): { { number } } + local t = table.create(ch) + for c = 1, ch do + t[c] = table.create(len, 0) + end + return t + end + local partClass = table.create(ch) + for c = 1, ch do + partClass[c] = {} + end + return { + channels = ch, + n0 = n0, + n1 = n1, + setup = setup, + plans = plans, + slopes = slopes, + spec = arrays(n1 // 2), + frame = arrays(n1), + tail = arrays(n1 // 2), + tailLen = 0, + prevN = 0, + out = arrays(n1), + finalY = arrays(math.max(2, setup.maxFloorValues)), + step2 = table.create(math.max(2, setup.maxFloorValues), 0), + inter = table.create(n1 // 2 * ch, 0), + zero = table.create(ch, false), + reallyZero = table.create(ch, false), + partClass = partClass, + } +end + +function Packet.reset(st: State) + st.prevN = 0 + st.tailLen = 0 +end + +-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio) +function Packet.blocksize(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return 0 + end + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return 0 + end + local m = bits(br, st.setup.modeBits) + local mode = st.setup.modes[m + 1] + if not mode or br.eop then + return 0 + end + return if mode.blockflag == 1 then st.n1 else st.n0 +end + +-- ------------------------------------------------------------------------------------------------ floor 1 +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) +local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) + local dy = y1 - y0 + local adx = x1 - x0 + local ady = if dy < 0 then -dy else dy + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= (if base < 0 then -base else base) * adx + if x1 > n then + x1 = n + end + local x, y, err = x0, y0, 0 + if x < x1 then + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + end + end +end + +-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent +local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean + if bits(br, 1) == 0 then + return false + end + local books = st.setup.books + local range = RANGE[g.multiplier] + local yb = ilog(range) - 1 + finalY[1] = bits(br, yb) + finalY[2] = bits(br, yb) + local offset = 2 + for j = 1, g.partitions do + local pclass = g.partitionClass[j] + 1 + local cdim = g.classDims[pclass] + local cbits = g.classSubs[pclass] + local csub = 2 ^ cbits + local cval = 0 + if cbits > 0 then + cval = decode(br, books[g.classMaster[pclass] + 1]) + if cval < 0 then + return false + end + end + local subs = g.subBooks[pclass] + for _ = 1, cdim do + local book = subs[cval % csub + 1] + cval = cval // csub + if book >= 0 then + local v = decode(br, books[book + 1]) + if v < 0 then + return false + end + finalY[offset + 1] = v + else + finalY[offset + 1] = 0 + end + offset += 1 + end + end + if br.eop then + return false + end + -- step 1: amplitude value synthesis + local step2 = st.step2 + step2[1], step2[2] = 1, 1 + local xl, low, high = g.xlist, g.low, g.high + for j = 2, g.values - 1 do + local lo, hi = low[j + 1], high[j + 1] + local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1]) + local val = finalY[j + 1] + local highroom = range - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + if val ~= 0 then + step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1 + if val >= room then + if highroom > lowroom then + finalY[j + 1] = val - lowroom + pred + else + finalY[j + 1] = pred - val + highroom - 1 + end + elseif val % 2 == 1 then + finalY[j + 1] = pred - (val + 1) // 2 + else + finalY[j + 1] = pred + val // 2 + end + else + step2[j + 1] = 0 + finalY[j + 1] = pred + end + end + for j = 1, g.values do + if step2[j] == 0 then + finalY[j] = -1 + end + end + return true +end + +-- multiply target[1 .. n2] by the floor curve (stb do_floor) +local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) + local mult = g.multiplier + local lx, ly = 0, finalY[1] * mult + local sorted, xl = g.sorted, g.xlist + for q = 2, g.values do + local j = sorted[q] + 1 + local fy = finalY[j] + if fy >= 0 then + local hy = fy * mult + local hx = xl[j] + if lx ~= hx then + drawLine(target, lx, ly, hx, hy, n2) + end + lx, ly = hx, hy + end + end + if lx < n2 then + local v = INV_DB[ly % 256 + 1] + for j = lx + 1, n2 do + target[j] *= v + end + end +end + +-- ------------------------------------------------------------------------------------------------ residue +-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit) +local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean + local vq = book.vq + if not vq then + br.eop = true -- a scalar book in a vector context: invalid stream + return false + end + local dims = book.dims + if rtype == 0 then + local step = psize // dims + for k = 0, step - 1 do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + for i = 0, dims - 1 do + local at = offset + k + i * step + if at < limit then + target[at + 1] += vq[base + i + 1] + end + end + end + else + local k = 0 + while k < psize do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + local len = math.min(dims, psize - k) + local at = offset + k + for i = 0, len - 1 do + if at + i < limit then + target[at + i + 1] += vq[base + i + 1] + end + end + k += dims + end + end + return true +end + +-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each +local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) + local books = st.setup.books + local rtype = r.type + local cbook = books[r.classbook + 1] + local classwords = cbook.dims + for j = 1, ch do + local t = targets[j] + if t then + for i = 1, n2 do + (t :: { number })[i] = 0 + end + end + end + local any = false + for j = 1, ch do + if targets[j] then + any = true + end + end + if not any then + return + end + local psize = r.partSize + local rb = r.books + local classdata = r.classdata + if rtype == 2 and ch > 1 then + local total = n2 * ch + local inter = st.inter + for i = 1, total do + inter[i] = 0 + end + local lb = math.min(r.begin, total) + local le = math.min(r.finish, total) + local partRead = (le - lb) // psize + local pc = st.partClass[1] + local done = false + for pass = 1, 8 do + if done then + break + end + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + local q = decode(br, cbook) + if q < 0 then + done = true + break + end + pc[classSet] = classdata[q + 1] + end + local cls = pc[classSet] + local i = 0 + while i < classwords and pcount < partRead do + local b = rb[cls[i + 1] + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then + done = true + break + end + end + i += 1 + pcount += 1 + end + if done then + break + end + classSet += 1 + end + end + -- de-interleave into the channels that are decoded + for j = 1, ch do + local t = targets[j] + if t then + local tt = t :: { number } + local v = j + for i = 1, n2 do + tt[i] = inter[v] + v += ch + end + end + end + return + end + local lb = math.min(r.begin, n2) + local le = math.min(r.finish, n2) + local partRead = (le - lb) // psize + local pcs = st.partClass + for pass = 1, 8 do + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + for j = 1, ch do + if targets[j] then + local q = decode(br, cbook) + if q < 0 then + return + end + pcs[j][classSet] = classdata[q + 1] + end + end + end + local i = 0 + while i < classwords and pcount < partRead do + for j = 1, ch do + local t = targets[j] + if t then + local c = pcs[j][classSet][i + 1] + local b = rb[c + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then + return + end + end + end + end + i += 1 + pcount += 1 + end + classSet += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ packet +-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet +function Packet.decode(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return -1 + end + local setup = st.setup + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return -1 + end + local mode = setup.modes[bits(br, setup.modeBits) + 1] + if not mode then + return -1 + end + local n, prevLong, nextLong + if mode.blockflag == 1 then + n = st.n1 + prevLong = bits(br, 1) == 1 + nextLong = bits(br, 1) == 1 + else + n = st.n0 + prevLong, nextLong = false, false + end + if br.eop then + return -1 + end + local n2 = n // 2 + local n0 = st.n0 + local leftStart, leftEnd, rightStart, rightEnd + if mode.blockflag == 1 and not prevLong then + leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4 + else + leftStart, leftEnd = 0, n2 + end + if mode.blockflag == 1 and not nextLong then + rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4 + else + rightStart, rightEnd = n2, n + end + local map = setup.mappings[mode.mapping + 1] + local ch = st.channels + local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero + -- floors + for c = 1, ch do + local s = map.mux[c] + 1 + local g = setup.floors[map.submapFloor[s] + 1] + local ok = floorDecode(st, br, g, st.finalY[c]) + zero[c] = not ok + reallyZero[c] = not ok + end + -- channels coupled to a non-silent channel are decoded too + for i = 1, map.couplingSteps do + local m, a = map.magnitude[i] + 1, map.angle[i] + 1 + if not zero[m] or not zero[a] then + zero[m], zero[a] = false, false + end + end + -- residues, per submap + for i = 1, map.submaps do + local targets: { { number } | false } = {} + local k = 0 + for c = 1, ch do + if map.mux[c] == i - 1 then + k += 1 + targets[k] = if zero[c] then false else spec[c] + end + end + residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) + end + -- inverse coupling + for i = map.couplingSteps, 1, -1 do + local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1] + for j = 1, n2 do + local mv, av = m[j], a[j] + local m2, a2 + if mv > 0 then + if av > 0 then + m2, a2 = mv, mv - av + else + a2, m2 = mv, mv + av + end + else + if av > 0 then + m2, a2 = mv, mv + av + else + a2, m2 = mv, mv - av + end + end + m[j], a[j] = m2, a2 + end + end + -- floor curves, IMDCT, windows + local plan = st.plans[n] + local lslope = st.slopes[leftEnd - leftStart] + local rslope = st.slopes[rightEnd - rightStart] + for c = 1, ch do + local sp = spec[c] + local fr = st.frame[c] + if reallyZero[c] then + for j = 1, n do + fr[j] = 0 + end + else + local s = map.mux[c] + 1 + floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2) + Mdct.inverse(plan, sp, 1, 1, fr, 1) + for j = 1, leftStart do + fr[j] = 0 + end + local L = leftEnd - leftStart + for j = 0, L - 1 do + fr[leftStart + j + 1] *= lslope[j + 1] + end + local R = rightEnd - rightStart + for j = 0, R - 1 do + fr[rightStart + j + 1] *= rslope[R - j] + end + for j = rightEnd + 1, n do + fr[j] = 0 + end + end + end + -- overlap-add with the previous frame; return the samples between the two centres + local prevN = st.prevN + local count = 0 + if prevN > 0 then + count = prevN // 4 + n // 4 + local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre + local tl = st.tailLen + for c = 1, ch do + local out, tail, fr = st.out[c], st.tail[c], st.frame[c] + for j = 0, count - 1 do + local v = if j < tl then tail[j + 1] else 0 + local fi = j - o + if fi >= 0 then + v += fr[fi + 1] + end + out[j + 1] = v + end + end + end + -- the new tail: this frame from its centre to the end of its window + local tl = rightEnd - n2 + for c = 1, ch do + local tail, fr = st.tail[c], st.frame[c] + for j = 1, tl do + tail[j] = fr[n2 + j] + end + end + st.tailLen = tl + st.prevN = n + return count +end + +return Packet diff --git a/src/Formats/audio/vorbis/Setup.luau b/src/Formats/audio/vorbis/Setup.luau new file mode 100644 index 0000000..e5eb312 --- /dev/null +++ b/src/Formats/audio/vorbis/Setup.luau @@ -0,0 +1,429 @@ +--!strict +--!native +-- audio/vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate, +-- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings, +-- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). +-- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000). +-- Never throws: every parser returns nil, message on bad data. +local Codebook = require("@formats/audio/vorbis/Codebook") + +local Setup = {} + +local bits, ilog = Codebook.bits, Codebook.ilog +local readu8, readu32 = buffer.readu8, buffer.readu32 + +export type Ident = { + channels: number, + sampleRate: number, + bitrateMax: number, + bitrateNominal: number, + bitrateMin: number, + blocksize0: number, + blocksize1: number, +} + +export type Floor1 = { + partitions: number, + partitionClass: { number }, -- 1-based list of class numbers (0-based values) + classDims: { number }, -- [class + 1] + classSubs: { number }, + classMaster: { number }, + subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1 + multiplier: number, + xlist: { number }, -- [j + 1] + values: number, + sorted: { number }, -- point indices (0-based) by increasing x + low: { number }, -- neighbours, [j + 1] (0-based indices) + high: { number }, +} + +export type Residue = { + type: number, + begin: number, + finish: number, + partSize: number, + classifications: number, + classbook: number, + books: { { number } }, -- [class + 1][pass + 1] = book or -1 + classdata: { { number } }, -- [classbook entry + 1][k + 1] = class +} + +export type Mapping = { + submaps: number, + couplingSteps: number, + magnitude: { number }, -- [step + 1] channel (0-based) + angle: { number }, + mux: { number }, -- [channel + 1] submap (0-based) + submapFloor: { number }, + submapResidue: { number }, +} + +export type Mode = { blockflag: number, mapping: number } + +export type Setup = { + books: { Codebook.Book }, + floors: { Floor1 }, + residues: { Residue }, + mappings: { Mapping }, + modes: { Mode }, + modeBits: number, + maxFloorValues: number, +} + +local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean + return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" +end +Setup.isVorbis = isVorbis + +-- ident(buf, offset, size) -> Ident | nil, message +function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) + if not isVorbis(b, o, n, 1) then + return nil, "not a Vorbis identification header" + end + if n < 30 then + return nil, "short identification header" + end + if readu32(b, o + 7) ~= 0 then + return nil, "Vorbis version " .. readu32(b, o + 7) + end + local ch = readu8(b, o + 11) + local rate = readu32(b, o + 12) + local bs = readu8(b, o + 28) + local l0, l1 = bs % 16, bs // 16 + if ch == 0 or rate == 0 then + return nil, "no channels or no sample rate" + end + if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then + return nil, "bad blocksizes" + end + if readu8(b, o + 29) % 2 == 0 then + return nil, "identification header framing bit not set" + end + return { + channels = ch, + sampleRate = rate, + bitrateMax = buffer.readi32(b, o + 16), + bitrateNominal = buffer.readi32(b, o + 20), + bitrateMin = buffer.readi32(b, o + 24), + blocksize0 = 2 ^ l0, + blocksize1 = 2 ^ l1, + }, + nil +end + +-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message +function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) + if not isVorbis(b, o, n, 3) then + return nil, nil + end + local p, e = o + 7, o + n + if p + 4 > e then + return nil, nil + end + local vlen = readu32(b, p) + p += 4 + if vlen > e - p then + return nil, nil + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + local list = {} + if p + 4 > e then + return vendor, list + end + local count = readu32(b, p) + p += 4 + for _ = 1, count do + if p + 4 > e then + break + end + local len = readu32(b, p) + p += 4 + if len > e - p then + break + end + table.insert(list, buffer.readstring(b, p, len)) + p += len + end + return vendor, list +end + +-- setup(buf, offset, size, ident) -> Setup | nil, message +function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) + if not isVorbis(b, o, n, 5) then + return nil, "not a Vorbis setup header" + end + local br = Codebook.reader(b, o + 7, n - 7) + local channels = id.channels + -- codebooks + local books: { Codebook.Book } = {} + local nbooks = bits(br, 8) + 1 + for i = 1, nbooks do + local book, err = Codebook.read(br) + if not book then + return nil, "codebook " .. (i - 1) .. ": " .. tostring(err) + end + books[i] = book + end + -- time domain transforms (placeholders) + local ntimes = bits(br, 6) + 1 + for _ = 1, ntimes do + if bits(br, 16) ~= 0 then + return nil, "bad time domain transform" + end + end + -- floors + local floors: { Floor1 } = {} + local maxValues = 0 + local nfloors = bits(br, 6) + 1 + for i = 1, nfloors do + local ftype = bits(br, 16) + if ftype == 0 then + return nil, "floor 0" + elseif ftype ~= 1 then + return nil, "bad floor type " .. ftype + end + local parts = bits(br, 5) + local pclass = table.create(parts, 0) + local maxClass = -1 + for j = 1, parts do + pclass[j] = bits(br, 4) + if pclass[j] > maxClass then + maxClass = pclass[j] + end + end + local cdims, csubs, cmaster, subBooks = {}, {}, {}, {} + for j = 1, maxClass + 1 do + cdims[j] = bits(br, 3) + 1 + csubs[j] = bits(br, 2) + cmaster[j] = -1 + if csubs[j] > 0 then + cmaster[j] = bits(br, 8) + if cmaster[j] >= nbooks then + return nil, "bad floor master book" + end + end + local sb = {} + for k = 1, 2 ^ csubs[j] do + sb[k] = bits(br, 8) - 1 + if sb[k] >= nbooks then + return nil, "bad floor subclass book" + end + end + subBooks[j] = sb + end + local mult = bits(br, 2) + 1 + local rangebits = bits(br, 4) + local xlist = { 0, 2 ^ rangebits } + for j = 1, parts do + local c = pclass[j] + for _ = 1, cdims[c + 1] do + table.insert(xlist, bits(br, rangebits)) + end + end + local values = #xlist + if values > 65 * 8 then + return nil, "too many floor points" + end + if br.eop then + return nil, "setup header ends in a floor" + end + local order = table.create(values, 0) + for j = 1, values do + order[j] = j - 1 + end + table.sort(order, function(a: number, c: number): boolean + return xlist[a + 1] < xlist[c + 1] + end) + for j = 1, values - 1 do + if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then + return nil, "duplicate floor x" + end + end + local low, high = table.create(values, 0), table.create(values, 0) + for j = 2, values - 1 do + local lo, hi = -1, 65536 + local x = xlist[j + 1] + for k = 0, j - 1 do + local xv = xlist[k + 1] + if xv > lo and xv < x then + low[j + 1], lo = k, xv + end + if xv < hi and xv > x then + high[j + 1], hi = k, xv + end + end + end + floors[i] = { + partitions = parts, + partitionClass = pclass, + classDims = cdims, + classSubs = csubs, + classMaster = cmaster, + subBooks = subBooks, + multiplier = mult, + xlist = xlist, + values = values, + sorted = order, + low = low, + high = high, + } + if values > maxValues then + maxValues = values + end + end + -- residues + local residues: { Residue } = {} + local nres = bits(br, 6) + 1 + for i = 1, nres do + local rtype = bits(br, 16) + if rtype > 2 then + return nil, "bad residue type " .. rtype + end + local rbegin, rend = bits(br, 24), bits(br, 24) + local psize = bits(br, 24) + 1 + local ncls = bits(br, 6) + 1 + local cbook = bits(br, 8) + if rend < rbegin then + return nil, "residue end before begin" + end + if cbook >= nbooks then + return nil, "bad residue classbook" + end + local cascade = table.create(ncls, 0) + for j = 1, ncls do + local lowBits = bits(br, 3) + local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0 + cascade[j] = highBits * 8 + lowBits + end + local rbooks = {} + for j = 1, ncls do + local row = table.create(8, -1) + local c = cascade[j] + for k = 1, 8 do + if c % 2 == 1 then + row[k] = bits(br, 8) + if row[k] >= nbooks then + return nil, "bad residue book" + end + end + c = c // 2 + end + rbooks[j] = row + end + if br.eop then + return nil, "setup header ends in a residue" + end + -- class numbers of each classbook entry (stb's classdata) + local cb = books[cbook + 1] + local cw = cb.dims + if cb.entries * cw > 2 ^ 22 then + return nil, "residue classbook too large" + end + local classdata = table.create(cb.entries) + for j = 0, cb.entries - 1 do + local row = table.create(cw, 0) + local tmp = j + for k = cw, 1, -1 do + row[k] = tmp % ncls + tmp = tmp // ncls + end + classdata[j + 1] = row + end + residues[i] = { + type = rtype, + begin = rbegin, + finish = rend, + partSize = psize, + classifications = ncls, + classbook = cbook, + books = rbooks, + classdata = classdata, + } + end + -- mappings + local mappings: { Mapping } = {} + local nmaps = bits(br, 6) + 1 + local chBits = ilog(channels - 1) + for i = 1, nmaps do + if bits(br, 16) ~= 0 then + return nil, "bad mapping type" + end + local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1 + local steps = 0 + local mag, ang = {}, {} + if bits(br, 1) == 1 then + steps = bits(br, 8) + 1 + if steps > channels then + return nil, "too many coupling steps" + end + for k = 1, steps do + mag[k] = bits(br, chBits) + ang[k] = bits(br, chBits) + if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then + return nil, "bad coupling channels" + end + end + end + if bits(br, 2) ~= 0 then + return nil, "mapping reserved bits set" + end + local mux = table.create(channels, 0) + if submaps > 1 then + for j = 1, channels do + mux[j] = bits(br, 4) + if mux[j] >= submaps then + return nil, "bad channel mux" + end + end + end + local sf, sr = {}, {} + for j = 1, submaps do + bits(br, 8) + sf[j] = bits(br, 8) + sr[j] = bits(br, 8) + if sf[j] >= nfloors or sr[j] >= nres then + return nil, "bad submap floor / residue" + end + end + mappings[i] = { + submaps = submaps, + couplingSteps = steps, + magnitude = mag, + angle = ang, + mux = mux, + submapFloor = sf, + submapResidue = sr, + } + end + -- modes + local modes: { Mode } = {} + local nmodes = bits(br, 6) + 1 + for i = 1, nmodes do + local bf = bits(br, 1) + local wt, tt = bits(br, 16), bits(br, 16) + local m = bits(br, 8) + if wt ~= 0 or tt ~= 0 or m >= nmaps then + return nil, "bad mode" + end + modes[i] = { blockflag = bf, mapping = m } + end + if br.eop then + return nil, "setup header truncated" + end + if bits(br, 1) ~= 1 then + return nil, "setup header framing bit not set" + end + return { + books = books, + floors = floors, + residues = residues, + mappings = mappings, + modes = modes, + modeBits = ilog(nmodes - 1), + maxFloorValues = maxValues, + }, + nil +end + +return Setup diff --git a/src/Formats/audio/vorbis/Tables.luau b/src/Formats/audio/vorbis/Tables.luau new file mode 100644 index 0000000..435f719 --- /dev/null +++ b/src/Formats/audio/vorbis/Tables.luau @@ -0,0 +1,37 @@ +--!strict +-- audio/vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22, +-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here). +return table.freeze({ + 1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07, + 1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07, + 2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07, + 4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07, + 7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06, + 1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06, + 2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06, + 3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06, + 5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06, + 9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05, + 1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05, + 2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05, + 4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05, + 7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824, + 0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536, + 0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787, + 0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927, + 0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457, + 0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129, + 0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743, + 0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906, + 0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176, + 0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080, + 0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797, + 0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276, + 0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758, + 0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227, + 0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215, + 0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342, + 0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414, + 0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640, + 0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0, +}) diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau new file mode 100644 index 0000000..79b192f --- /dev/null +++ b/src/Formats/audio/vorbis/init.luau @@ -0,0 +1,448 @@ +--!strict +-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau +-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct, +-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last +-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). +-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, +-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level +-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Not supported: floor 0 (Err.UNSUPPORTED, as in +-- stb_vorbis; no encoder has produced it since 2000), chained streams (the first logical Vorbis stream is decoded). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Setup = require("@formats/audio/vorbis/Setup") +local Packet = require("@formats/audio/vorbis/Packet") + +-- ------------------------------------------------------------------------------------------------ contract +local Vorbis = { + name = "vorbis", + category = "audio", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255 }, +} + +export type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TAG_KEYS = { tracknumber = "track", description = "comment" } + +local function tagsOf(comments: { string }): Types.Tags + local tags: Types.Tags = {} + for _, s in comments do + local eq = string.find(s, "=", 1, true) + if eq then + local k = string.lower(string.sub(s, 1, eq - 1)) + local v = string.sub(s, eq + 1) + k = TAG_KEYS[k] or k + tags[k] = if tags[k] then tags[k] .. "; " .. v else v + end + end + return tags +end + +-- the three headers -> ident, setup, vendor, tags | nil, Err +local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?) + local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id then + return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size) + if not vendor then + return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") + end + local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id) + if not setup then + local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT + return nil, nil, nil, nil, Err.new(code, serr or "bad setup header") + end + return id, setup, vendor, tagsOf(comments or {}), nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vorbis.sniff(r: Bytes.Reader): number + if r:remaining() < 35 or r:peek(4) ~= "OggS" then + return 0 + end + local b, p = r.buf, r.pos + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 > r.limit then + return 0 + end + return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vorbis.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local ch = d.channels + local parts, total = {}, 0 + while true do + local b, n = d:read(65536) + if n == 0 then + break + end + local copy = buffer.create(n * ch * 4) + buffer.copy(copy, 0, b, 0, n * ch * 4) + table.insert(parts, copy) + total += n + end + local a = Types.Audio.new(d.sampleRate, ch, total) + local o = 0 + for _, p in parts do + buffer.copy(a.samples, o, p) + o += buffer.len(p) + end + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) +local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) + local lo = math.max(g0, self.startG, self.skipTo) + if hi > g0 + count then + hi = g0 + count + end + if hi > lo then + table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) + end +end + +local function copyOut(self: any, count: number): { { number } } + local t = table.create(self.channels) + for c = 1, self.channels do + local src = self.st.out[c] + local a = table.create(count, 0) + table.move(src, 1, count, 1, a) + t[c] = a + end + return t +end + +-- decode packets until something is queued; false at the end of the stream +local function decodeMore(self: any): boolean + local reader, st = self.reader, self.st + while not self.ended do + local p = reader:nextPacket() + if p == nil then + self.ended = true + break + end + if p.gap then + Packet.reset(st) + self.syncing, self.pend, self.pendCount = true, {}, 0 + end + local count = Packet.decode(st, p.data, p.offset, p.size) + if count >= 0 then + local endG = if p.eos and p.granule >= 0 then p.granule else math.huge + if self.syncing then + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + -- the position is known again: this packet's output ends at its granule + local g = p.granule - self.pendCount + if p.eos and self.pendCount > 0 then + g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position + end + for _, c in self.pend do + push(self, c[1], g, c[2], endG) + g += c[2] + end + self.pos = g + self.syncing, self.pend, self.pendCount = false, {}, 0 + end + else + local g0 = self.pos + self.pos += count + if count > 0 then + push(self, st.out, g0, count, endG) + end + if p.granule >= 0 and not p.eos then + self.pos = p.granule + end + end + if p.eos then + self.ended = true + end + if #self.queue > 0 then + return true + end + end + end + return #self.queue > 0 +end + +function Stream.read(self: any, n: number, out: buffer?): (buffer, number) + local ch = self.channels + n = math.max(0, math.floor(n)) + local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4) + local got = 0 + local writef32 = buffer.writef32 + while got < n do + local q = self.queue[1] + if q == nil then + if not decodeMore(self) then + break + end + q = self.queue[1] + end + local arrays, first, last = q[1], q[2], q[3] + local take = math.min(n - got, last - first + 1) + for c = 1, ch do + local a = arrays[c] + local o = got * ch * 4 + (c - 1) * 4 + for i = first, first + take - 1 do + writef32(b, o, a[i]) + o += ch * 4 + end + end + got += take + self.next = q[4] + take + if first + take > last then + table.remove(self.queue, 1) + else + q[2] = first + take + q[4] += take + end + end + if got > 0 then + self.skipTo = -math.huge + end + return b, got +end + +function Stream.position(self: any): number + return (self.next - self.startG) / self.sampleRate +end + +-- back to the first audio packet +local function restart(self: any) + local r = self.reader + r:rewind() + for _ = 1, 3 do + r:nextPacket() + end + Packet.reset(self.st) + self.pos = self.base + self.syncing, self.pend, self.pendCount = false, {}, 0 + self.ended = false + self.queue = {} +end + +function Stream.seek(self: any, seconds: number) + local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) + if target ~= target then + target = self.startG + end + if self.lastG >= 0 and target > self.lastG then + target = self.lastG + end + self.skipTo = target + self.next = target + local r = self.reader + local g = target - self.st.n1 + for _ = 1, 16 do + if g <= self.startG then + break + end + local G = r:seekGranule(g) + if G == nil or G < 0 then + break + end + -- decode forward to the next page boundary to learn the exact position + Packet.reset(self.st) + self.queue = {} + self.ended = false + self.syncing, self.pend, self.pendCount = true, {}, 0 + self.pos = G + local ok = false + while true do + local p = r:nextPacket() + if p == nil then + break + end + local count = Packet.decode(self.st, p.data, p.offset, p.size) + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + if not p.eos then + local g0 = p.granule - self.pendCount + for _, c in self.pend do + push(self, c[1], g0, c[2], math.huge) + g0 += c[2] + end + self.pos = p.granule + self.syncing, self.pend, self.pendCount = false, {}, 0 + ok = true + end + break + end + end + if ok then + return + end + g = G - 1 -- the last page: start one page earlier + end + restart(self) + self.skipTo = target + self.next = target +end + +function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("vorbis") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") + end + local reader = demux:reader(serial) + local h1 = reader:nextPacket() + if h1 == nil then + return nil, Err.new(Err.TRUNCATED, "missing identification header") + end + local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id0 then + return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local h2 = reader:nextPacket() + if h2 == nil then + return nil, Err.new(Err.TRUNCATED, "missing comment header") + end + local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } + local h3 = reader:nextPacket() + if h3 == nil then + return nil, Err.new(Err.TRUNCATED, "missing setup header") + end + local id, setup, vendor, tags, herr = headers(h1, h2copy, h3) + if not id then + return nil, herr + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + -- the granule of the first returned sample: the first granule page minus what its packets return + local base = 0 + do + local prev, sum = 0, 0 + while true do + local p = reader:nextPacket() + if p == nil then + break + end + local bs = Packet.blocksize(st, p.data, p.offset, p.size) + if bs > 0 then + if prev > 0 then + sum += prev // 4 + bs // 4 + end + prev = bs + end + if p.granule >= 0 then + base = p.granule - sum + if p.eos then + base = 0 -- one page holds the whole stream: the spec trims its end, not its start + end + break + end + end + end + local info = demux:stream(serial) + local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1 + local startG = math.max(base, 0) + local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0 + local rate = id.sampleRate + local self = setmetatable({ + sampleRate = rate, + channels = id.channels, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal, + tags = tags, + vendor = vendor, + ident = id, + source = { + format = "vorbis", + codec = "vorbis", + vendor = vendor, + blocksizes = { id.blocksize0, id.blocksize1 }, + nominalBitrate = id.bitrateNominal, + }, + demux = demux, + reader = reader, + st = st, + base = base, + startG = startG, + lastG = lastG, + pos = base, + next = startG, + skipTo = -math.huge, + queue = {}, + syncing = false, + pend = {}, + pendCount = 0, + ended = false, + }, Stream) + restart(self) + return self :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three +-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. +-- local pd = Vorbis.packetDecoder(h1, h2, h3) +-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] +-- pd:reset() -- after a seek +function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?) + local function pk(b: buffer): any + return { data = b, offset = 0, size = buffer.len(b) } + end + local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3)) + if not id then + return nil, err + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + return { + sampleRate = id.sampleRate, + channels = id.channels, + vendor = vendor, + tags = tags, + out = st.out, + decode = function(_self: any, b: buffer, offset: number, size: number): number + if offset < 0 or size < 0 or offset + size > buffer.len(b) then + return -1 + end + return Packet.decode(st, b, offset, size) + end, + reset = function(_self: any) + Packet.reset(st) + end, + }, + nil +end + +return Vorbis diff --git a/tests/audio/vorbis.luau b/tests/audio/vorbis.luau new file mode 100644 index 0000000..2cc5c01 --- /dev/null +++ b/tests/audio/vorbis.luau @@ -0,0 +1,193 @@ +-- audio/vorbis tests: oggenc / ffmpeg streams (qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1, +-- transients, silence, tags, sub-block lengths) against oggdec (libvorbisfile: sample counts and 16-bit samples, so +-- start / end trimming is exact) and ffmpeg's f32 decode (SNR); streaming reads; seeking (sample-exact against the +-- reference at the target); the packet-level decoder; errors; fuzz. Fixtures: tools/fixtures/vorbis.py. +local T = require("@tests/T") +local Vorbis = require("@formats/audio/vorbis") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Cases = require("@tests/gen/vorbis_cases") + +local t = T.suite("vorbis") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function s16(x: number): number + local v = math.floor(x * 32768 + 0.5) + return math.clamp(v, -32768, 32767) +end +-- the largest |our sample as s16 - oggdec's| over n samples of ours at byte a0 against ref16 from sample r0 +local function maxDiff16(a: buffer, a0: number, ref: buffer, r0: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(s16(buffer.readf32(a, a0 + i * 4)) - buffer.readi16(ref, (r0 + i) * 2)) + if d > m then + m = d + end + end + return m +end +local function snr(a: buffer, ref: buffer, n: number): number + local sig, er = 0, 0 + for i = 0, n - 1 do + local x = buffer.readf32(ref, i * 4) + local d = x - buffer.readf32(a, i * 4) + sig += x * x + er += d * d + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end + +t:eq(Vorbis.name, "vorbis", "name") +t:eq(Vorbis.category, "audio", "category") +t:check(Vorbis.caps.decode and Vorbis.open ~= nil, "caps") + +local minSnr = math.huge +for _, c in Cases do + local a, err = Vorbis.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames = oggdec's") + t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input") + local ref16 = buffer.fromstring(c.ref16) + local n = c.frames * c.channels + local d = maxDiff16(a.samples, 0, ref16, 0, n) + t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d)) + if c.ffRef then + local s = snr(a.samples, buffer.fromstring(c.ffRef), n) + minSnr = math.min(minSnr, s) + t:check(s > 100, string.format("%s: SNR vs ffmpeg %.1f dB", c.name, s)) + end + -- streaming in odd chunks gives the same samples + local dec = Vorbis.open(reader(c.data)) :: Types.Decoder + t:eq(dec.frames, c.frames, c.name .. ": Decoder.frames") + local got, ok = 0, true + while true do + local b, k = dec:read(1013) + if k == 0 then + break + end + for i = 0, k * c.channels - 1, 7 do + ok = ok and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, got * c.channels * 4 + i * 4) + end + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + -- seeks: sample-exact against the full decode + for _, frac in { 0.5, 0.1, 0.93, 0 } do + local target = math.floor(c.frames * frac) + dec:seek(target / c.rate) + t:check(math.abs(dec:position() - target / c.rate) < 1e-9, c.name .. ": position after seek") + local b, k = dec:read(300) + local want = math.min(300, c.frames - target) + t:eq(k, want, string.format("%s: frames after seek to %d", c.name, target)) + local same = true + for i = 0, k * c.channels - 1 do + same = same and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, (target * c.channels + i) * 4) + end + t:check(same, string.format("%s: samples after seek to %d", c.name, target)) + end +end +t:note("%d streams match oggdec (counts, 1 LSB) and ffmpeg (min SNR %.1f dB)", #Cases, minSnr) + +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- tags, meta, sniff, sub-range +do + local c = case("q2-stereo-32k-tags") + local dec = Vorbis.open(reader(c.data)) :: any + t:eq(dec.tags.title, "A Title", "title tag") + t:eq(dec.tags.artist, "An Artist", "artist tag") + t:eq(dec.tags.album, "The Album", "album tag") + t:eq(dec.tags.track, "7", "track tag") + t:eq(dec.tags.comment, "hello vorbis", "comment tag") + t:check(type(dec.vendor) == "string" and string.find(dec.vendor, "Xiph", 1, true) ~= nil, "vendor") + t:check(dec.bitrate > 0 and math.abs(dec.duration - c.frames / c.rate) < 1e-9, "bitrate / duration") + t:eq(Vorbis.sniff(reader(c.data)), 1, "sniff") + t:eq(Vorbis.sniff(reader("OggS")), 0, "sniff short") + t:eq(Vorbis.sniff(reader("RIFF")), 0, "sniff other") + local big = buffer.create(#c.data + 11) + buffer.writestring(big, 11, c.data) + local a = Vorbis.decode(Bytes.reader(big, 11, #c.data)) + t:check(a and a.frames == c.frames, "decode from a sub-range") +end + +-- the packet-level decoder (as Matroska / MP4 would use it) gives the same samples, minus the Ogg trimming +do + local c = case("q5-stereo-44k-music") + local full = Vorbis.decode(reader(c.data)) :: Types.Audio + local demux = Ogg.open(buffer.fromstring(c.data)) + local serial = demux:find("vorbis") + local h = {} + for i = 1, 3 do + h[i] = Ogg.copy(demux:nextPacket(serial)) + end + local pd = Vorbis.packetDecoder(h[1], h[2], h[3]) + t:check(pd and pd.channels == 2 and pd.sampleRate == 44100, "packetDecoder") + local total, same = 0, true + for p in demux:packets(serial) do + local n = pd:decode(p.data, p.offset, p.size) + for i = 1, n, 13 do + if total + i <= full.frames then + same = same and math.abs(pd.out[1][i] - buffer.readf32(full.samples, (total + i - 1) * 8)) < 1e-6 + end + end + total += math.max(n, 0) + end + t:check(same and total >= full.frames, "packetDecoder samples") + local _, e = Vorbis.packetDecoder(h[2], h[1], h[3]) + t:check(e and e.code == Err.CORRUPT, "packetDecoder with headers swapped") +end + +-- errors +do + local _, e1 = Vorbis.decode(reader("OggS but not really")) + t:check(e1 and Err.is(e1), "junk: " .. tostring(e1)) + local c = case("short-100").data + local _, e2 = Vorbis.decode(reader(string.sub(c, 1, 60))) + t:check(e2 and Err.is(e2), "cut in the headers: " .. tostring(e2)) + -- a truncated stream decodes what is there + local q = case("q5-stereo-44k-music") + local cut = Vorbis.decode(reader(string.sub(q.data, 1, #q.data // 2)), { verify = false }) + t:check(cut and cut.frames > 0 and cut.frames < q.frames, "truncated stream") +end + +-- fuzz: whole streams with mutations past the headers, truncations, garbage +do + local samples = {} + for _, name in { "short-100", "short-3000-mono", "q-1-mono-8k-music", "ffmpeg-mono-16k" } do + table.insert(samples, case(name).data) + end + t:fuzz("decode", function(b: buffer) + return Vorbis.decode(Bytes.reader(b), { verify = false }) + end, samples, { mutations = 40 }) + t:fuzz("decode (CRC checked)", function(b: buffer) + return Vorbis.decode(Bytes.reader(b)) + end, samples, { mutations = 5, garbage = 20 }) + t:fuzz("open + seek", function(b: buffer) + local d = Vorbis.open(Bytes.reader(b), { verify = false }) + if d then + d:read(500) + d:seek(0.05) + d:read(500) + d:seek(1e9) + d:read(10) + end + return d + end, samples, { mutations = 10, garbage = 20 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index fd8d79c..5465ca5 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -84,3 +84,13 @@ for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", Op Opus.decode(Bytes.reader(b)) end) end +-- vorbis (ws-audio): 10 s of 44.1 kHz stereo music at oggenc -q 5 (tools/fixtures/vorbis.py) +do + local Vorbis = require("@formats/audio/vorbis") + local VB = require("@tests/gen/vorbis_bench") + local b = buffer.fromstring(VB.data) + local dt = bench("vorbis decode q5 (10 s st)", 3, VB.frames * VB.channels * 4, function() + Vorbis.decode(Bytes.reader(b)) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", VB.frames / VB.rate / dt)) +end diff --git a/tools/bench.sh b/tools/bench.sh index 76faa4d..814df57 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 mp3 opus > /dev/null || exit 1 +python3 -I tools/fixtures.py deflate png mp3 opus vorbis > /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 diff --git a/tools/fixtures/vorbis.py b/tools/fixtures/vorbis.py new file mode 100644 index 0000000..e4994ee --- /dev/null +++ b/tools/fixtures/vorbis.py @@ -0,0 +1,57 @@ +# Ogg Vorbis fixtures (tools/fixtures.py): files made by oggenc (libvorbis, vorbis-tools) and ffmpeg (libvorbis) from +# the test signals in tools/fixtures/_audio.py: qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1, +# transients (block switching), silence, tags, a stream shorter than one block. References: oggdec (libvorbisfile: +# the authority on start / end trimming) as 16-bit samples, and ffmpeg's f32 decode (more precise, but its Ogg demuxer +# trims some streams differently: the test uses it only when its frame count agrees with oggdec). +# tests/gen/vorbis_cases.luau { name, data, rate, channels, frames (oggdec), ref16 (s16le, oggdec), ffFrames, +# ffRef (f32le, ffmpeg), inputFrames } +import importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +CASES = [ + # name, signal, rate, channels, seconds, tool, args + ("q5-stereo-44k-music", "music", 44100, 2, 1.5, "oggenc", ["-q", "5"]), + ("q-1-mono-8k-music", "music", 8000, 1, 1.0, "oggenc", ["-q", "-1"]), + ("q10-stereo-48k-sweep", "sweep", 48000, 2, 1.0, "oggenc", ["-q", "10"]), + ("q3-mono-22k-noise", "noise", 22050, 1, 0.7, "oggenc", ["-q", "3"]), + ("q0-stereo-44k-square", "square", 44100, 2, 1.0, "oggenc", ["-q", "0"]), + ("q2-stereo-32k-tags", "sine", 32000, 2, 0.6, "oggenc", ["-q", "2", "-t", "A Title", "-a", "An Artist", "-l", "The Album", "-N", "7", "-c", "comment=hello vorbis"]), + ("managed-64k-stereo", "music", 44100, 2, 1.0, "oggenc", ["--managed", "-b", "64"]), + ("silence-stereo", "silence", 44100, 2, 0.5, "oggenc", ["-q", "4"]), + ("short-100", "sine", 44100, 2, 100 / 44100, "oggenc", ["-q", "4"]), + ("short-3000-mono", "music", 44100, 1, 3000 / 44100, "oggenc", ["-q", "4"]), + ("q6-stereo-96k", "music", 96000, 2, 0.4, "oggenc", ["-q", "6"]), + ("ffmpeg-5.1-48k", "music", 48000, 6, 0.6, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "4"]), + ("ffmpeg-mono-16k", "sweep", 16000, 1, 0.8, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "1"]), + ("loud-stereo", "loud", 44100, 2, 0.5, "oggenc", ["-q", "8"]), +] + +INPUTS = [] + + +def generate(ctx): + cases = [] + bench = None + for name, kind, rate, ch, secs, tool, args in CASES: + frames = max(1, int(round(secs * rate))) + sig = A.signal(kind, rate, ch, frames, seed=len(name)) + wav = A.wav(sig, rate, ch, float_=True) if tool == "ffmpeg" else A.wav(sig, rate, ch, 16) + if tool == "oggenc": + data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "--serial", "1234"] + args + ["-o", "{out}", "{in}"], wav, "wav", "ogg") + else: + data = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}"] + args + ["-f", "ogg", "-y", "{out}"], wav, "wav", "ogg") + rrate, rch, ref = A.ffdecode(ctx, data, ext="ogg") + raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") + case = {"name": name, "data": data, "rate": rrate, "channels": rch, "frames": len(raw) // (2 * rch), "ref16": raw, + "ffFrames": len(ref) // rch, "inputFrames": frames} + if len(ref) // rch == len(raw) // (2 * rch): + case["ffRef"] = A.f32le(ref) + cases.append(case) + ctx.emit("vorbis_cases", cases) + # bench: 10 s of stereo music at q5 + sig = A.signal("music", 44100, 2, 441000, seed=9) + data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "-q", "5", "-o", "{out}", "{in}"], A.wav(sig, 44100, 2, 16), "wav", "ogg") + ctx.emit("vorbis_bench", {"data": data, "frames": 441000, "rate": 44100, "channels": 2}) From bdab71df779de8d2ca8e0eaf1346b8be0e67412c Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:54:11 -0500 Subject: [PATCH 11/28] ws-audio: fix the bench.luau merge --- tools/bench.luau | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/bench.luau b/tools/bench.luau index cde94d3..45f550e 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -98,6 +98,7 @@ do Vorbis.decode(Bytes.reader(b)) end) print(string.format("%-8s %-30s %8.0fx real time", runtime, "", VB.frames / VB.rate / dt)) +end for _, name in { "s16_long", "s24_96k" } do for _, c in FC do if c.name == name then From cf7c1b8ad2dc7f6583e071183ba74baed0cbbd99 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:00:04 -0500 Subject: [PATCH 12/28] ws-music: music/s3m read + render (OpenMPT-matched master volume / mono rule / default panning), finer comparison bands, voice ownership fix --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/codecs/Tracker/Player.luau | 23 ++- src/Formats/music/s3m/init.luau | 241 +++++++++++++++++++++++++ tests/music/_similar.luau | 14 +- tests/music/mod.luau | 8 +- tests/music/s3m.luau | 71 ++++++++ tests/music/zz_probe.luau | 27 +++ tests/music/zz_voices.luau | 24 +++ tools/fixtures/_tracker.py | 6 +- tools/fixtures/s3m.py | 124 +++++++++++++ tools/fixtures/zz_probe.py | 62 +++++++ 12 files changed, 598 insertions(+), 15 deletions(-) create mode 100644 src/Formats/music/s3m/init.luau create mode 100644 tests/music/s3m.luau create mode 100644 tests/music/zz_probe.luau create mode 100644 tests/music/zz_voices.luau create mode 100644 tools/fixtures/s3m.py create mode 100644 tools/fixtures/zz_probe.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 9bd0313..450e651 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -8,6 +8,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | | music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | +| music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | | music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 751f221..222ae4e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -50,6 +50,18 @@ local list: { Entry } = { return require("@formats/music/mod") end, }, + { + name = "s3m", + category = "music", + path = "music/s3m", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/s3m") + end, + }, { name = "sf2", category = "music", diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau index df4350b..7f34e11 100644 --- a/src/Formats/codecs/Tracker/Player.luau +++ b/src/Formats/codecs/Tracker/Player.luau @@ -23,7 +23,7 @@ local MOD, S3M, XM, IT = 1, 2, 3, 4 Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } -local MAX_VOICES = 96 -- channels + IT background voices +local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions -- ------------------------------------------------------------------------------------------------ state local function newVoice(): any @@ -86,6 +86,7 @@ local function newVoice(): any tremorMute = false, surround = false, rampN = 0, + owner = 0, -- the channel whose foreground voice this is (0: free or background) order = 0, -- allocation age } end @@ -225,7 +226,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any end st.chans[i] = c end - for i = 1, MAX_VOICES do + for i = 1, m.channels + BG_VOICES do st.voices[i] = newVoice() end st.master = Player.masterGain(m, fmt) @@ -239,7 +240,7 @@ function Player.masterGain(m: any, fmt: number): number if fmt == IT then return 0.5 * (m.mixVolume or 48) / 48 elseif fmt == S3M then - return 0.5 * (m.mixVolume or 48) / 48 + return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the master volume, 64 = 0.5 end -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) return 2 / clamp(m.channels, 2, 8) @@ -361,7 +362,7 @@ end local function allocVoice(st: any): any local best, bestScore = nil, math.huge for _, v in st.voices do - if not v.active then + if not v.active and v.owner == 0 then return v end if v.bg then @@ -375,7 +376,17 @@ local function allocVoice(st: any): any best.active = false return best end - return st.voices[1] -- unreachable while MAX_VOICES > channels: every channel holds one foreground voice + -- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway + for _, v in st.voices do + if not v.active then + local c = st.chans[v.owner] + if c and c.voice == v then + c.voice = nil + end + return v + end + end + return st.voices[1] -- unreachable: there are more voices than channels end local function keyOff(st: any, v: any) @@ -422,6 +433,7 @@ local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, i if v == nil or v.bg then v = allocVoice(st) c.voice = v + v.owner = c.idx end local wasActive = v.active v.active = smp.length > 0 and smp.data ~= nil @@ -494,6 +506,7 @@ local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: nu return end v.bg = true + v.owner = 0 c.voice = nil if nna == 2 then keyOff(st, v) diff --git a/src/Formats/music/s3m/init.luau b/src/Formats/music/s3m/init.luau new file mode 100644 index 0000000..f7a80f7 --- /dev/null +++ b/src/Formats/music/s3m/init.luau @@ -0,0 +1,241 @@ +--!strict +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism +-- Tracker). Reads into the codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio +-- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning +-- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 +-- speed reference, as IT shows S3M files). +-- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local S3m = { + name = "s3m", + category = "music", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function S3m.sniff(r: Bytes.Reader): number + if r:size() >= 48 and r:peek(4, 44) == "SCRM" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:size() < 96 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(4, 44) ~= "SCRM" then + return nil, Err.new(Err.CORRUPT, "no SCRM signature") + end + local title = r:fixed(28) + r:seek(32) + local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le() + local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le() + r:seek(48) + local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:seek(64) + local chnset: { number } = {} + for i = 1, 32 do + chnset[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 256 or patnum > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + -- channels: enabled PCM channels (0..15); the count is the last used one + local nch = 0 + for i = 1, 32 do + local c = chnset[i] + if c < 16 then + nch = i + end + end + if nch == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)") + end + local m = Tracker.newModule("s3m", nch) + m.title = title + m.speed = if speed > 0 and speed < 255 then speed else 6 + m.tempo = if tempo >= 33 then tempo else 125 + m.globalVolume = math.min(gv, 64) * 2 + m.mixVolume = math.max(mv % 128, 16) + if mv < 128 then + -- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same) + m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5) + end + m.linear = false + m.instrumentMode = false + m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 + m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 + m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } + -- orders, parapointers, panning + r:seek(96) + for i = 1, ordnum do + local o = r:u8() + table.insert(m.order, o) + end + local insPtr, patPtr = {}, {} + for i = 1, insnum do + insPtr[i] = r:u16le() * 16 + end + for i = 1, patnum do + patPtr[i] = r:u16le() * 16 + end + local pans: { number } = {} + if dp == 252 then + for i = 1, 32 do + pans[i] = r:u8() + end + end + if r.err then + return nil, r.err + end + -- drop trailing end markers; keep inner "+++" / "---" + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + local stereo = mv >= 128 + for i = 1, nch do + local c = chnset[i] + local pan = 128 + if stereo then + pan = if c % 16 >= 8 then 0xCC else 0x33 + local p = pans[i] + if p and bit32.band(p, 0x20) ~= 0 then + pan = (p % 16) * 0x11 + end + end + m.channelPan[i] = pan + m.channelMute[i] = c >= 16 + end + -- samples + local total = 0 + local unsigned = ffi ~= 1 + for i = 1, insnum do + local s = Tracker.newSample() + m.samples[i] = s + local h = r:sub(insPtr[i], 80) + if h:size() < 80 then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i]) + end + local typ = h:u8() + h:skip(12) + local hi = h:u8() + local lo = h:u16le() + local len, ls, le = h:u32le(), h:u32le(), h:u32le() + local vol = h:u8() + h:skip(1) + local pack, sflags = h:u8(), h:u8() + local c2spd = h:u32le() + h:seek(48) + s.name = h:fixed(28) + s.volume = math.min(vol, 64) + s.c5speed = if c2spd > 0 then c2spd else 8363 + if typ == 1 and len > 0 and pack == 0 then + local bits = if bit32.band(sflags, 4) ~= 0 then 16 else 8 + local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1 + local off = (hi * 65536 + lo) * 16 + len = math.min(len, 2 ^ 26) + -- a short file: keep what is there + local avail = math.max(0, r:size() - off) // (nchs * bits // 8) + len = math.min(len, avail) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true }) + if data then + s.data, s.length, s.bits, s.channels = data, len, bits, nchs + if bit32.band(sflags, 1) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + local ptr = patPtr[p] + if ptr > 0 then + local pr = r:sub(ptr) + local plen = pr:u16le() + pr = pr:sub(2, math.max(0, plen - 2)) + local d = pat.data + local row = 0 + while row < 64 and not pr:eof() do + local what = pr:u8() + if what == 0 then + row += 1 + else + local ch = what % 32 + local note, ins, vol, cmd, info = 0, 0, 0, 0, 0 + if bit32.band(what, 0x20) ~= 0 then + local nb = pr:u8() + ins = pr:u8() + if nb == 254 then + note = 254 + elseif nb < 254 and nb % 16 < 12 then + note = (nb // 16) * 12 + nb % 16 + 13 + if note > 120 then + note = 0 + end + end + end + if bit32.band(what, 0x40) ~= 0 then + vol = math.min(pr:u8(), 64) + 1 + end + if bit32.band(what, 0x80) ~= 0 then + cmd, info = pr:u8(), pr:u8() + if cmd > 26 then + cmd, info = 0, 0 + end + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, cmd) + buffer.writeu8(d, o + 4, info) + end + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = S3m.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return S3m diff --git a/tests/music/_similar.luau b/tests/music/_similar.luau index b234d86..e97f7eb 100644 --- a/tests/music/_similar.luau +++ b/tests/music/_similar.luau @@ -1,10 +1,10 @@ -- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and -- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left, --- right and mid, and 20 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides. +-- right and mid, and 40 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides. local S = {} -local SR, HOP, BANDS = 44100, 2048, 20 -local F_LO, F_HI = 100, 16000 +local SR, HOP, BANDS = 44100, 2048, 40 +local F_LO, F_HI = 150, 16000 S.SR = SR local WINDOW = table.create(HOP, 0) @@ -112,6 +112,7 @@ end -- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames: -- gainDb total mid energy ratio in dB (ours / ref) -- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either) +-- envErr mean absolute difference of the per-block mid loudness in dB, after removing gainDb (same blocks) -- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB) -- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks) function S.compare(a: any, b: any): any @@ -144,6 +145,12 @@ function S.compare(a: any, b: any): any syy += (ys[i] - my) ^ 2 end local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1 + -- the mean loudness difference per block once the overall gain is taken out (dB, each side clamped at -60) + local envErr = 0 + for i = 1, #xs do + envErr += math.abs(math.max(xs[i], -60) - math.max(ys[i], -60) - gainDb) + end + envErr /= math.max(1, #xs) local cs, cn = 0, 0 local bal, bn = 0, 0 for k = 1, n do @@ -167,6 +174,7 @@ function S.compare(a: any, b: any): any return { gainDb = gainDb, envCorr = envCorr, + envErr = envErr, spectral = if cn > 0 then cs / cn else 1, balance = if bn > 0 then bal / bn else 0, frames = n, diff --git a/tests/music/mod.luau b/tests/music/mod.luau index f873981..30935ae 100644 --- a/tests/music/mod.luau +++ b/tests/music/mod.luau @@ -18,7 +18,7 @@ local function load(data: string): any return Mod.decode(Bytes.reader(buffer.fromstring(data))) end -local THRESH = { gainDb = 1.5, envCorr = 0.95, spectral = 0.93, balance = 0.05, duration = 0.01 } +local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } for _, c in Cases do local m, err = load(c.data) @@ -29,14 +29,14 @@ for _, c in Cases do t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) local r = S.compare(S.features(buf, frames), c.ref) - t:note("%-6s gain %+.2f dB, envelope r %.3f, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envCorr, r.spectral, r.balance, dec.duration) - if r.spectral < THRESH.spectral or r.envCorr < THRESH.envCorr then + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then for _, w in S.worst(S.features(buf, frames), c.ref, 6) do t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) end end t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") - t:check(r.envCorr > THRESH.envCorr, c.name .. ": loudness envelope") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") -- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files) diff --git a/tests/music/s3m.luau b/tests/music/s3m.luau new file mode 100644 index 0000000..989ca30 --- /dev/null +++ b/tests/music/s3m.luau @@ -0,0 +1,71 @@ +-- music/s3m tests: generated Scream Tracker 3 modules (tools/fixtures/s3m.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local S3m = require("@formats/music/s3m") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/s3m_cases") + +local t = T.suite("s3m") + +t:eq(S3m.name, "s3m", "name") +t:eq(S3m.category, "music", "category") +t:check(S3m.caps.decode and not S3m.caps.encode, "caps") + +local function load(data: string): any + return S3m.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(S3m.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = S3m.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/music/zz_probe.luau b/tests/music/zz_probe.luau new file mode 100644 index 0000000..53cd319 --- /dev/null +++ b/tests/music/zz_probe.luau @@ -0,0 +1,27 @@ +-- debug probes +local S = require("@tests/music/_similar") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/probe_cases") +local verbose = ... +local F = { s3m = require("@formats/music/s3m"), mod = require("@formats/music/mod") } +for _, c in Cases do + local m, err = F[c.fmt].decode(Bytes.reader(buffer.fromstring(c.data))) + if not m then print(c.name, err) continue end + local dec = m:render() + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local a = S.features(buf, frames) + local r = S.compare(a, c.ref) + print(string.format("%-8s gain %+.2f err %.2f env %.3f spec %.3f bal %.3f dur %.3f/%.3f", c.name, r.gainDb, r.envErr, r.envCorr, r.spectral, r.balance, dec.duration, c.duration)) + if verbose == c.name then + for k = 1, math.min(a.frames, c.ref.frames) do + local x, y = 20 * math.log10(a.rmsM[k] + 1e-6), 20 * math.log10(c.ref.rmsM[k] + 1e-6) + local sim = 0 + local dot, na, nb = 0, 0, 0 + for j = 1, 40 do + local p, q = a.bands[(k - 1) * 40 + j], c.ref.bands[(k - 1) * 40 + j] + dot += p * q; na += p * p; nb += q * q + end + print(string.format(" block %3d %5.2fs M %6.1f %6.1f spec %.3f", k, (k - 1) * 2048 / 44100, x, y, dot / math.sqrt(na * nb + 1e-20))) + end + end +end diff --git a/tests/music/zz_voices.luau b/tests/music/zz_voices.luau new file mode 100644 index 0000000..6a16e5b --- /dev/null +++ b/tests/music/zz_voices.luau @@ -0,0 +1,24 @@ +-- debug: voice states at a time +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/probe_cases") +local name, at = ... +local F = { s3m = require("@formats/music/s3m"), mod = require("@formats/music/mod") } +for _, c in Cases do + if c.name == name then + local m = F[c.fmt].decode(Bytes.reader(buffer.fromstring(c.data))) + local dec = m:render() + local n = math.floor(tonumber(at) * 44100) + while n > 0 do + local _, got = dec:read(math.min(n, 4096)) + n -= got + if got == 0 then break end + end + local st = dec.st + print("ord", st.ord, "row", st.row, "tick", st.tick, "speed", st.speed, "tempo", st.tempo, "gvol", st.gvol) + for i, v in st.voices do + if v.chan > 0 then print("voice", v.active, i, "chan", v.chan, "smp", v.smpIdx, "p", v.p, "inc", v.inc, "vol", v.vol, "g", v.gl, v.gr, "t", v.tl, v.tr, "len", v.len, v.loopS, v.loopE, v.loopT) end + end + local out = dec:read(8) + print(buffer.readf32(out, 0), buffer.readf32(out, 4), buffer.readf32(out, 8)) + end +end diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index d1c5609..482955d 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -1,14 +1,14 @@ # Tracker fixture helpers (used by tools/fixtures/{mod,s3m,xm,it}.py): small writers for MOD, S3M, XM and IT # (including IT 2.14 / 2.15 sample compression), synthesized samples, reference renders through openmpt123 (nix -# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 20 log-spaced band +# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 40 log-spaced band # magnitudes of the mid signal), computed the same way in tests/music/_similar.luau. Every module is generated here # (no third-party files), so the fixtures carry no licence. import json, math, os, struct, subprocess, tempfile SR = 44100 HOP = 2048 -BANDS = 20 -F_LO, F_HI = 100.0, 16000.0 +BANDS = 40 +F_LO, F_HI = 150.0, 16000.0 # ---------------------------------------------------------------------------------------------- samples diff --git a/tools/fixtures/s3m.py b/tools/fixtures/s3m.py new file mode 100644 index 0000000..17ea196 --- /dev/null +++ b/tools/fixtures/s3m.py @@ -0,0 +1,124 @@ +# S3M fixtures (tools/fixtures.py): generated Scream Tracker 3 modules exercising the effects, rendered by openmpt123. +# tests/gen/s3m_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + +A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27) + + +def empty(ch, rows=64): + return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, info=0): + p[row][ch] = (T.s3m_note(note) if 0 < note < 254 else note, ins, vol, cmd, info) + + +def samples(): + return [ + {"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "volume": 64, "c2spd": 8363, "loop": (0, 64)}, + {"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c2spd": 16726, "loop": (0, 64)}, + {"name": "saw", "data": T.u8(T.synth("saw", 100, 100, 0.6)), "volume": 64, "c2spd": 13000, "loop": (0, 100)}, + {"name": "noise", "data": T.u8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c2spd": 8363}, + {"name": "tri", "data": T.u8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c2spd": 10000, "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + """keep: debugging aid, a set of channels to keep (the others keep only their global effects)""" + a, b, c = empty(4), empty(4), empty(4) + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, None, J if i % 4 == 1 else 0, 0x47 if i % 4 == 1 else 0) + put(a, 0, 1, 49, 2, 48) + put(a, 4, 1, 0, 0, None, D, 0x04) + put(a, 8, 1, 0, 0, None, D, 0x20) + put(a, 12, 1, 0, 0, None, D, 0xF2) + put(a, 13, 1, 0, 0, None, D, 0x3F) + put(a, 14, 1, 0, 0, None, D, 0x00) + put(a, 16, 1, 51, 2, None, E, 0x03) + put(a, 20, 1, 0, 0, None, F, 0x06) + put(a, 24, 1, 0, 0, None, E, 0xF4) + put(a, 25, 1, 0, 0, None, F, 0xE8) + put(a, 28, 1, 56, 2, None, H, 0x46) + put(a, 32, 1, 0, 0, None, U, 0x48) + put(a, 36, 1, 0, 0, None, K, 0x02) + put(a, 40, 1, 49, 2, None, G, 0x00) + put(a, 41, 1, 61, 0, None, G, 0x10) + put(a, 44, 1, 0, 0, None, L, 0x01) + put(a, 48, 1, 54, 2, None, R, 0x58) + put(a, 52, 1, 0, 0, None, I, 0x21) + put(a, 56, 1, 0, 0, None, X, 0x20) + put(a, 60, 1, 0, 0, None, S, 0x8C) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 64 - r // 2) + put(a, 20, 3, 0, 0, None, O, 0x08) + put(a, 24, 3, 61, 4, None, Q, 0x83) + put(a, 32, 3, 61, 4, None, S, 0xC3) + put(a, 40, 3, 61, 4, None, S, 0xD2) + put(a, 48, 2, 37, 3, None, V, 0x30) + put(a, 56, 2, 0, 0, None, V, 0x40) + put(b, 0, 2, 49, 3, None, A, 0x04) + put(b, 4, 2, 0, 0, None, Tt, 0x90) + put(b, 8, 2, 52, 5, None, S, 0xB0) + put(b, 10, 0, 64, 1) + put(b, 12, 2, 0, 0, None, S, 0xB2) + put(b, 16, 2, 56, 5, None, S, 0xE2) + put(b, 20, 0, 61, 1, None, O, 0x00) + put(b, 24, 0, 254) + put(b, 28, 2, 0, 0, None, C, 0x08) + put(c, 8, 0, 49, 1, 32) + put(c, 12, 1, 61, 2, None, X, 0x80) + put(c, 16, 1, 0, 0, None, S, 0x82) + put(c, 20, 0, 0, 0, None, B, 0x05) + if keep is not None: # debugging: only some channels + for p in (a, b, c): + for row in p: + for ch in range(4): + if ch not in keep and row[ch][3] not in (A, B, C, Tt, V): + row[ch] = (0, 0, None, 0, 0) + return T.write_s3m("effects", samples(), [0, 1, 254, 2], [a, b, c], 4) + + +def song_memory(): + """ST3's shared effect memory, fast slides (ST3.00), the panning table, global volume, an order loop""" + a = empty(6) + put(a, 0, 0, 61, 1, None, D, 0x08) + put(a, 4, 0, 0, 0, None, E, 0x02) + put(a, 8, 0, 0, 0, None, D, 0x00) + put(a, 12, 0, 0, 0, None, F, 0x00) + put(a, 0, 1, 49, 3, None, D, 0x80) + put(a, 2, 1, 0, 0, None, D, 0x00) + put(a, 16, 2, 73, 5) + put(a, 20, 2, 0, 0, None, Q, 0x02) + put(a, 24, 2, 0, 0, None, Q, 0x00) + put(a, 28, 3, 56, 2, 20) + put(a, 28, 4, 63, 1, 30) + put(a, 32, 5, 37, 3, None, X, 0x00) + put(a, 40, 5, 0, 0, None, S, 0xE3) + put(a, 48, 0, 0, 0, None, V, 0x20) + put(a, 63, 0, 0, 0, None, B, 0x00) + return T.write_s3m("memory", samples(), [0], [a], 6, speed=5, tempo=140, cwt=0x1300, + pans=[2, 13, 5, 10, 7, 15], mvol=64 | 128, gvol=48) + + +def song_mono(): + a = empty(2) + put(a, 0, 0, 61, 1) + put(a, 8, 1, 68, 2) + put(a, 16, 0, 0, 0, None, H, 0x28) + put(a, 32, 1, 0, 0, None, F, 0x10) + return T.write_s3m("mono", samples(), [0], [a], 2, mvol=32) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("memory", song_memory()), ("mono", song_mono())): + ref = T.reference(ctx, data, "s3m") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("s3m_cases", cases) diff --git a/tools/fixtures/zz_probe.py b/tools/fixtures/zz_probe.py new file mode 100644 index 0000000..3598c71 --- /dev/null +++ b/tools/fixtures/zz_probe.py @@ -0,0 +1,62 @@ +# debug only (not committed): one small module per effect, for locating engine differences against openmpt +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa +import s3m as S # noqa + +def probes_s3m(): + out = [] + smp = S.samples() + def one(nm, events, ch=1, **kw): + p = S.empty(ch, 64) + for e in events: + S.put(p, *e) + out.append((nm, T.write_s3m(nm, smp, [0], [p], ch, **kw), "s3m")) + one("Q83", [(0, 0, 61, 4, None, S.Q, 0x83), (1, 0, 0, 0, None, S.Q, 0x83), (2, 0, 61, 4, None, S.Q, 0x83)]) + one("Q32", [(0, 0, 61, 4, None, S.Q, 0x32), (1, 0, 0, 0, None, S.Q, 0x00)]) + one("EF4", [(0, 0, 61, 2), (2, 0, 0, 0, None, S.E, 0xF4), (3, 0, 0, 0, None, S.F, 0xE8)]) + one("E03", [(0, 0, 61, 2), (2, 0, 0, 0, None, S.E, 0x03), (4, 0, 0, 0, None, S.F, 0x06)]) + one("D", [(0, 0, 61, 2, 48), (1, 0, 0, 0, None, S.D, 0x04), (3, 0, 0, 0, None, S.D, 0x20), (5, 0, 0, 0, None, S.D, 0xF2), (6, 0, 0, 0, None, S.D, 0x3F), (7, 0, 0, 0, None, S.D, 0x00)]) + one("H46", [(0, 0, 61, 1, None, S.H, 0x46), (1, 0, 0, 0, None, S.H, 0x00)]) + one("U48", [(0, 0, 61, 1, None, S.U, 0x48), (1, 0, 0, 0, None, S.U, 0x00)]) + one("K02", [(0, 0, 61, 1, None, S.H, 0x46), (1, 0, 0, 0, None, S.K, 0x02)]) + one("G", [(0, 0, 49, 1), (1, 0, 61, 0, None, S.G, 0x10), (3, 0, 49, 0, None, S.G, 0x00)]) + one("L01", [(0, 0, 49, 1), (1, 0, 61, 0, None, S.G, 0x08), (3, 0, 0, 0, None, S.L, 0x01)]) + one("R58", [(0, 0, 54, 1, None, S.R, 0x58), (1, 0, 0, 0, None, S.R, 0x00)]) + one("I21", [(0, 0, 54, 1, None, S.I, 0x21), (1, 0, 0, 0, None, S.I, 0x00)]) + one("J47", [(0, 0, 54, 1, None, S.J, 0x47), (1, 0, 0, 0, None, S.J, 0x00)]) + one("X", [(0, 0, 54, 1, None, S.X, 0x20), (4, 0, 0, 0, None, S.S, 0x8C), (8, 0, 0, 0, None, S.X, 0x80)]) + one("O", [(0, 0, 61, 4, None, S.O, 0x08), (4, 0, 61, 4, None, S.O, 0x00), (8, 0, 61, 4, None, S.O, 0x10)]) + one("SC", [(0, 0, 61, 4, None, S.S, 0xC3), (4, 0, 61, 1, None, S.S, 0xD2), (8, 0, 254)]) + one("V", [(0, 0, 61, 1, None, S.V, 0x30), (4, 0, 0, 0, None, S.V, 0x10)]) + one("T", [(0, 0, 61, 1, None, S.Tt, 0x90), (4, 0, 0, 0, None, S.A, 0x03)]) + one("SD2", [(0, 0, 61, 4), (8, 0, 61, 4, None, S.S, 0xD2), (16, 0, 61, 4, None, S.S, 0xD7)]) + one("G00mem", [(0, 0, 56, 2, None, S.H, 0x46), (4, 0, 0, 0, None, S.K, 0x02), (8, 0, 49, 2, None, S.G, 0x00), (9, 0, 61, 0, None, S.G, 0x10)]) + one("Qnote", [(0, 0, 61, 4), (4, 0, 61, 4, None, S.Q, 0x83), (5, 0, 0, 0, None, S.Q, 0x00), (8, 0, 61, 4, 64)]) + one("Gnew", [(0, 0, 49, 2, None, S.G, 0x04), (4, 0, 61, 0, None, S.G, 0x00)]) + one("seqA", [(24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (48, 0, 61, 4, 40)]) + one("seqB", [(32, 0, 61, 4, None, S.S, 0xC3), (48, 0, 61, 4, 40)]) + one("seqC", [(24, 0, 61, 4, None, S.Q, 0x83), (48, 0, 61, 4, 40)]) + one("seqD", [(40, 0, 61, 4, None, S.S, 0xD2), (48, 0, 61, 4, 40)]) + base = [(r, 0, 61, 4, 64 - r // 2) for r in range(0, 64, 8)] + one("b1", base) + one("b2", base + [(20, 0, 0, 0, None, S.O, 0x08)]) + ev = base + [(20, 0, 0, 0, None, S.O, 0x08), (24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (40, 0, 61, 4, None, S.S, 0xD2)] + one("b3", ev) + one("b4", base + [(24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (40, 0, 61, 4, None, S.S, 0xD2)]) + one("v1", base + [(48, 1, 0, 0, None, S.V, 0x30), (56, 1, 0, 0, None, S.V, 0x40)], ch=2) + one("v2", [(e[0], 1) + e[2:] for e in base] + [(48, 0, 0, 0, None, S.V, 0x30), (56, 0, 0, 0, None, S.V, 0x40)], ch=2) + ev4 = [(e[0], 3) + e[2:] for e in base + [(24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (40, 0, 61, 4, None, S.S, 0xD2)]] + one("c1", ev4, ch=4) + one("c2", ev4 + [(48, 2, 0, 0, None, S.V, 0x30)], ch=4) + for keep in ((3,),): + out.append(("eff" + "".join(map(str, keep)), S.song_effects(set(keep)), "s3m")) + return out + +def generate(ctx): + which = os.environ.get("PROBE", "s3m") + cases = [] + for nm, data, ext in {"s3m": probes_s3m}[which](): + ref = T.reference(ctx, data, ext) + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"], "fmt": ext}) + ctx.emit("probe_cases", cases) From 6c49ab38dd09add2ad3edb5a661dd78d34258b15 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:00:08 -0500 Subject: [PATCH 13/28] ws-music: untrack debug probes --- tests/music/zz_probe.luau | 27 ----------------- tests/music/zz_voices.luau | 24 --------------- tools/fixtures/zz_probe.py | 62 -------------------------------------- 3 files changed, 113 deletions(-) delete mode 100644 tests/music/zz_probe.luau delete mode 100644 tests/music/zz_voices.luau delete mode 100644 tools/fixtures/zz_probe.py diff --git a/tests/music/zz_probe.luau b/tests/music/zz_probe.luau deleted file mode 100644 index 53cd319..0000000 --- a/tests/music/zz_probe.luau +++ /dev/null @@ -1,27 +0,0 @@ --- debug probes -local S = require("@tests/music/_similar") -local Bytes = require("@formats/core/Bytes") -local Cases = require("@tests/gen/probe_cases") -local verbose = ... -local F = { s3m = require("@formats/music/s3m"), mod = require("@formats/music/mod") } -for _, c in Cases do - local m, err = F[c.fmt].decode(Bytes.reader(buffer.fromstring(c.data))) - if not m then print(c.name, err) continue end - local dec = m:render() - local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) - local a = S.features(buf, frames) - local r = S.compare(a, c.ref) - print(string.format("%-8s gain %+.2f err %.2f env %.3f spec %.3f bal %.3f dur %.3f/%.3f", c.name, r.gainDb, r.envErr, r.envCorr, r.spectral, r.balance, dec.duration, c.duration)) - if verbose == c.name then - for k = 1, math.min(a.frames, c.ref.frames) do - local x, y = 20 * math.log10(a.rmsM[k] + 1e-6), 20 * math.log10(c.ref.rmsM[k] + 1e-6) - local sim = 0 - local dot, na, nb = 0, 0, 0 - for j = 1, 40 do - local p, q = a.bands[(k - 1) * 40 + j], c.ref.bands[(k - 1) * 40 + j] - dot += p * q; na += p * p; nb += q * q - end - print(string.format(" block %3d %5.2fs M %6.1f %6.1f spec %.3f", k, (k - 1) * 2048 / 44100, x, y, dot / math.sqrt(na * nb + 1e-20))) - end - end -end diff --git a/tests/music/zz_voices.luau b/tests/music/zz_voices.luau deleted file mode 100644 index 6a16e5b..0000000 --- a/tests/music/zz_voices.luau +++ /dev/null @@ -1,24 +0,0 @@ --- debug: voice states at a time -local Bytes = require("@formats/core/Bytes") -local Cases = require("@tests/gen/probe_cases") -local name, at = ... -local F = { s3m = require("@formats/music/s3m"), mod = require("@formats/music/mod") } -for _, c in Cases do - if c.name == name then - local m = F[c.fmt].decode(Bytes.reader(buffer.fromstring(c.data))) - local dec = m:render() - local n = math.floor(tonumber(at) * 44100) - while n > 0 do - local _, got = dec:read(math.min(n, 4096)) - n -= got - if got == 0 then break end - end - local st = dec.st - print("ord", st.ord, "row", st.row, "tick", st.tick, "speed", st.speed, "tempo", st.tempo, "gvol", st.gvol) - for i, v in st.voices do - if v.chan > 0 then print("voice", v.active, i, "chan", v.chan, "smp", v.smpIdx, "p", v.p, "inc", v.inc, "vol", v.vol, "g", v.gl, v.gr, "t", v.tl, v.tr, "len", v.len, v.loopS, v.loopE, v.loopT) end - end - local out = dec:read(8) - print(buffer.readf32(out, 0), buffer.readf32(out, 4), buffer.readf32(out, 8)) - end -end diff --git a/tools/fixtures/zz_probe.py b/tools/fixtures/zz_probe.py deleted file mode 100644 index 3598c71..0000000 --- a/tools/fixtures/zz_probe.py +++ /dev/null @@ -1,62 +0,0 @@ -# debug only (not committed): one small module per effect, for locating engine differences against openmpt -import os, sys -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import _tracker as T # noqa -import s3m as S # noqa - -def probes_s3m(): - out = [] - smp = S.samples() - def one(nm, events, ch=1, **kw): - p = S.empty(ch, 64) - for e in events: - S.put(p, *e) - out.append((nm, T.write_s3m(nm, smp, [0], [p], ch, **kw), "s3m")) - one("Q83", [(0, 0, 61, 4, None, S.Q, 0x83), (1, 0, 0, 0, None, S.Q, 0x83), (2, 0, 61, 4, None, S.Q, 0x83)]) - one("Q32", [(0, 0, 61, 4, None, S.Q, 0x32), (1, 0, 0, 0, None, S.Q, 0x00)]) - one("EF4", [(0, 0, 61, 2), (2, 0, 0, 0, None, S.E, 0xF4), (3, 0, 0, 0, None, S.F, 0xE8)]) - one("E03", [(0, 0, 61, 2), (2, 0, 0, 0, None, S.E, 0x03), (4, 0, 0, 0, None, S.F, 0x06)]) - one("D", [(0, 0, 61, 2, 48), (1, 0, 0, 0, None, S.D, 0x04), (3, 0, 0, 0, None, S.D, 0x20), (5, 0, 0, 0, None, S.D, 0xF2), (6, 0, 0, 0, None, S.D, 0x3F), (7, 0, 0, 0, None, S.D, 0x00)]) - one("H46", [(0, 0, 61, 1, None, S.H, 0x46), (1, 0, 0, 0, None, S.H, 0x00)]) - one("U48", [(0, 0, 61, 1, None, S.U, 0x48), (1, 0, 0, 0, None, S.U, 0x00)]) - one("K02", [(0, 0, 61, 1, None, S.H, 0x46), (1, 0, 0, 0, None, S.K, 0x02)]) - one("G", [(0, 0, 49, 1), (1, 0, 61, 0, None, S.G, 0x10), (3, 0, 49, 0, None, S.G, 0x00)]) - one("L01", [(0, 0, 49, 1), (1, 0, 61, 0, None, S.G, 0x08), (3, 0, 0, 0, None, S.L, 0x01)]) - one("R58", [(0, 0, 54, 1, None, S.R, 0x58), (1, 0, 0, 0, None, S.R, 0x00)]) - one("I21", [(0, 0, 54, 1, None, S.I, 0x21), (1, 0, 0, 0, None, S.I, 0x00)]) - one("J47", [(0, 0, 54, 1, None, S.J, 0x47), (1, 0, 0, 0, None, S.J, 0x00)]) - one("X", [(0, 0, 54, 1, None, S.X, 0x20), (4, 0, 0, 0, None, S.S, 0x8C), (8, 0, 0, 0, None, S.X, 0x80)]) - one("O", [(0, 0, 61, 4, None, S.O, 0x08), (4, 0, 61, 4, None, S.O, 0x00), (8, 0, 61, 4, None, S.O, 0x10)]) - one("SC", [(0, 0, 61, 4, None, S.S, 0xC3), (4, 0, 61, 1, None, S.S, 0xD2), (8, 0, 254)]) - one("V", [(0, 0, 61, 1, None, S.V, 0x30), (4, 0, 0, 0, None, S.V, 0x10)]) - one("T", [(0, 0, 61, 1, None, S.Tt, 0x90), (4, 0, 0, 0, None, S.A, 0x03)]) - one("SD2", [(0, 0, 61, 4), (8, 0, 61, 4, None, S.S, 0xD2), (16, 0, 61, 4, None, S.S, 0xD7)]) - one("G00mem", [(0, 0, 56, 2, None, S.H, 0x46), (4, 0, 0, 0, None, S.K, 0x02), (8, 0, 49, 2, None, S.G, 0x00), (9, 0, 61, 0, None, S.G, 0x10)]) - one("Qnote", [(0, 0, 61, 4), (4, 0, 61, 4, None, S.Q, 0x83), (5, 0, 0, 0, None, S.Q, 0x00), (8, 0, 61, 4, 64)]) - one("Gnew", [(0, 0, 49, 2, None, S.G, 0x04), (4, 0, 61, 0, None, S.G, 0x00)]) - one("seqA", [(24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (48, 0, 61, 4, 40)]) - one("seqB", [(32, 0, 61, 4, None, S.S, 0xC3), (48, 0, 61, 4, 40)]) - one("seqC", [(24, 0, 61, 4, None, S.Q, 0x83), (48, 0, 61, 4, 40)]) - one("seqD", [(40, 0, 61, 4, None, S.S, 0xD2), (48, 0, 61, 4, 40)]) - base = [(r, 0, 61, 4, 64 - r // 2) for r in range(0, 64, 8)] - one("b1", base) - one("b2", base + [(20, 0, 0, 0, None, S.O, 0x08)]) - ev = base + [(20, 0, 0, 0, None, S.O, 0x08), (24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (40, 0, 61, 4, None, S.S, 0xD2)] - one("b3", ev) - one("b4", base + [(24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (40, 0, 61, 4, None, S.S, 0xD2)]) - one("v1", base + [(48, 1, 0, 0, None, S.V, 0x30), (56, 1, 0, 0, None, S.V, 0x40)], ch=2) - one("v2", [(e[0], 1) + e[2:] for e in base] + [(48, 0, 0, 0, None, S.V, 0x30), (56, 0, 0, 0, None, S.V, 0x40)], ch=2) - ev4 = [(e[0], 3) + e[2:] for e in base + [(24, 0, 61, 4, None, S.Q, 0x83), (32, 0, 61, 4, None, S.S, 0xC3), (40, 0, 61, 4, None, S.S, 0xD2)]] - one("c1", ev4, ch=4) - one("c2", ev4 + [(48, 2, 0, 0, None, S.V, 0x30)], ch=4) - for keep in ((3,),): - out.append(("eff" + "".join(map(str, keep)), S.song_effects(set(keep)), "s3m")) - return out - -def generate(ctx): - which = os.environ.get("PROBE", "s3m") - cases = [] - for nm, data, ext in {"s3m": probes_s3m}[which](): - ref = T.reference(ctx, data, ext) - cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"], "fmt": ext}) - ctx.emit("probe_cases", cases) From 83d43f6c6d97f5064f6ffba77a798e9145653896 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:03:04 -0500 Subject: [PATCH 14/28] 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 15/28] 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 c74c93ae118a1c58ab0478c1e5bacdaeb10477a8 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:04:31 -0500 Subject: [PATCH 16/28] ws-audio: FLAC encoder (audio/flac/Encode: levels 0-8 like libFLAC presets, fixed + LPC + Rice/Rice2 partition search, wasted bits, stereo decorrelation, MD5, VORBIS_COMMENT, SEEKTABLE, padding; streams from a Decoder) wired into audio/flac encode; core/Md5 (new core module, RFC 1321) + test; fixtures: flac -t + MD5 bit-exact on 76 encodes, sizes within 1.1% of libFLAC; bench lines --- docs/FORMATS.md | 2 +- src/Formats/Registry.luau | 4 +- src/Formats/audio/flac/Encode.luau | 1038 ++++++++++++++++++++++++++++ src/Formats/audio/flac/init.luau | 62 +- src/Formats/core/Md5.luau | 164 +++++ tests/audio/flac_encode.luau | 109 +++ tests/core/md5.luau | 30 + tools/bench.luau | 19 + tools/fixtures/_audio.py | 42 ++ tools/fixtures/flac_enc.py | 89 +++ 10 files changed, 1553 insertions(+), 6 deletions(-) create mode 100644 src/Formats/audio/flac/Encode.luau create mode 100644 src/Formats/core/Md5.luau create mode 100644 tests/audio/flac_encode.luau create mode 100644 tests/core/md5.luau create mode 100644 tools/fixtures/flac_enc.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index edcb10f..b57f8d9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -9,7 +9,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | | audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.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 | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.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 | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 941a69b..cbdfa37 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -68,8 +68,8 @@ local list: { Entry } = { path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return require("@formats/audio/flac") end, diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau new file mode 100644 index 0000000..499f4c0 --- /dev/null +++ b/src/Formats/audio/flac/Encode.luau @@ -0,0 +1,1038 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8 +-- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive / +-- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum), +-- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with +-- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted +-- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 / +-- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional +-- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it +-- whole. Never throws: bad options are rejected by audio/flac before calling in. +local Md5 = require("@formats/core/Md5") + +local Encode = {} + +local floor, abs, log = math.floor, math.abs, math.log +local readf32, writeu8 = buffer.readf32, buffer.writeu8 + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ CRCs +local CRC8 = table.create(256, 0) +local CRC16 = table.create(256, 0) +for i = 0, 255 do + local c = i + for _ = 1, 8 do + c = if c >= 128 then bit32.bxor((c * 2) % 256, 0x07) else c * 2 + end + CRC8[i + 1] = c + local d = i * 256 + for _ = 1, 8 do + d = if d >= 32768 then bit32.bxor((d * 2) % 65536, 0x8005) else d * 2 + end + CRC16[i + 1] = d +end +local function crc8(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = CRC8[bit32.bxor(c, buffer.readu8(b, i)) + 1] + end + return c +end +local function crc16(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor((c * 256) % 65536, CRC16[bit32.bxor(c // 256, buffer.readu8(b, i)) + 1]) + end + return c +end +Encode.crc8, Encode.crc16 = crc8, crc16 + +-- ------------------------------------------------------------------------------------------------ bit writer (MSB first) +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function ensure(w: W, n: number) + local need = w.pos + n + 16 + local cap = buffer.len(w.buf) + if need > cap then + local nb = buffer.create(math.max(cap * 2, need)) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end +end + +-- put(w, v, n): the low n bits (n <= 32) of the non-negative integer v +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +local function putSigned(w: W, v: number, n: number) + put(w, if v < 0 then v + POW[n + 1] else v, n) +end + +local function alignByte(w: W) + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end +end + +local function putUtf8(w: W, v: number) + if v < 0x80 then + put(w, v, 8) + return + end + local n = if v < 0x800 then 2 elseif v < 0x10000 then 3 elseif v < 0x200000 then 4 elseif v < 0x4000000 then 5 elseif v < 0x80000000 then 6 else 7 + local first = if n == 7 then 0xFE else (0xFF00 // POW[n + 1]) % 256 -- n leading ones + local shift = 6 * (n - 1) + put(w, first + floor(v / POW[shift + 1]), 8) + for k = n - 2, 0, -1 do + put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) + end +end + +-- ------------------------------------------------------------------------------------------------ presets +export type Config = { + blockSize: number, + maxLpcOrder: number, + maxPartitionOrder: number, + stereo: string, -- "independent" | "adaptive" | "exhaustive" + exhaustiveOrder: boolean, +} +local PRESETS: { Config } = { + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, +} +Encode.PRESETS = PRESETS + +-- ------------------------------------------------------------------------------------------------ analysis +-- a subframe plan for one channel signal +type Plan = { + kind: number, -- 0 constant, 1 verbatim, 2 fixed, 3 lpc + bits: number, -- estimated size in bits (with the subframe header) + order: number, + wasted: number, + bps: number, -- sample size after removing wasted bits + res: { number }, -- residual (fixed / lpc), indices 1..n + porder: number, + params: { number }, + method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit) + qlp: { number }, + shift: number, + precision: number, + x: { number }, -- the (shifted) samples +} + +local function newPlan(n: number): Plan + return { + kind = 1, + bits = 0, + order = 0, + wasted = 0, + bps = 16, + res = table.create(n, 0), + porder = 0, + params = table.create(64, 0), + method = 0, + qlp = table.create(32, 0), + shift = 0, + precision = 0, + x = table.create(n, 0), + } +end + +-- scratch per encoder +type Scratch = { + sums: { number }, + counts: { number }, + ks: { number }, + bestKs: { number }, + tmpRes: { number }, + win: { number }, + winN: number, + wx: { number }, + autoc: { number }, + lpc: { { number } }, + err: { number }, + qlp: { number }, +} + +-- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters) +local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) + -- the finest usable partition order + local p = maxP + while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do + p -= 1 + end + local sums, counts = sc.sums, sc.counts + local parts = POW[p + 1] + local ps = n // parts + -- sums of zig-zag values at the finest order + for j = 0, parts - 1 do + local s = 0 + local a = if j == 0 then order + 1 else j * ps + 1 + local e = (j + 1) * ps + for i = a, e do + local r = res[i] + s += if r >= 0 then 2 * r else -2 * r - 1 + end + sums[j + 1] = s + counts[j + 1] = e - a + 1 + end + local bestBits, bestP, bestMethod = math.huge, 0, 0 + local ks, bestKs = sc.ks, sc.bestKs + local q = p + while true do + local np = POW[q + 1] + local total = 0 + local maxk = 0 + for j = 1, np do + local s, c = sums[j], counts[j] + local k = 0 + local cost = s + c -- k = 0: unary s, plus one stop bit per sample + if c > 0 and s > c then + local k0 = floor(log(s / c) / 0.6931471805599453) + for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do + local cc = c * (kk + 1) + floor(s / POW[kk + 1]) + if cc < cost then + cost, k = cc, kk + end + end + end + ks[j] = k + if k > maxk then + maxk = k + end + total += cost + end + local method = if maxk > 14 then 1 else 0 + total += np * (if method == 1 then 5 else 4) + 2 + 4 + if total < bestBits then + bestBits, bestP, bestMethod = total, q, method + for j = 1, np do + bestKs[j] = ks[j] + end + end + if q == 0 then + break + end + -- merge pairs into the next coarser order + for j = 1, np // 2 do + sums[j] = sums[2 * j - 1] + sums[2 * j] + counts[j] = counts[2 * j - 1] + counts[2 * j] + end + q -= 1 + end + return bestBits, bestP, bestMethod +end + +local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) + plan.porder, plan.method = porder, method + local params = plan.params + for j = 1, POW[porder + 1] do + params[j] = sc.bestKs[j] + end +end + +-- fixed predictor residuals +local function fixedResidual(x: { number }, n: number, order: number, res: { number }) + for i = 1, order do + res[i] = 0 + end + if order == 0 then + for i = 1, n do + res[i] = x[i] + end + elseif order == 1 then + for i = 2, n do + res[i] = x[i] - x[i - 1] + end + elseif order == 2 then + for i = 3, n do + res[i] = x[i] - 2 * x[i - 1] + x[i - 2] + end + elseif order == 3 then + for i = 4, n do + res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3] + end + else + for i = 5, n do + res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4] + end + end +end + +-- the fixed order with the smallest residual magnitude (libFLAC's estimate) +local function bestFixedOrder(x: { number }, n: number): (number, number) + if n <= 4 then + return 0, 0 + end + local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0 + local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1] + for i = 5, n do + local e0 = x[i] + local e1 = e0 - a + local e2 = e1 - b + local e3 = e2 - c + local e4 = e3 - d + s0 += abs(e0) + s1 += abs(e1) + s2 += abs(e2) + s3 += abs(e3) + s4 += abs(e4) + a, b, c, d = e0, e1, e2, e3 + end + local best, bs = 0, s0 + if s1 < bs then + best, bs = 1, s1 + end + if s2 < bs then + best, bs = 2, s2 + end + if s3 < bs then + best, bs = 3, s3 + end + if s4 < bs then + best, bs = 4, s4 + end + return best, bs +end +Encode.bestFixedOrder = bestFixedOrder + +-- libFLAC's default QLP coefficient precision for a block size +local function qlpPrecision(bps: number, n: number): number + if bps > 16 then + return 15 + end + if n <= 192 then + return 7 + elseif n <= 384 then + return 8 + elseif n <= 576 then + return 9 + elseif n <= 1152 then + return 10 + elseif n <= 2304 then + return 11 + elseif n <= 4608 then + return 12 + end + return 13 +end + +-- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil +local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? + local cmax = 0 + for i = 1, order do + local a = abs(lp[i]) + if a > cmax then + cmax = a + end + end + if cmax <= 0 or cmax ~= cmax or cmax == math.huge then + return nil + end + local log2cmax = 0 + while cmax >= 1 do + cmax /= 2 + log2cmax += 1 + end + while cmax < 0.5 do + cmax *= 2 + log2cmax -= 1 + end + -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) + log2cmax -= 1 + local p = precision - 1 + local qmax = POW[p + 1] - 1 + local qmin = -POW[p + 1] + local shift = p - log2cmax - 1 + if shift > 15 then + shift = 15 + elseif shift < 0 then + return nil + end + local err = 0 + local scale = POW[shift + 1] + for i = 1, order do + err += lp[i] * scale + local q = floor(err + 0.5) + if q > qmax then + q = qmax + elseif q < qmin then + q = qmin + end + err -= q + qlp[i] = q + end + return shift +end + +local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) + local d = POW[shift + 1] + for i = 1, order do + res[i] = 0 + end + for i = order + 1, n do + local s = 0 + for j = 1, order do + s += qlp[j] * x[i - j] + end + res[i] = x[i] - floor(s / d) + end +end + +-- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order +local function levinson(sc: Scratch, maxOrder: number): number + local r = sc.autoc + local e = r[1] + if e <= 0 then + return 0 + end + local a = table.create(maxOrder + 1, 0) + local tmp = table.create(maxOrder + 1, 0) + for o = 1, maxOrder do + local acc = r[o + 1] + for j = 1, o - 1 do + acc -= a[j] * r[o - j + 1] + end + local k = acc / e + for j = 1, o - 1 do + tmp[j] = a[j] - k * a[o - j] + end + for j = 1, o - 1 do + a[j] = tmp[j] + end + a[o] = k + e *= (1 - k * k) + local row = sc.lpc[o] + for j = 1, o do + row[j] = a[j] + end + sc.err[o] = e + if e <= 0 then + return o + end + end + return maxOrder +end + +-- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays) +local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) + local x = plan.x + -- constant? + local first = src[1] + local constant = true + for i = 1, n do + local v = src[i] + if v ~= first then + constant = false + end + end + if constant then + plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps + plan.res[1] = first + return + end + -- wasted bits: the common trailing zeros + local wasted = 0 + do + local w = 0 + while w < bps - 1 do + local m = POW[w + 2] + local all = true + for i = 1, n do + if src[i] % m ~= 0 then + all = false + break + end + end + if not all then + break + end + w += 1 + end + wasted = w + end + local d = POW[wasted + 1] + for i = 1, n do + x[i] = src[i] / d + end + local b = bps - wasted + local hdr = 8 + wasted + plan.wasted, plan.bps = wasted, b + -- verbatim + plan.kind, plan.bits = 1, hdr + n * b + -- fixed + local fo = bestFixedOrder(x, n) + if n > fo then + local tmp = sc.tmpRes + fixedResidual(x, n, fo, tmp) + local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder) + local bits = hdr + fo * b + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 2, bits, fo + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + -- lpc + local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) + if maxOrder > 0 then + -- windowed autocorrelation + local win = sc.win + if sc.winN ~= n then + -- tukey(0.5) + local np = floor(0.25 * n) + for i = 1, n do + win[i] = 1 + end + if np > 0 then + for i = 0, np - 1 do + local v = 0.5 - 0.5 * math.cos(math.pi * i / np) + win[i + 1] = v + win[n - i] = v + end + end + sc.winN = n + end + local wx = sc.wx + for i = 1, n do + wx[i] = x[i] * win[i] + end + local ac = sc.autoc + for lag = 0, maxOrder do + local s = 0 + for i = lag + 1, n do + s += wx[i] * wx[i - lag] + end + ac[lag + 1] = s + end + local top = levinson(sc, maxOrder) + if top > 0 then + local precision = qlpPrecision(b, n) + local orders = {} + if cfg.exhaustiveOrder then + for o = 1, top do + table.insert(orders, o) + end + else + -- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision + local bestO, bestE = 1, math.huge + for o = 1, top do + local e = sc.err[o] + local est = if e > 0 then (n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) else -math.huge + if est < bestE then + bestO, bestE = o, est + end + end + orders[1] = bestO + end + local qlp = sc.qlp + for _, o in orders do + local prec = precision + local shift = quantize(sc.lpc[o], o, prec, qlp) + if shift then + local tmp = sc.tmpRes + lpcResidual(x, n, o, qlp, shift, tmp) + local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder) + local bits = hdr + o * b + 4 + 5 + o * prec + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 3, bits, o + plan.shift, plan.precision = shift, prec + for j = 1, o do + plan.qlp[j] = qlp[j] + end + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ writing +local function writeResidual(w: W, plan: Plan, n: number) + local method = plan.method + put(w, method, 2) + local porder = plan.porder + put(w, porder, 4) + local parts = POW[porder + 1] + local ps = n // parts + local res = plan.res + local pbits = if method == 1 then 5 else 4 + for j = 0, parts - 1 do + local k = plan.params[j + 1] + put(w, k, pbits) + local a = if j == 0 then plan.order + 1 else j * ps + 1 + local e = (j + 1) * ps + local mk = POW[k + 1] + for i = a, e do + local r = res[i] + local u = if r >= 0 then 2 * r else -2 * r - 1 + local hi = floor(u / mk) + local lo = u - hi * mk + if hi + 1 + k <= 32 then + put(w, mk + lo, hi + 1 + k) + else + local q = hi + while q > 24 do + put(w, 0, 24) + q -= 24 + end + put(w, 1, q + 1) + put(w, lo, k) + end + end + end +end + +local function writeSubframe(w: W, plan: Plan, n: number) + local kind = plan.kind + local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1 + put(w, 0, 1) + put(w, typ, 6) + if kind ~= 0 and plan.wasted > 0 then + put(w, 1, 1) + put(w, 1, plan.wasted) -- k - 1 zeros, then a one + else + put(w, 0, 1) + end + local b = plan.bps + if kind == 0 then + putSigned(w, plan.res[1], b) + return + end + local x = plan.x + if kind == 1 then + for i = 1, n do + putSigned(w, x[i], b) + end + return + end + for i = 1, plan.order do + putSigned(w, x[i], b) + end + if kind == 3 then + put(w, plan.precision - 1, 4) + put(w, plan.shift, 5) + for j = 1, plan.order do + putSigned(w, plan.qlp[j], plan.precision) + end + end + writeResidual(w, plan, n) +end + +local RATE_CODES: { [number]: number } = { + [88200] = 1, + [176400] = 2, + [192000] = 3, + [8000] = 4, + [16000] = 5, + [22050] = 6, + [24000] = 7, + [32000] = 8, + [44100] = 9, + [48000] = 10, + [96000] = 11, +} +local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } + +local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) + if n == 192 then + return 1, 0 + end + for k = 2, 5 do + if n == 576 * POW[k - 1] then + return k, 0 + end + end + for k = 8, 15 do + if n == 256 * POW[k - 7] then + return k, 0 + end + end + if n <= 256 then + return 6, 8 + end + return 7, 16 +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + level: number, + bits: number, + blockSize: number?, + seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE) + padding: number, -- bytes of PADDING + vendor: string, +} + +local TAG_NAMES = { track = "TRACKNUMBER" } + +-- encode(src, opts) -> buffer | nil, message +function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local cfg = PRESETS[opts.level + 1] + local ch, rate, bps = src.channels, src.sampleRate, opts.bits + local bs = opts.blockSize or cfg.blockSize + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + -- metadata + put(w, 0x664C6143, 32) -- "fLaC" + put(w, 0, 1) + put(w, 0, 7) + put(w, 34, 24) + local siData = w.pos + for _ = 1, 34 do + put(w, 0, 8) + end + -- seek table placeholders (when the length is known) + local seekPoints = 0 + local seekAt = 0 + local interval = floor(opts.seekInterval * rate) + if interval > 0 and src.frames > 0 then + seekPoints = (src.frames - 1) // interval + 1 + if seekPoints > 65535 // 18 * 18 then + seekPoints = 0 + end + end + -- vorbis comment + local comments = {} + local keys = {} + for k in src.tags do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + local v = src.tags[k] + if type(v) == "string" then + table.insert(comments, (TAG_NAMES[k] or string.upper(k)) .. "=" .. v) + end + end + local vendor = opts.vendor + local vcLen = 4 + #vendor + 4 + for _, c in comments do + vcLen += 4 + #c + end + -- SEEKTABLE + if seekPoints > 0 then + put(w, 0, 1) + put(w, 3, 7) + put(w, seekPoints * 18, 24) + seekAt = w.pos + ensure(w, seekPoints * 18) + for _ = 1, seekPoints do + put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it + put(w, 0xFFFFFFFF, 32) + put(w, 0, 32) -- byte offset + put(w, 0, 32) + put(w, 0, 16) -- frame samples + end + end + -- VORBIS_COMMENT (little-endian lengths) + local function le32(v: number) + put(w, v % 256, 8) + put(w, (v // 256) % 256, 8) + put(w, (v // 65536) % 256, 8) + put(w, v // 16777216, 8) + end + ensure(w, vcLen + 8) + put(w, if opts.padding > 0 then 0 else 1, 1) -- the last metadata block unless PADDING follows + put(w, 4, 7) + put(w, vcLen, 24) + le32(#vendor) + for i = 1, #vendor do + put(w, string.byte(vendor, i), 8) + end + le32(#comments) + for _, c in comments do + ensure(w, #c + 8) + le32(#c) + for i = 1, #c do + put(w, string.byte(c, i), 8) + end + end + if opts.padding > 0 then + ensure(w, opts.padding + 8) + put(w, 1, 1) + put(w, 1, 7) + put(w, opts.padding, 24) + for _ = 1, opts.padding do + put(w, 0, 8) + end + end + local audioStart = w.pos + -- frames + local md5 = Md5.new() + local mbytes = (bps + 7) // 8 + local mbuf = buffer.create(bs * ch * mbytes) + local scale = POW[bps] + local maxv, minv = scale - 1, -scale + local X = table.create(ch) + for c = 1, ch do + X[c] = table.create(bs, 0) + end + local side = table.create(bs, 0) + local mid = table.create(bs, 0) + local plans = {} + for i = 1, 4 do + plans[i] = newPlan(bs) + end + for c = 1, ch do + plans[4 + c] = newPlan(bs) + end + local lpcRows = {} + for o = 1, 32 do + lpcRows[o] = table.create(o, 0) + end + local sc: Scratch = { + sums = table.create(64, 0), + counts = table.create(64, 0), + ks = table.create(64, 0), + bestKs = table.create(64, 0), + tmpRes = table.create(bs, 0), + win = table.create(bs, 0), + winN = 0, + wx = table.create(bs, 0), + autoc = table.create(33, 0), + lpc = lpcRows, + err = table.create(32, 0), + qlp = table.create(32, 0), + } + local frameNo = 0 + local total = 0 + local minFrame, maxFrame = math.huge, 0 + local seekNext = 0 + local seekIdx = 0 + local rateCode = RATE_CODES[rate] or 0 + local sizeCode = SIZE_CODES[bps] or 0 + local tmp: buffer? = nil + local pendingBuf: buffer? = nil + local pendingN, pendingOff = 0, 0 + -- read exactly bs frames (fewer only at the end) + local function readBlock(): (buffer?, number) + local out = buffer.create(bs * ch * 4) + local got = 0 + while got < bs do + if pendingN == 0 then + local b, n = src:read(math.max(bs, 4096), tmp) + if n <= 0 then + break + end + tmp = b + pendingBuf, pendingN, pendingOff = b, n, 0 + end + local take = math.min(bs - got, pendingN) + buffer.copy(out, got * ch * 4, pendingBuf :: buffer, pendingOff * ch * 4, take * ch * 4) + got += take + pendingN -= take + pendingOff += take + end + return out, got + end + while true do + local fb, n = readBlock() + if n <= 0 or fb == nil then + break + end + -- to integers (+ the MD5 bytes, signed little endian) + local mo = 0 + for i = 0, n - 1 do + for c = 1, ch do + local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5) + if v ~= v then + v = 0 + elseif v > maxv then + v = maxv + elseif v < minv then + v = minv + end + X[c][i + 1] = v + local u = if v < 0 then v + 4294967296 else v + for k = 0, mbytes - 1 do + writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) + mo += 1 + end + end + end + md5:update(mbuf, 0, mo) + -- channel decorrelation + local assign = ch - 1 + local chosen: { Plan } = {} + if ch == 2 and cfg.stereo ~= "independent" then + local L, R = X[1], X[2] + for i = 1, n do + local l, r = L[i], R[i] + side[i] = l - r + mid[i] = floor((l + r) / 2) + end + local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4] + if cfg.stereo == "adaptive" then + local _, el = bestFixedOrder(L, n) + local _, er = bestFixedOrder(R, n) + local _, em = bestFixedOrder(mid, n) + local _, es = bestFixedOrder(side, n) + -- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real + local best = math.min(el + es, er + es, em + es) + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + chosen, assign = { pl, pr }, 1 + if best < el + er then + analyze(sc, cfg, side, n, bps + 1, ps) + if best == em + es then + analyze(sc, cfg, mid, n, bps, pm) + if pm.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pm, ps }, 10 + end + elseif best == el + es then + if pl.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pl, ps }, 8 + end + elseif ps.bits + pr.bits < pl.bits + pr.bits then + chosen, assign = { ps, pr }, 9 + end + end + else + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + analyze(sc, cfg, mid, n, bps, pm) + analyze(sc, cfg, side, n, bps + 1, ps) + local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits + local best = math.min(lr, ls, rs, msb) + if best == lr then + chosen, assign = { pl, pr }, 1 + elseif best == msb then + chosen, assign = { pm, ps }, 10 + elseif best == ls then + chosen, assign = { pl, ps }, 8 + else + chosen, assign = { ps, pr }, 9 + end + end + else + for c = 1, ch do + analyze(sc, cfg, X[c], n, bps, plans[4 + c]) + chosen[c] = plans[4 + c] + end + end + -- the frame + local need = n * ch * 4 + 64 + for _, p in chosen do + need += (p.bits // 8) + 8 + end + ensure(w, need) + local start = w.pos + -- seek points: the first frame at or after each multiple of the interval + while seekIdx < seekPoints and total >= seekNext do + local at = seekAt + seekIdx * 18 + local sn, off = total, start - audioStart + local tb = w.buf + for k = 0, 7 do + writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256) + writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256) + end + writeu8(tb, at + 16, n // 256) + writeu8(tb, at + 17, n % 256) + seekIdx += 1 + seekNext = seekIdx * interval + end + put(w, 0x3FFE, 14) + put(w, 0, 1) + put(w, 0, 1) -- fixed block size + local bcode, bextra = blockCode(n) + put(w, bcode, 4) + put(w, rateCode, 4) + put(w, assign, 4) + put(w, sizeCode, 3) + put(w, 0, 1) + putUtf8(w, frameNo) + if bextra > 0 then + put(w, n - 1, bextra) + end + put(w, crc8(w.buf, start, w.pos - start), 8) + for _, p in chosen do + writeSubframe(w, p, n) + end + alignByte(w) + local c16 = crc16(w.buf, start, w.pos - start) + put(w, c16, 16) + local fsize = w.pos - start + if fsize < minFrame then + minFrame = fsize + end + if fsize > maxFrame then + maxFrame = fsize + end + frameNo += 1 + total += n + if n < bs then + break + end + end + if src.err then + return nil, tostring(src.err) + end + -- unused seek points stay placeholders; STREAMINFO + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest()) + buffer.copy(out, siData, si, 0, 34) + return out, nil +end + +-- streaminfo(...) -> the 34-byte STREAMINFO body +function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer + local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } + put(w, bs, 16) + put(w, bs, 16) + put(w, minFrame, 24) + put(w, maxFrame, 24) + put(w, rate, 20) + put(w, ch - 1, 3) + put(w, bps - 1, 5) + put(w, floor(total / 2 ^ 32), 4) + put(w, total % 2 ^ 32, 32) + for i = 1, 16 do + put(w, string.byte(md5, i), 8) + end + local out = buffer.create(34) + buffer.copy(out, 0, w.buf, 0, 34) + return out +end + +return Encode diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index bcf2578..88e5f22 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -5,7 +5,9 @@ -- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame -- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in -- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when --- STREAMINFO has none. Not supported: encoding (ws-audio), MD5 verification, chained Ogg streams. +-- STREAMINFO has none. Encode (audio/flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels +-- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5 +-- verification on decode, chained Ogg streams, Ogg FLAC output. -- -- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) -- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end @@ -18,6 +20,8 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Stream = require("@formats/audio/flac/Stream") +local Encode = require("@formats/audio/flac/Encode") +local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Flac = { @@ -25,8 +29,8 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } -- ------------------------------------------------------------------------------------------------ types @@ -35,6 +39,13 @@ export type OpenOptions = { crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) } +export type EncodeOptions = { + level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) + bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16) + blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) + seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) + padding: number?, -- bytes of PADDING after the metadata (default 0) +} -- ------------------------------------------------------------------------------------------------ sniff function Flac.sniff(r: Bytes.Reader): number @@ -108,6 +119,51 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err +function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local level = o.level or 5 + if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then + return nil, Err.new(Err.ARG, "level must be 0..8") + end + local bits = o.bits + if bits == nil then + local v = value :: any + local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample + bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16 + end + if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then + return nil, Err.new(Err.ARG, "bits must be 4..24") + end + local bs = o.blockSize + if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then + return nil, Err.new(Err.ARG, "blockSize must be 16..65535") + end + if src.channels > 8 then + return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20") + end + local out, msg = Encode.encode(src :: any, { + level = level, + bits = bits :: number, + blockSize = bs, + seekInterval = math.max(0, o.seekInterval or 10), + padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF), + vendor = "formats-luau", + }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + -- ------------------------------------------------------------------------------------------------ open -- open(r, opts?) -> Decoder | nil, Err function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) diff --git a/src/Formats/core/Md5.luau b/src/Formats/core/Md5.luau new file mode 100644 index 0000000..3ec4379 --- /dev/null +++ b/src/Formats/core/Md5.luau @@ -0,0 +1,164 @@ +--!strict +--!native +--!optimize 2 +-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); +-- not for security. +-- +-- local h = Md5.new() +-- h:update(buf, offset?, length?) -- any number of times +-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again) +-- Md5.hex(digest) / Md5.of(buf) -> hex string +-- Never throws (ranges are clamped to the buffer). +local Md5 = {} + +local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate +local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8 + +local K = table.create(64, 0) +for i = 0, 63 do + K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296 +end +local S = { + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +} +local G = table.create(64, 0) +for i = 0, 63 do + if i < 16 then + G[i + 1] = i + elseif i < 32 then + G[i + 1] = (5 * i + 1) % 16 + elseif i < 48 then + G[i + 1] = (3 * i + 5) % 16 + else + G[i + 1] = (7 * i) % 16 + end +end + +export type State = { + a: number, + b: number, + c: number, + d: number, + block: buffer, -- 64-byte pending block + fill: number, + total: number, -- bytes hashed + update: (self: State, buf: buffer, offset: number?, length: number?) -> (), + digest: (self: State) -> string, +} + +local M = table.create(16, 0) + +local function compress(st: State, blk: buffer, o: number) + for i = 0, 15 do + M[i + 1] = readu32(blk, o + i * 4) + end + local a, b, c, d = st.a, st.b, st.c, st.d + for i = 0, 63 do + local f + if i < 16 then + f = bor(band(b, c), band(bnot(b), d)) + elseif i < 32 then + f = bor(band(d, b), band(bnot(d), c)) + elseif i < 48 then + f = bxor(b, c, d) + else + f = bxor(c, bor(b, bnot(d))) + end + local tmp = d + d = c + c = b + b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296 + a = tmp + end + st.a = (st.a + a) % 4294967296 + st.b = (st.b + b) % 4294967296 + st.c = (st.c + c) % 4294967296 + st.d = (st.d + d) % 4294967296 +end + +local function update(self: State, buf: buffer, offset: number?, length: number?) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + local len = math.clamp(length or (n - o), 0, n - o) + self.total += len + local blk = self.block + if self.fill > 0 then + local take = math.min(64 - self.fill, len) + buffer.copy(blk, self.fill, buf, o, take) + self.fill += take + o += take + len -= take + if self.fill == 64 then + compress(self, blk, 0) + self.fill = 0 + end + end + while len >= 64 do + compress(self, buf, o) + o += 64 + len -= 64 + end + if len > 0 then + buffer.copy(blk, 0, buf, o, len) + self.fill = len + end +end + +local function digest(self: State): string + local bits = self.total * 8 + local blk = self.block + local f = self.fill + writeu8(blk, f, 0x80) + f += 1 + if f > 56 then + buffer.fill(blk, f, 0, 64 - f) + compress(self, blk, 0) + f = 0 + end + buffer.fill(blk, f, 0, 56 - f) + writeu32(blk, 56, bits % 4294967296) + writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296) + compress(self, blk, 0) + self.fill = 0 + local out = buffer.create(16) + writeu32(out, 0, self.a) + writeu32(out, 4, self.b) + writeu32(out, 8, self.c) + writeu32(out, 12, self.d) + return buffer.tostring(out) +end + +function Md5.new(): State + return { + a = 0x67452301, + b = 0xEFCDAB89, + c = 0x98BADCFE, + d = 0x10325476, + block = buffer.create(64), + fill = 0, + total = 0, + update = update, + digest = digest, + } +end + +-- hex(digest) -> 32 lower-case hex digits +function Md5.hex(d: string): string + local out = table.create(#d) + for i = 1, #d do + out[i] = string.format("%02x", string.byte(d, i)) + end + return table.concat(out) +end + +-- of(buf, offset?, length?) -> hex digest +function Md5.of(buf: buffer, offset: number?, length: number?): string + local h = Md5.new() + h:update(buf, offset, length) + return Md5.hex(h:digest()) +end + +return Md5 diff --git a/tests/audio/flac_encode.luau b/tests/audio/flac_encode.luau new file mode 100644 index 0000000..7a0f204 --- /dev/null +++ b/tests/audio/flac_encode.luau @@ -0,0 +1,109 @@ +-- audio/flac encoder tests: every fixture-step encode (levels 0-8, 1 / 2 / 6 channels, 8 / 12 / 16 / 20 / 24 bits, +-- odd lengths and block sizes, odd rates, seek tables, padding) passed `flac -t` and carries the MD5 of the quantized +-- input; sizes within 10% of libFLAC at the same level; each decodes bit-exactly through our own decoder; streaming +-- from a Decoder gives the same bytes; tags; option errors. Fixtures: tools/fixtures/flac_enc.py. +local T = require("@tests/T") +local Flac = require("@formats/audio/flac") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/flac_enc") +local Sigs = require("@tests/gen/flac_enc_sigs") + +local t = T.suite("flac_encode") + +local sigCache: { [string]: any } = {} +local function sig(name: string): Types.Audio + local s = sigCache[name] + if not s then + local m = Sigs[name] + s = Types.Audio.new(m.rate, m.channels, m.frames) + buffer.writestring(s.samples, 0, m.data) + sigCache[name] = s + end + return s +end + +t:check(Flac.caps.encode and Flac.encode ~= nil, "caps.encode") + +local worst = 0 +for _, e in Enc do + t:eq(e.flacTest, "", e.name .. ": flac -t") + t:eq(e.md5, e.wantMd5, e.name .. ": STREAMINFO MD5 = MD5 of the quantized input") + if e.refSize then + local ratio = e.size / e.refSize + worst = math.max(worst, ratio) + t:check(ratio < 1.1, string.format("%s: %d bytes, libFLAC %d (%.3f)", e.name, e.size, e.refSize, ratio)) + end + -- our decoder: bit-exact against the input quantized to e.bits + local a = sig(e.sig) + local back, err = Flac.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(back, e.name .. ": our decoder: " .. tostring(err)) + t:check(back.frames == a.frames and back.channels == a.channels and back.sampleRate == a.sampleRate, e.name .. ": format") + local s = 2 ^ (e.bits - 1) + local exact = true + for i = 0, a.frames * a.channels - 1 do + local want = math.clamp(math.floor(buffer.readf32(a.samples, i * 4) * s + 0.5), -s, s - 1) + if math.floor(buffer.readf32(back.samples, i * 4) * s + 0.5) ~= want then + exact = false + break + end + end + t:check(exact, e.name .. ": bit-exact round trip") + t:eq(back.meta.source.bitDepth, e.bits, e.name .. ": bits per sample") +end +t:note("%d encodes pass flac -t with the right MD5 and decode bit-exactly; worst size vs libFLAC %.3f", #Enc, worst) + +-- streaming: a Decoder source gives the same bytes as the Audio +do + local a = sig("flacsig_music_2_7000_44100") + local f1 = Flac.encode(a, { level = 5 }) :: buffer + local f2 = Flac.encode(Pcm.audioDecoder(a), { level = 5 }) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + -- a decoder of our own output re-encodes to the same stream (its bit depth carries over) + local dec = Flac.open(Bytes.reader(f1)) :: any + local f3 = Flac.encode(dec, { level = 5 }) :: buffer + t:check(buffer.tostring(f3) == buffer.tostring(f1), "FLAC -> FLAC through the streaming decoder") +end + +-- tags, bit depth from the source +do + local a = Types.Audio.new(48000, 1, 3000) + for i = 0, 2999 do + buffer.writef32(a.samples, i * 4, math.floor(math.sin(i / 7) * 100) / 128) + end + a.tags = { title = "Tïtle", artist = "Artist", track = "3" } + a.meta.source = { format = "wav", bitDepth = 8 } + local f = Flac.encode(a) :: buffer + local back = Flac.decode(Bytes.reader(f)) :: Types.Audio + t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source") + -- (the absorbed FLAC decoder keeps Vorbis comment keys upper case) + local tags = back.tags :: any + t:eq(tags.title or tags.TITLE, "Tïtle", "title") + t:eq(tags.artist or tags.ARTIST, "Artist", "artist") + t:eq(tags.track or tags.TRACKNUMBER, "3", "track number") + local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer + local e0 = Flac.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty audio") +end + +-- errors +do + local a = Types.Audio.new(44100, 2, 10) + local function code(v: any, o: any): string? + local _, e = Flac.encode(v, o) + return e and e.code + end + t:eq(code({}, nil), Err.ARG, "junk value") + t:eq(code(a, { level = 9 }), Err.ARG, "level 9") + t:eq(code(a, { level = 2.5 }), Err.ARG, "level 2.5") + t:eq(code(a, { bits = 32 }), Err.ARG, "32 bits") + t:eq(code(a, { bits = 3 }), Err.ARG, "3 bits") + t:eq(code(a, { blockSize = 8 }), Err.ARG, "block size 8") + t:eq(code(Types.Audio.new(44100, 9, 1), nil), Err.ARG, "9 channels") + t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate") +end + +-- (the decoder's fuzz pass is in tests/audio/flac.luau; the encoder takes no untrusted bytes) +t:done() diff --git a/tests/core/md5.luau b/tests/core/md5.luau new file mode 100644 index 0000000..a40b8c8 --- /dev/null +++ b/tests/core/md5.luau @@ -0,0 +1,30 @@ +-- core/Md5 tests: the RFC 1321 test suite, incremental updates at every split, sub-ranges, a long input. +local T = require("@tests/T") +local Md5 = require("@formats/core/Md5") + +local t = T.suite("md5") +local VECTORS = { + { "", "d41d8cd98f00b204e9800998ecf8427e" }, + { "a", "0cc175b9c0f1b6a831c399e269772661" }, + { "abc", "900150983cd24fb0d6963f7d28e17f72" }, + { "message digest", "f96b697d7cb7938d525a2f31aaf161d0" }, + { "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" }, + { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f" }, + { string.rep("1234567890", 8), "57edf4a22be3c955ac49da2e2107b67a" }, +} +for _, v in VECTORS do + t:eq(Md5.of(buffer.fromstring(v[1])), v[2], "md5 of " .. string.format("%q", v[1])) +end +-- incremental: every split point of a 130-byte message, three pieces +local msg = string.rep("The quick brown fox jumps over the lazy dog. ", 3) +local want = Md5.of(buffer.fromstring(msg)) +for cut = 0, #msg, 7 do + local h = Md5.new() + h:update(buffer.fromstring(string.sub(msg, 1, cut))) + h:update(buffer.fromstring(string.sub(msg, cut + 1, cut + 20))) + h:update(buffer.fromstring(string.sub(msg, cut + 21))) + t:eq(Md5.hex(h:digest()), want, "split at " .. cut) +end +t:eq(Md5.of(buffer.fromstring("xxabcyy"), 2, 3), "900150983cd24fb0d6963f7d28e17f72", "sub-range") +t:eq(Md5.of(buffer.fromstring(string.rep("a", 1000000))), "7707d6ae4e027c70eea2a935c2296f21", "a million a's") +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 45f550e..cf64540 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -125,3 +125,22 @@ do Wav.decode(Bytes.reader(file)) end) end +-- flac encode (ws-audio): 10 s of 44.1 kHz stereo 16-bit (a synthetic two-tone signal with noise) +do + local Fl = require("@formats/audio/flac") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + local seed = 1 + for i = 0, n - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + local noise = (seed / 2147483648 - 0.5) * 0.01 + buffer.writef32(a.samples, i * 8, math.floor((math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1 + noise) * 32768) / 32768) + buffer.writef32(a.samples, i * 8 + 4, math.floor((math.sin(i * 0.017) * 0.3 + noise) * 32768) / 32768) + end + for _, level in { 0, 5, 8 } do + local dt = bench("flac encode -" .. level .. " (10 s st 16)", 2, n * 4, function() + Fl.encode(a, { level = level }) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", 10 / dt)) + end +end diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py index b9680c3..e9a5207 100644 --- a/tools/fixtures/_audio.py +++ b/tools/fixtures/_audio.py @@ -272,3 +272,45 @@ def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000): "maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"), "bytes": len(out), "sameStreamed": out == streamed, "data": out}) ctx.emit(fmt + "_enc", results) + + +def encode_luau_many(ctx, module, jobs, sigmod): + """jobs = [(signal name, opts_lua)] over the emitted module sigmod = { [name] = { rate, channels, frames, data } } + -> [bytes]: one Luau run encodes them all (length-prefixed on stdout)""" + body = ['job("%s", %s)' % (name, opts) for name, opts in jobs] + code = """ +local Types = require("@formats/Types") +local M = require("@formats/%s") +local S = require("@tests/gen/%s") +local outs = {} +local function job(name, opts) + local s = S[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + local out, err = M.encode(a, opts) + if not out then error("encode failed: " .. tostring(err)) end + local n = buffer.len(out) + table.insert(outs, string.format("%%012d", n) .. buffer.tostring(out)) +end +%s +print(table.concat(outs)) +""" % (module, sigmod, "\n".join(body)) + raw = luau(ctx, code) + res, p = [], 0 + while p < len(raw): + n = int(raw[p:p + 12]) + res.append(raw[p + 12:p + 12 + n]) + p += 12 + n + return res + + +def shell_many(ctx, packages, files, script): + """write files {name: bytes} into a temp dir and run `sh -c script` there under nix; returns stdout""" + d = tempfile.mkdtemp(prefix="fmt-audio-") + try: + for name, data in files.items(): + with open(os.path.join(d, name), "wb") as f: + f.write(data) + return ctx.nix(packages, ["sh", "-c", "cd '%s' && %s" % (d, script)]) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/flac_enc.py b/tools/fixtures/flac_enc.py new file mode 100644 index 0000000..19cf672 --- /dev/null +++ b/tools/fixtures/flac_enc.py @@ -0,0 +1,89 @@ +# FLAC encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py +# encode_luau_many) on test signals; every output must pass `flac -t` (which also checks the decoded PCM against the +# STREAMINFO MD5), and that MD5 must equal the MD5 of the input quantized here, so the stream is bit-exact. The level +# sweep is compared in size with `flac -` (libFLAC 1.5, --no-padding --no-seektable). +# tests/gen/flac_enc.luau { name, sig, opts, bits, channels, frames, flacTest, md5, wantMd5, size, refSize?, data } +# tests/gen/flac_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }: the inputs +import hashlib, importlib.util, os + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/flac", "src/Formats/codecs/Pcm", "src/Formats/core/Md5.luau"] + + +def pcm_bytes(samples, bits): + s = 2 ** (bits - 1) + nb = (bits + 7) // 8 + out = bytearray() + for v in samples: + q = max(-s, min(s - 1, int(__import__("math").floor(v * s + 0.5)))) + out += (q & ((1 << (8 * nb)) - 1)).to_bytes(nb, "little") + return bytes(out) + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, frames, rate=44100): + name = "flacsig_%s_%d_%d_%d" % (kind, ch, frames, rate) + if name not in sigs: + samples = A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames + ch))) # f32-rounded + sigs[name] = (samples, rate, ch) + return name + + cases = [] # (name, sigmod, bits, opts_lua, ref_level) + for level in range(9): + cases.append(("L%d-music-st16" % level, sig("music", 2, 20000), 16, "{ level = %d, bits = 16 }" % level, level)) + cases.append(("L%d-noise-mono24" % level, sig("noise", 1, 9000), 24, "{ level = %d, bits = 24 }" % level, level)) + cases.append(("L%d-sweep-6ch8" % level, sig("sweep", 6, 5000, 48000), 8, "{ level = %d, bits = 8 }" % level, level)) + for kind in ("sine", "silence", "loud", "square"): + for ch in (1, 2): + for bits in (8, 16, 24): + cases.append(("%s-%dch-%d" % (kind, ch, bits), sig(kind, ch, 4500), bits, "{ bits = %d }" % bits, None)) + for level in (0, 5, 8): + for n in (1, 15, 100, 1153, 4097): + cases.append(("L%d-len%d" % (level, n), sig("music", 2, n), 16, "{ level = %d }" % level, None)) + for bs in (192, 576, 1000, 4608, 16): + cases.append(("bs%d" % bs, sig("music", 2, 7000), 16, "{ blockSize = %d }" % bs, None)) + cases.append(("bits12-22k", sig("music", 1, 6000, 22050), 12, "{ bits = 12 }", None)) + cases.append(("bits20-96k", sig("sweep", 2, 6000, 96000), 20, "{ bits = 20, level = 8 }", None)) + cases.append(("rate-11111", sig("sine", 2, 3000, 11111), 16, "nil", None)) + cases.append(("seek-1s", sig("music", 2, 30000), 16, "{ seekInterval = 0.25 }", None)) + cases.append(("padding", sig("sine", 1, 1000), 16, "{ padding = 100 }", None)) + + ctx.emit("flac_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + outs = A.encode_luau_many(ctx, "audio/flac", [(c[1], c[3]) for c in cases], "flac_enc_sigs") + files = {"c%03d.flac" % i: o for i, o in enumerate(outs)} + script = 'for f in c*.flac; do r=$(flac -s -t "$f" 2>&1); echo "$f|$?|$(metaflac --show-md5sum "$f")|$(echo $r | tr "\\n" " ")"; done' + report = A.shell_many(ctx, "flac", files, script).decode(errors="replace") + rows = {} + for line in report.strip().split("\n"): + f, rc, md5, msg = line.split("|", 3) + rows[f] = (int(rc), md5.strip(), msg.strip()) + # libFLAC reference sizes for the level sweep + refs = {} + wavs = {} + for i, c in enumerate(cases): + if c[4] is not None: + samples, rate, ch = sigs[c[1]] + wavs["r%03d.raw" % i] = pcm_bytes(samples, c[2]) + wavs["r%03d.arg" % i] = ("-%d --channels=%d --bps=%d --sample-rate=%d" % (c[4], ch, c[2], rate)).encode() + script = ('for i in r*.raw; do rm -f out.flac; flac -s $(cat "${i%.raw}.arg") --force-raw-format --endian=little --sign=signed ' + '--no-padding --no-seektable -f -o out.flac "$i"; echo "$i $(stat -c %s out.flac)"; done') + for line in A.shell_many(ctx, "flac", wavs, script).decode().strip().split("\n"): + f, size = line.split() + refs[int(f[1:4])] = int(size) + emitted = [] + for i, (name, sigmod, bits, opts, lvl) in enumerate(cases): + samples, rate, ch = sigs[sigmod] + rc, md5, msg = rows["c%03d.flac" % i] + want = hashlib.md5(pcm_bytes(samples, bits)).hexdigest() + e = {"name": name, "sig": sigmod, "opts": opts, "bits": bits, "channels": ch, "frames": len(samples) // ch, + "flacTest": "" if rc == 0 else (msg or "rc %d" % rc), "md5": md5, "wantMd5": want, "size": len(outs[i]), + "data": outs[i]} + if i in refs: + e["refSize"] = refs[i] + emitted.append(e) + ctx.emit("flac_enc", emitted) From 73004015c8e576e5bb21d79d2a4387069f309130 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:04:45 -0500 Subject: [PATCH 17/28] ws-audio: tests/audio/flac.luau: caps.encode is now true --- tests/audio/flac.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau index c1d2305..75478d0 100644 --- a/tests/audio/flac.luau +++ b/tests/audio/flac.luau @@ -22,7 +22,7 @@ for _, c in Cases do end t:eq(Flac.name, "flac", "name") -t:check(Flac.caps.decode and not Flac.caps.encode, "caps") +t:check(Flac.caps.decode and Flac.caps.encode, "caps") -- encode: ws-audio (tests/audio/flac_encode.luau) local seekChecks = 0 for _, fx in Cases do From 3f2be59a65176905d14412c8d7c496cf3f453e28 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:05:04 -0500 Subject: [PATCH 18/28] ws-audio: tests/audio/flac.luau: caps.encode is now true, F.save flac works --- tests/audio/flac.luau | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau index 75478d0..3f0f9a3 100644 --- a/tests/audio/flac.luau +++ b/tests/audio/flac.luau @@ -156,8 +156,8 @@ do t:check(a and a.frames == fx.frames, "F.audio.load") local d = F.audio.open(byName.s16_l3.data) t:check(d and d.frames == byName.s16_l3.frames, "F.audio.open") - local _, se = F.save(a, nil, { format = "flac" }) - t:check(se and se.code == Err.UNSUPPORTED, "F.save flac is read-only here: " .. tostring(se)) + local saved, se = F.save(a, nil, { format = "flac" }) -- the encoder (ws-audio) + t:check(saved and F.audio.load(saved).frames == fx.frames, "F.save flac: " .. tostring(se)) end -- a damaged frame is dropped, the rest decodes From 8b8b64885fd3f5577baf0ce3ff1b2408f36ddeab Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:18:07 -0500 Subject: [PATCH 19/28] ws-music: music/xm read/write/render (FT2 / OpenMPT instrument, tremor, envelope and E6x quirks), tone portamento never starts MOD/XM notes --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/Tracker/Player.luau | 71 ++-- src/Formats/music/xm/init.luau | 560 +++++++++++++++++++++++++ tests/music/xm.luau | 77 ++++ tools/fixtures/xm.py | 161 +++++++ 6 files changed, 858 insertions(+), 24 deletions(-) create mode 100644 src/Formats/music/xm/init.luau create mode 100644 tests/music/xm.luau create mode 100644 tools/fixtures/xm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 450e651..5ddcb80 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,6 +10,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | | music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | | music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | +| music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 222ae4e..65f9734 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -74,6 +74,18 @@ local list: { Entry } = { return require("@formats/music/sf2") end, }, + { + name = "xm", + category = "music", + path = "music/xm", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, + load = function() + return require("@formats/music/xm") + end, + }, } return list diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau index 7f34e11..bf0742d 100644 --- a/src/Formats/codecs/Tracker/Player.luau +++ b/src/Formats/codecs/Tracker/Player.luau @@ -199,6 +199,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any patDelayRep = 0, fineDelay = 0, jumpOrd = -1, + ft2BreakPos = 0, breakRow = -1, loopJump = -1, ended = false, @@ -242,6 +243,9 @@ function Player.masterGain(m: any, fmt: number): number elseif fmt == S3M then return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the master volume, 64 = 0.5 end + if fmt == XM then + return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count + end -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) return 2 / clamp(m.channels, 2, 8) end @@ -295,6 +299,7 @@ local function advanceRow(st: any) local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 local r = if st.breakRow >= 0 then st.breakRow else 0 st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + st.ft2BreakPos = 0 Player.startOrder(st, o, r) return end @@ -309,7 +314,10 @@ local function advanceRow(st: any) end st.row += 1 if st.row >= st.pat.rows then - Player.startOrder(st, st.ord + 1, 0) + -- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep) + local r = if st.fmt == XM then st.ft2BreakPos else 0 + st.ft2BreakPos = 0 + Player.startOrder(st, st.ord + 1, r) end end @@ -428,7 +436,7 @@ local function cutVoice(v: any) end -- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c -local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: boolean) +local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) local v = c.voice if v == nil or v.bg then v = allocVoice(st) @@ -456,9 +464,11 @@ local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, i v.base = base st.age += 1 v.order = st.age - if not keepEnv then - v.keyOn = true - v.fading = false + if keepEnv ~= true then + if keepEnv ~= "release" then + v.keyOn = true + v.fading = false + end v.fade = 65536 v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 v.avPos, v.avAmp = 0, 0 @@ -612,8 +622,9 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb setInstrumentDefaults(st, c, smp, ins) if not hasNote then local v = c.voice - if f == XM and v and v.active and (prev == insIdx) then - -- an instrument number alone restarts the envelopes (FT2) + if f == XM and v then + -- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no + -- fadeout); the new instrument applies from the next note v.keyOn, v.fading, v.fade = true, false, 65536 v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 elseif (f == MOD or f == S3M) and smp then @@ -641,7 +652,8 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb local ft = c.finetune local period, base = notePeriod(st, realNote, smp, ft) local v = c.voice - if porta and v and v.active then + if porta and ((v and v.active) or f == MOD or f == XM) then + -- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it) c.target = period if st.fmt == IT or st.fmt == S3M then c.note = note @@ -650,8 +662,15 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb if f == IT and st.insMode then newNoteAction(st, c, ins, useIns, realNote, smpIdx) end - local keep = f == XM and insIdx == 0 and c.voice ~= nil + -- FT2: a note without an instrument number restarts the sample only (envelopes, key off and + -- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start + -- over but a key off stays + local keep: any = false + if f == XM and insIdx == 0 and c.voice ~= nil then + keep = if c.voice.ins == ins then true else "release" + end c.triggered = true + c.tremorOn = true c.retrigCount = 0 v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) c.period, c.target, c.base = period, period, base @@ -902,17 +921,19 @@ local function fxModXm(st: any, c: any, tick: number) elseif c.loopCount == 0 then c.loopCount = y st.loopJump = c.loopRow + st.ft2BreakPos = c.loopRow else c.loopCount -= 1 if c.loopCount > 0 then st.loopJump = c.loopRow end + st.ft2BreakPos = c.loopRow end end elseif x == 7 then c.tremWave = y % 8 elseif x == 8 then - if tick == 0 and not xm then + if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it c.pan = y * 17 c.surround = false end @@ -1051,8 +1072,9 @@ local function fxModXm(st: any, c: any, tick: number) -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks if fx == 29 and tick > 0 then local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 - c.tremorCount = (c.tremorCount + 1) % (on + off) + c.tremorCount %= on + off c.tremorOn = c.tremorCount < on + c.tremorCount += 1 end end @@ -1173,8 +1195,9 @@ local function fxS3mIt(st: any, c: any, tick: number) on, off = on + 1, off + 1 end on, off = max(on, 1), max(off, 1) - c.tremorCount = (c.tremorCount + 1) % (on + off) + c.tremorCount %= on + off c.tremorOn = c.tremorCount < on + c.tremorCount += 1 end elseif fx == 10 then -- J arpeggio local p = mem(st, c, "mArp", param) @@ -1550,9 +1573,7 @@ local function runEffects(st: any, c: any, tick: number) if fx ~= 7 then c.tremDelta = 0 end - if fx ~= 29 then - c.tremorOn = true - end + -- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2) else if fx ~= 18 then c.tremDelta = 0 @@ -1584,9 +1605,6 @@ local function processRow(st: any) c.fx, c.param, c.vcmd = fx, param, vcmd c.cutTick, c.keyOffTick = -1, -1 c.triggered = false - if fx ~= 29 and fx ~= 9 then - c.tremorCount = 0 - end local delay = noteDelayOf(st, fx, param) c.finetune = finetuneOf(st, fx, param) if delay > 0 then @@ -1600,7 +1618,7 @@ local function processRow(st: any) local _ = m end -local function updateEnvelope(env: any, pos: number, keyOn: boolean): (number, number, boolean) +local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) -- returns value, next position, ended local ticks, values = env.ticks, env.values local n = #ticks @@ -1626,9 +1644,14 @@ local function updateEnvelope(env: any, pos: number, keyOn: boolean): (number, n end local nextPos = pos + 1 local ended = false - if keyOn and env.sustain and ticks[env.susEnd] and nextPos > ticks[env.susEnd] then + -- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on) + -- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks), + -- IT after playing it (end - start + 1 ticks) + local se, le = ticks[env.susEnd], ticks[env.loopEnd] + local over = if it then 1 else 0 + if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then nextPos = ticks[env.susStart] or nextPos - elseif env.loop and ticks[env.loopEnd] and nextPos > ticks[env.loopEnd] then + elseif env.loop and le and pos <= le and nextPos >= le + over then nextPos = ticks[env.loopStart] or nextPos elseif nextPos > ticks[n] then nextPos = ticks[n] @@ -1646,7 +1669,7 @@ local function updateVoice(st: any, v: any) if ins then local e = ins.volEnv if e and e.enabled and v.volEnvOn then - local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn) + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) envVol, v.volEnvPos = val, np if ended and it then if val <= 0 then @@ -1658,12 +1681,12 @@ local function updateVoice(st: any, v: any) end e = ins.panEnv if e and e.enabled and v.panEnvOn then - local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn) + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) envPan, v.panEnvPos = val, np end e = ins.pitchEnv if e and e.enabled and v.pitchEnvOn then - local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn) + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) v.pitchEnvPos = np if e.filter then filterEnv = val diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau new file mode 100644 index 0000000..d2cbafa --- /dev/null +++ b/src/Formats/music/xm/init.luau @@ -0,0 +1,560 @@ +--!strict +-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / +-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/Tracker Module and +-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit +-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga +-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files +-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). +-- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Xm = { + name = "xm", + category = "music", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} +export type EncodeOptions = { + tracker: string?, -- the tracker name field (default: the source file's, else "formats-luau") +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Extended Module: " +local Pcm = Tracker.Pcm + +-- ------------------------------------------------------------------------------------------------ sniff +function Xm.sniff(r: Bytes.Reader): number + return if r:peek(17) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function readEnvelope(r: Bytes.Reader): ({ number }, { number }) + local xs, ys = {}, {} + for i = 1, 12 do + xs[i] = r:u16le() + ys[i] = r:u16le() + end + return xs, ys +end + +local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any + local e = Tracker.newEnvelope() + n = math.min(n, 12) + for i = 1, n do + e.ticks[i] = xs[i] + e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64) + end + e.enabled = bit32.band(typ, 1) ~= 0 and n > 0 + e.sustain = bit32.band(typ, 2) ~= 0 + e.loop = bit32.band(typ, 4) ~= 0 + e.susStart, e.susEnd = sus + 1, sus + 1 + e.loopStart, e.loopEnd = ls + 1, le + 1 + -- the raw fields, for a faithful re-save + e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } + return e +end + +function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(17) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no XM signature") + end + r:skip(17) + local title = r:fixed(20) + r:skip(1) + local tracker = r:fixed(20) + local version = r:u16le() + local hdrStart = r:tell() + local hdrSize = r:u32le() + local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le() + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + if r.err then + return nil, r.err + end + if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + if version < 0x0104 then + return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version)) + end + local m = Tracker.newModule("xm", nch) + m.title = title + m.speed = if speed > 0 and speed < 256 then speed else 6 + m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125 + m.linear = bit32.band(flags, 1) ~= 0 + m.restart = restart + for i = 1, songLen do + m.order[i] = orders[i] + end + m.meta.tracker = tracker + m.meta.source = { format = "xm", tracker = tracker, version = version } + -- patterns + if not r:seek(hdrStart + hdrSize) then + return nil, r.err + end + for p = 1, npat do + local start = r:tell() + local plen = r:u32le() + r:u8() + local rows = r:u16le() + local psize = r:u16le() + if r.err then + return nil, r.err + end + if rows < 1 or rows > 256 then + return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos) + end + r:seek(start + plen) + local pat = Tracker.newPattern(rows, nch) + m.patterns[p] = pat + local pr = r:slice(psize) + if r.err then + return nil, r.err + end + local d = pat.data + if psize > 0 then + for i = 0, rows * nch - 1 do + local b = pr:u8() + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if b >= 128 then + if bit32.band(b, 1) ~= 0 then + note = pr:u8() + end + if bit32.band(b, 2) ~= 0 then + ins = pr:u8() + end + if bit32.band(b, 4) ~= 0 then + vol = pr:u8() + end + if bit32.band(b, 8) ~= 0 then + fx = pr:u8() + end + if bit32.band(b, 16) ~= 0 then + param = pr:u8() + end + else + note, ins, vol, fx, param = b, pr:u8(), pr:u8(), pr:u8(), pr:u8() + end + if pr.err then + break -- a short pattern: the rest stays empty + end + if note == 97 then + note = 255 + elseif note > 96 then + note = 0 + end + if fx > 35 then + fx, param = 0, 0 + end + local o = i * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + -- instruments and their samples + local total = 0 + for i = 1, nins do + local start = r:tell() + local isize = r:u32le() + local ins = Tracker.newInstrument(r:fixed(22)) + r:u8() + local ns = r:u16le() + if r.err then + -- a file cut inside the instruments: keep what was read + r.err = nil + break + end + m.instruments[i] = ins + ins.samples = {} + if ns == 0 then + r:seek(start + math.max(isize, 29)) + continue + end + if ns > 256 then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples") + end + local shSize = r:u32le() + local keymap = {} + for n = 1, 96 do + keymap[n] = r:u8() + end + local vx, vy = readEnvelope(r) + local px, py = readEnvelope(r) + local nv, np = r:u8(), r:u8() + local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local vt, pt = r:u8(), r:u8() + ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8() + ins.fadeout = r:u16le() + if r.err then + return nil, r.err + end + ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false) + ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true) + ins.headerSize = isize + r:seek(start + isize) + local base = #m.samples + local heads = {} + for k = 1, ns do + local hs = r:tell() + local len, ls, ll = r:u32le(), r:u32le(), r:u32le() + local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8() + local nm = r:fixed(22) + r:seek(hs + math.max(shSize, 40)) + heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm } + end + if r.err then + return nil, r.err + end + for k = 1, ns do + local h = heads[k] + local s = Tracker.newSample(h.name) + local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8 + local bps = bits // 8 + s.bits = bits + s.volume = math.min(h.vol, 64) + s.finetune = h.ft + s.relativeNote = h.rel + s.pan = h.pan + local frames = h.len // bps + if h.res == 0xAD then + -- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length) + local bytes = 16 + (h.len + 1) // 2 + r:skip(math.min(bytes, r:remaining())) + frames = h.len + s.data = buffer.create(frames * 4) + else + local avail = r:remaining() // bps + local got = math.min(frames, avail) + total += got * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true }) + r:skip(got * bps) + s.data = data or buffer.create(0) + frames = if data then got else 0 + end + s.length = frames + local lt = h.typ % 4 + if lt == 3 then + lt = 2 + end + if lt > 0 and h.ll > 0 then + s.loopStart = h.ls // bps + s.loopEnd = (h.ls + h.ll) // bps + s.loopType = lt + end + m.samples[base + k] = s + table.insert(ins.samples, base + k) + end + for n = 1, 120 do + local k = keymap[math.min(n, 96)] + ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0 + end + ins.keymap = keymap + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string?, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } +local function instrumentsOf(m: any): ({ any }?, string?) + local out = {} + if m.format == "mod" then + for i, s in m.samples do + local km = table.create(96, 0) + out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil } + end + return out + end + for i, ins in m.instruments do + local list: { number } = {} + if type(ins.samples) == "table" then + for _, g in ins.samples do + table.insert(list, g) + end + end + local index: { [number]: number } = {} + for k, g in list do + index[g] = k - 1 + end + local km = table.create(96, 0) + for n = 1, 96 do + local g = ins.sampleMap[n] or 0 + if g > 0 and m.samples[g] then + if index[g] == nil then + table.insert(list, g) + index[g] = #list - 1 + end + km[n] = index[g] + end + end + if #list > 255 then + return nil, "instrument " .. i .. " uses more than 255 samples" + end + local smps = {} + for k, g in list do + smps[k] = m.samples[g] or Tracker.newSample() + end + out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins } + end + return out +end + +local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean) + local n = if e then math.min(#e.ticks, 12) else 0 + for i = 1, 12 do + if i <= n then + w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535)) + w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64)) + else + w:u32le(0) + end + end +end + +-- envelope count, type, sustain, loop start, loop end +local function envelopeFields(e: any): (number, number, number, number, number) + if not e then + return 0, 0, 0, 0, 0 + end + local n = math.min(#e.ticks, 12) + local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0) + local raw = e.raw + if raw and raw.type % 8 == typ then + typ = raw.type -- keep unknown bits + end + local function idx(v: number): number + return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) + end + local sus = idx(e.susStart) + local ls, le = idx(e.loopStart), idx(e.loopEnd) + if raw and n == 0 then + sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd + end + return n, typ, sus, ls, le +end + +-- encode(module, opts) -> XM bytes ("xm" or "mod" modules) +function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "xm" and m.format ~= "mod" then + return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")") + end + local nch = m.channels + if nch > 64 then + return nil, Err.new(Err.ARG, "XM holds at most 64 channels") + end + local insts, ierr = instrumentsOf(m) + if not insts then + return nil, Err.new(Err.ARG, ierr or "bad instruments") + end + if #insts > 128 then + return nil, Err.new(Err.ARG, "XM holds at most 128 instruments") + end + if #m.patterns > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 patterns") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 order entries") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + writeName(w, m.title, 20) + w:u8(0x1A) + writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "formats-luau", 20) + w:u16le(0x0104) + w:u32le(276) + w:u16le(#order) + w:u16le(if m.restart < #order then m.restart else 0) + w:u16le(nch) + w:u16le(#m.patterns) + w:u16le(#insts) + w:u16le(if m.linear then 1 else 0) + w:u16le(m.speed) + w:u16le(math.clamp(math.floor(m.tempo), 32, 999)) + for i = 1, 256 do + w:u8(order[i] or 0) + end + -- patterns (every cell packed, as FT2-compatible writers may) + for _, pat in m.patterns do + local pk = Bytes.writer(pat.rows * nch * 2) + local d = pat.data + for i = 0, pat.rows * nch - 1 do + local o = i * 5 + local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if note == 255 then + note = 97 + elseif note > 96 then + note = 0 + end + if m.format == "mod" then + vol = 0 + if fx > 15 then + fx, param = 0, 0 + end + end + if ins > 128 then + ins = 0 + end + local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0) + pk:u8(flags) + if note > 0 then + pk:u8(note) + end + if ins > 0 then + pk:u8(ins) + end + if vol > 0 then + pk:u8(vol) + end + if fx > 0 then + pk:u8(fx) + end + if param > 0 then + pk:u8(param) + end + end + local data = pk:finish() + if buffer.len(data) > 65535 then + return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB") + end + w:u32le(9) + w:u8(0) + w:u16le(pat.rows) + w:u16le(buffer.len(data)) + w:bytes(data) + end + -- instruments + for _, it in insts do + local ins = it.ins + local smps = it.samples + if #smps == 0 then + w:u32le(29) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(0) + continue + end + w:u32le(263) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(#smps) + w:u32le(40) + for n = 1, 96 do + w:u8(it.keymap[n]) + end + local ve, pe = ins and ins.volEnv, ins and ins.panEnv + writeEnvelope(w, ve, false) + writeEnvelope(w, pe, true) + local vn, vt, vs, vls, vle = envelopeFields(ve) + local pn, pt, ps, pls, ple = envelopeFields(pe) + w:u8(vn) + w:u8(pn) + w:u8(vs) + w:u8(vls) + w:u8(vle) + w:u8(ps) + w:u8(pls) + w:u8(ple) + w:u8(vt) + w:u8(pt) + w:u8(ins and ins.vibType or 0) + w:u8(ins and ins.vibSweep or 0) + w:u8(ins and ins.vibDepth or 0) + w:u8(ins and ins.vibRate or 0) + w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0) + w:fill(0, 22) + local datas = {} + for k, s in smps do + local mono = s.data + if s.channels == 2 then + mono = buffer.create(s.length * 4) + for f = 0, s.length - 1 do + buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2) + end + end + local bits = if s.bits == 16 then 16 else 8 + local bps = bits // 8 + datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true }) + local typ = (if bits == 16 then 16 else 0) + local ls, ll = 0, 0 + if s.loopType > 0 then + typ += s.loopType + ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps + end + local ft = s.finetune + local rel = s.relativeNote + if m.format == "mod" then + rel = 0 + end + w:u32le(s.length * bps) + w:u32le(ls) + w:u32le(ll) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + w:u8(math.clamp(math.floor(ft), -128, 127) % 256) + w:u8(typ) + w:u8(math.clamp(math.floor(s.pan or 128), 0, 255)) + w:u8(math.clamp(math.floor(rel), -128, 127) % 256) + w:u8(0) + writeName(w, s.name, 22) + end + for _, dd in datas do + w:bytes(dd) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Xm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Xm diff --git a/tests/music/xm.luau b/tests/music/xm.luau new file mode 100644 index 0000000..2e47118 --- /dev/null +++ b/tests/music/xm.luau @@ -0,0 +1,77 @@ +-- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Xm = require("@formats/music/xm") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/xm_cases") + +local t = T.suite("xm") + +t:eq(Xm.name, "xm", "name") +t:eq(Xm.category, "music", "category") +t:check(Xm.caps.decode and Xm.caps.encode, "caps") + +local function load(data: string): any + return Xm.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(Xm.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") + -- the writer: XM -> XM gives the same bytes back (the fixtures use the FT2 layout) + local out, werr = Xm.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Xm.decode(Bytes.reader(out :: buffer)) + t:check(m2, c.name .. ": re-decode") + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = Xm.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tools/fixtures/xm.py b/tools/fixtures/xm.py new file mode 100644 index 0000000..fd40898 --- /dev/null +++ b/tools/fixtures/xm.py @@ -0,0 +1,161 @@ +# XM fixtures (tools/fixtures.py): generated FastTracker 2 modules exercising instruments (envelopes, fadeout, +# auto-vibrato, keymaps, 16-bit and ping-pong samples) and the effects, rendered by openmpt123. +# tests/gen/xm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + +OFF = 97 +Gx, Hx, Kx, Lx, Px, Rx, Tx, Xx = 16, 17, 20, 21, 25, 27, 29, 33 + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=0, fx=0, param=0): + p[row][ch] = (note, ins, vol, fx, param) + + +def instruments(): + sine = {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + tri = {"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 48, "pan": 96, "relnote": 12, "finetune": -20, + "loop": (0, 32, 1)} + saw16 = {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 56, "pan": 160, + "loop": (0, 128, 1)} + ping = {"name": "ping", "data": T.s8(T.synth("saw", 200, 200, 0.7)), "volume": 64, "pan": 128, "finetune": 30, + "loop": (20, 150, 2)} + noise = {"name": "noise", "data": T.s8(T.synth("noise", 5000, 1, 0.7, decay=1500)), "volume": 60, "pan": 128} + square = {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + return [ + {"name": "env", "samples": [sine], "volenv": {"points": [(0, 0), (4, 64), (10, 40), (30, 20), (40, 0)], "sustain": 2}, + "fadeout": 1024}, + {"name": "panloop", "samples": [square], "panenv": {"points": [(0, 0), (8, 64), (16, 0)], "loop": (0, 2)}, + "volenv": {"points": [(0, 64), (20, 48), (60, 32)], "loop": (1, 2)}, "fadeout": 512}, + {"name": "autovib", "samples": [saw16], "vib": (0, 10, 8, 6)}, + {"name": "multi", "samples": [sine, tri], "keymap": [0] * 48 + [1] * 48}, + {"name": "ping", "samples": [ping]}, + {"name": "noise", "samples": [noise]}, + {"name": "sq vib", "samples": [square], "vib": (1, 0, 4, 20)}, + {"name": "empty"}, + ] + + +def song_instruments(): + a, b = empty(4), empty(4) + put(a, 0, 0, 49, 1) + put(a, 12, 0, OFF) + put(a, 20, 0, 56, 1) + put(a, 24, 0, 0, 0, 0, Kx, 3) + put(a, 32, 0, 61, 1) + put(a, 33, 0, 0, 0, 0, Lx, 20) + put(a, 40, 0, 63) + put(a, 44, 0, OFF) + put(a, 48, 0, 0, 1) + put(a, 0, 1, 37, 2) + put(a, 30, 1, OFF) + put(a, 40, 1, 44, 2) + put(a, 0, 2, 49, 3) + put(a, 32, 2, 56, 3) + put(a, 8, 3, 37, 4) + put(a, 16, 3, 61, 4) + put(a, 24, 3, 73, 4) + put(a, 32, 3, 85, 4) + put(a, 40, 3, 49, 5) + put(a, 52, 3, 61, 5) + put(a, 60, 3, 61, 8) + put(b, 0, 0, 49, 7) + put(b, 0, 1, 56, 3, 0x30) + put(b, 8, 1, 0, 3) + put(b, 16, 2, 61, 6, 0x40) + put(b, 20, 2, 61, 6, 0, 0x9, 0x08) + put(b, 24, 2, 61, 6, 0, 0xE, 0x93) + put(b, 32, 3, 49, 1) + put(b, 36, 3, 61) + put(b, 40, 3, OFF) + put(b, 44, 3, 63) + put(b, 48, 0, 0, 0, 0, 0xD, 0x00) + return T.write_xm("instruments", instruments(), [0, 1], [a, b], 4) + + +def song_effects(linear=True): + a, b = empty(6), empty(6, 48) + put(a, 0, 0, 49, 7, 0, 0x1, 0x04) + put(a, 4, 0, 0, 0, 0, 0x1, 0x00) + put(a, 8, 0, 0, 0, 0, 0x2, 0x08) + put(a, 12, 0, 0, 0, 0, 0xE, 0x18) + put(a, 13, 0, 0, 0, 0, 0xE, 0x10) + put(a, 14, 0, 0, 0, 0, 0xE, 0x2F) + put(a, 16, 0, 0, 0, 0, Xx, 0x1F) + put(a, 17, 0, 0, 0, 0, Xx, 0x10) + put(a, 18, 0, 0, 0, 0, Xx, 0x28) + put(a, 20, 0, 49, 7, 0, 0x3, 0x10) + put(a, 21, 0, 61, 0, 0, 0x3, 0x00) + put(a, 24, 0, 0, 0, 0, 0x5, 0x02) + put(a, 28, 0, 56, 0, 0, 0x4, 0x48) + put(a, 32, 0, 0, 0, 0, 0x6, 0x20) + put(a, 36, 0, 0, 0, 0, 0x7, 0x6F) + put(a, 40, 0, 0, 0, 0, Tx, 0x21) + put(a, 44, 0, 0, 0, 0, 0xA, 0x0F) + put(a, 46, 0, 0, 0, 0, 0xE, 0xA8) + put(a, 48, 0, 61, 7, 0, 0x0, 0x37) + put(a, 52, 0, 0, 0, 0, 0xE, 0xC3) + # channel 1: the volume column + put(a, 0, 1, 56, 6, 0x30) + put(a, 4, 1, 0, 0, 0x64) + put(a, 8, 1, 0, 0, 0x73) + put(a, 12, 1, 0, 0, 0x85) + put(a, 13, 1, 0, 0, 0x9A) + put(a, 16, 1, 0, 0, 0xA6) + put(a, 17, 1, 0, 0, 0xB8) + put(a, 24, 1, 0, 0, 0xC2) + put(a, 28, 1, 0, 0, 0xE4) + put(a, 32, 1, 0, 0, 0xD6) + put(a, 36, 1, 61, 0, 0xF8) + put(a, 40, 1, 49, 0, 0xF0) + # channel 2: panning, retrig, offset, delay + put(a, 0, 2, 61, 2, 0, 0x8, 0x20) + put(a, 8, 2, 0, 0, 0, Px, 0x30) + put(a, 16, 2, 0, 0, 0, Px, 0x06) + put(a, 24, 2, 61, 6, 0, Rx, 0x83) + put(a, 32, 2, 61, 6, 0, Rx, 0x32) + put(a, 40, 2, 61, 6, 0, 0x9, 0x06) + put(a, 48, 2, 61, 6, 0, 0xE, 0xD3) + put(a, 56, 2, 61, 6, 0x20, 0xE, 0xC2) + # channel 3: global volume, pattern loop, pattern delay, speed / tempo + put(a, 0, 3, 37, 3, 0, Gx, 0x30) + put(a, 8, 3, 0, 0, 0, Hx, 0x02) + put(a, 16, 3, 0, 0, 0, Hx, 0x40) + put(a, 24, 3, 0, 0, 0, 0xE, 0x60) + put(a, 26, 3, 0, 0, 0, 0xE, 0x62) + put(a, 32, 3, 0, 0, 0, 0xE, 0xE2) + put(a, 40, 3, 0, 0, 0, 0xF, 0x05) + put(a, 48, 3, 0, 0, 0, 0xF, 0x96) + # channel 4 / 5: an instrument change without a note, an empty instrument, a note after key off + put(a, 0, 4, 49, 1) + put(a, 8, 4, 0, 2) + put(a, 16, 4, OFF) + put(a, 24, 4, 51) + put(a, 32, 4, 51, 8) + put(a, 40, 4, 53, 1) + put(a, 4, 5, 73, 5, 0, 0xE, 0x80) + put(a, 20, 5, 0, 0, 0, 0x8, 0xC0) + # pattern b (48 rows): portamento in the other direction, arpeggio, a break and a jump back (song loop) + put(b, 0, 0, 73, 7, 0, 0x4, 0x00) + put(b, 0, 1, 61, 4) + put(b, 4, 1, 0, 0, 0, 0x0, 0x47) + put(b, 16, 1, 25, 4, 0, 0x2, 0x10) + put(b, 32, 0, 0, 0, 0, 0xB, 0x01) + return T.write_xm("effects", instruments(), [0, 1], [a, b], 6, speed=5, tempo=130, linear=linear, restart=1) + + +def generate(ctx): + cases = [] + for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))): + ref = T.reference(ctx, data, "xm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("xm_cases", cases) From 929b5d6d5369173a26a24a05df718d4401dfe4cb Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:18:23 -0500 Subject: [PATCH 20/28] ws-audio: MP3 layer III encoder (Encode3: shine-style CBR, MPEG-1/2/2.5, mono/stereo/joint MS, global-gain rate loop, region/table choice, count1 A/B) + MP2 layer II encoder (Encode2: standard alloc tables, greedy noise allocation, grouping), shared polyphase Analysis, EncTables (PDMP3 public-domain window + Huffman trees -> codeword tables); mp3 init encode() with ID3v2.4; fixtures decode with ffmpeg + lame (no errors, SNR floors); bench lines --- docs/FORMATS.md | 2 +- licenses/NOTICE.md | 1 + licenses/PDMP3-UNLICENSE.txt | 27 ++ src/Formats/Registry.luau | 4 +- src/Formats/audio/mp3/Analysis.luau | 63 +++ src/Formats/audio/mp3/EncTables.luau | 292 ++++++++++++ src/Formats/audio/mp3/Encode2.luau | 407 ++++++++++++++++ src/Formats/audio/mp3/Encode3.luau | 680 +++++++++++++++++++++++++++ src/Formats/audio/mp3/init.luau | 128 ++++- tests/audio/mp3.luau | 6 +- tests/audio/mp3_encode.luau | 143 ++++++ tools/bench.luau | 16 + tools/fixtures/_audio.py | 22 +- tools/fixtures/mp3_enc.py | 80 ++++ 14 files changed, 1859 insertions(+), 12 deletions(-) create mode 100644 licenses/PDMP3-UNLICENSE.txt create mode 100644 src/Formats/audio/mp3/Analysis.luau create mode 100644 src/Formats/audio/mp3/EncTables.luau create mode 100644 src/Formats/audio/mp3/Encode2.luau create mode 100644 src/Formats/audio/mp3/Encode3.luau create mode 100644 tests/audio/mp3_encode.luau create mode 100644 tools/fixtures/mp3_enc.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b57f8d9..72cc12e 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 | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | | audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` | | audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | -| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | +| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | 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 | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | - | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index e218c97..d380919 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -14,6 +14,7 @@ | `src/Formats/image/bmp/` | bmp-luau b86aed6 (same author), written from the Microsoft BMP documentation | no licence chosen yet; no third-party code | | `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | | `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code | +| `src/Formats/audio/mp3/EncTables.luau` (ws-audio encoders) | PDMP3 by Krister Lagerström et al. (https://github.com/technosaurus/PDMP3): the ISO/IEC 11172-3 synthesis window and layer III Huffman trees | public domain (unlicense): [PDMP3-UNLICENSE.txt](PDMP3-UNLICENSE.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/licenses/PDMP3-UNLICENSE.txt b/licenses/PDMP3-UNLICENSE.txt new file mode 100644 index 0000000..abdbb5f --- /dev/null +++ b/licenses/PDMP3-UNLICENSE.txt @@ -0,0 +1,27 @@ +PDMP3 (https://github.com/technosaurus/PDMP3), public domain decoder by Krister Lagerstrom et al. +Tables used in src/Formats/audio/mp3/EncTables.luau. + +Public Domain (www.unlicense.org) + This is free and unencumbered software released into the public domain. + Anyone is free to copy, modify, publish, use, compile, sell, or distribute this + software, either in source code form or as a compiled binary, for any purpose, + commercial or non-commercial, and by any means. + In jurisdictions that recognize copyright laws, the author or authors of this + software dedicate any and all copyright interest in the software to the public + domain. We make this dedication for the benefit of the public at large and to + the detriment of our heirs and successors. We intend this dedication to be an + overt act of relinquishment in perpetuity of all present and future rights to + this software under copyright law. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + Original version written by Krister Lagerström(krister@kmlager.com) + Website: https://sites.google.com/a/kmlager.com/www/projects + + Contributors: + technosaurus + Erik Hofman (added a subset of the libmpg123 compatible streaming API) diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index cbdfa37..0b9fbc5 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -80,8 +80,8 @@ local list: { Entry } = { path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") end, diff --git a/src/Formats/audio/mp3/Analysis.luau b/src/Formats/audio/mp3/Analysis.luau new file mode 100644 index 0000000..782b023 --- /dev/null +++ b/src/Formats/audio/mp3/Analysis.luau @@ -0,0 +1,63 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 +-- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from +-- audio/mp3/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III +-- encoders. New code from the standard's flow chart. Never throws. +-- +-- local st = Analysis.new() +-- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31] +local E = require("@formats/audio/mp3/EncTables") + +local Analysis = {} + +local C = table.create(512, 0) +for i = 1, 512 do + C[i] = E.D[i] / 32 +end +local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1] +for k = 0, 31 do + for i = 0, 63 do + M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) + end +end + +export type State = { x: { number }, off: number, y: { number } } + +function Analysis.new(): State + return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } +end + +-- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) +function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) + -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo + local x = st.x + local off = (st.off - 32) % 512 + st.off = off + for j = 0, 31 do + local v = s[si + j] + local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] + x[p] = v + x[p + 512] = v + end + local y = st.y + for i = 0, 63 do + local acc = 0 + local b = off + i + 1 + for j = 0, 7 do + acc += C[i + 64 * j + 1] * x[b + 64 * j] + end + y[i + 1] = acc + end + for k = 0, 31 do + local acc = 0 + local mb = k * 64 + for i = 1, 64 do + acc += M[mb + i] * y[i] + end + out[oi + k] = acc + end +end + +return Analysis diff --git a/src/Formats/audio/mp3/EncTables.luau b/src/Formats/audio/mp3/EncTables.luau new file mode 100644 index 0000000..e730723 --- /dev/null +++ b/src/Formats/audio/mp3/EncTables.luau @@ -0,0 +1,292 @@ +--!strict +-- audio/mp3/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister +-- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D +-- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from +-- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low +-- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits). +local E = {} +E.D = { + 0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518, + -0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294, + -0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847, + -0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729, + -0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716, + -0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103, + -0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854, + -0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828, + 0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745, + 0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183, + 0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316, + -0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774, + -0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827, + -0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666, + -0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744, + -0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882, + 0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241, + 0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876, + -0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131, + -0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082, + -0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021, + -0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493, + -0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193, + -0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201, + 0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010, + 0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059, + -0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481, + -0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242, + -0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907, + -0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934, + -0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715, + -1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109, + 1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901, + 1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338, + 0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014, + 0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727, + 0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537, + 0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429, + 0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271, + -0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124, + 0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771, + 0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967, + 0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399, + 0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739, + 0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155, + 0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531, + 0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250, + -0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578, + 0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859, + 0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861, + 0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352, + 0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312, + 0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726, + 0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866, + -0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192, + -0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416, + 0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735, + 0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726, + 0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304, + 0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022, + 0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623, + 0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553, + 0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518, + 0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, +} +E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 } +-- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's) +E.TREES = { + [1] = { + 0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, + }, + [2] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [3] = { + 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [5] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033, + }, + [6] = { + 0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033, + }, + [7] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004, + 0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043, + 0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, + 0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055, + }, + [8] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020, + 0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035, + 0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055, + }, + [9] = { + 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401, + 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050, + 0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005, + 0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055, + }, + [10] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, + 0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401, + 0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015, + 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053, + 0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072, + 0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201, + 0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [11] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801, + 0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033, + 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201, + 0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401, + 0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053, + 0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601, + 0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [12] = { + 0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021, + 0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201, + 0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035, + 0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201, + 0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017, + 0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401, + 0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [13] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, + 0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044, + 0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601, + 0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018, + 0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009, + 0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047, + 0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067, + 0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201, + 0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a, + 0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401, + 0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01, + 0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4, + 0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201, + 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401, + 0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201, + 0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201, + 0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01, + 0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c, + 0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa, + 0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab, + 0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401, + 0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201, + 0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201, + 0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f, + 0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd, + 0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd, + 0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201, + 0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe, + }, + [15] = { + 0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032, + 0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01, + 0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, + 0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055, + 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, + 0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601, + 0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01, + 0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086, + 0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, + 0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096, + 0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a, + 0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b, + 0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c, + 0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401, + 0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a, + 0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01, + 0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8, + 0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d, + 0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9, + 0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4, + 0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c, + 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401, + 0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801, + 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201, + 0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201, + 0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db, + 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be, + 0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201, + 0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff, + }, + [16] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, + 0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, + 0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017, + 0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601, + 0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082, + 0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048, + 0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085, + 0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057, + 0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01, + 0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4, + 0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b, + 0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1, + 0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801, + 0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601, + 0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b, + 0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201, + 0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201, + 0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa, + 0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c, + 0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201, + 0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb, + 0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801, + 0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da, + 0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb, + 0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f, + 0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6, + 0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af, + 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [24] = { + 0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201, + 0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201, + 0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062, + 0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046, + 0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01, + 0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082, + 0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, + 0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01, + 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068, + 0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201, + 0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601, + 0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0, + 0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201, + 0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401, + 0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201, + 0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401, + 0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801, + 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01, + 0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d, + 0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201, + 0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01, + 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e, + 0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd, + 0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec, + 0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201, + 0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201, + 0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af, + 0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [32] = { + 0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201, + 0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b, + }, + [33] = { + 0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007, + 0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f, + }, +} +return E diff --git a/src/Formats/audio/mp3/Encode2.luau b/src/Formats/audio/mp3/Encode2.luau new file mode 100644 index 0000000..0a6af36 --- /dev/null +++ b/src/Formats/audio/mp3/Encode2.luau @@ -0,0 +1,407 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 +-- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3, +-- C.1.5.2): the polyphase analysis (audio/mp3/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are +-- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder +-- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise +-- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of +-- 3 / 5 / 9-level samples. Never throws. +local T = require("@formats/audio/mp3/Tables") +local Analysis = require("@formats/audio/mp3/Analysis") + +local Encode2 = {} + +local floor, log = math.floor, math.log +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local CODE = T.g_bitalloc_code_tab + +-- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped +local function levels(ba: number): number + if ba >= 17 then + return if ba == 17 then 3 elseif ba == 18 then 5 else 9 + end + return POW[ba + 1] - 1 +end +-- bits for the 3 samples of one granule +local function tripleBits(ba: number): number + if ba >= 17 then + return if ba == 17 then 5 elseif ba == 18 then 7 else 10 + end + return 3 * ba +end +-- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) +local SNR: { [number]: number } = {} +do + local byLevels = { + [3] = 7.00, + [5] = 11.00, + [7] = 16.00, + [9] = 20.84, + [15] = 25.28, + [31] = 31.59, + [63] = 37.75, + [127] = 43.84, + [255] = 49.89, + [511] = 55.93, + [1023] = 61.96, + [2047] = 67.98, + [4095] = 74.01, + [8191] = 80.03, + [16383] = 86.05, + [32767] = 92.01, + [65535] = 98.01, + } + for ba = 1, 19 do + SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) + end +end + +-- scalefactors 2^(1 - i/3), i = 0 .. 62 +local SCF = table.create(63, 0) +for i = 0, 62 do + SCF[i + 1] = 2 ^ (1 - i / 3) +end + +local RATES = { + [44100] = { 3, 0 }, + [48000] = { 3, 1 }, + [32000] = { 3, 2 }, + [22050] = { 2, 0 }, + [24000] = { 2, 1 }, + [16000] = { 2, 2 }, +} +Encode2.RATES = RATES +local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } +local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } +Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +type W = { buf: buffer, pos: number, acc: number, cnt: number } +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +export type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { bitrate: number, mode: string, prefix: buffer? } + +-- encode(src, opts) -> buffer | nil, message +function Encode2.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex = info[1], info[2] + local mpeg1 = version == 3 + local inCh = src.channels + local nch = if opts.mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + -- the allocation table (the decoder's choice from the header) + local alloc, nbands + if not mpeg1 then + alloc, nbands = ALLOC_L2M2, 30 + else + local perCh = if nch == 2 then kbps // 2 else kbps + alloc, nbands = ALLOC_L2M1, 27 + if perCh < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8 + elseif perCh >= 96 and srIndex ~= 1 then + nbands = 30 + end + end + local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) + do + local k, ai = 0, 1 + local off, bits = 0, 0 + for i = 0, nbands - 1 do + if i == k then + off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + bandOff[i + 1], bandBits[i + 1] = off, bits + end + end + -- per band: the classes it can take, in increasing order (index into the code table = the value written) + local steps: { { { number } } } = {} + for i = 1, nbands do + local s = {} + for v = 1, POW[bandBits[i] + 1] - 1 do + local ba = CODE[bandOff[i] + v] + if ba and ba > 0 then + table.insert(s, { v, ba }) + end + end + steps[i] = s + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + if buffer.len(pf) > buffer.len(w.buf) - 16 then + w.buf = buffer.create(buffer.len(pf) + 65536) + end + buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) + w.pos = buffer.len(pf) + end + local ana = { Analysis.new(), Analysis.new() } + local pcm = { table.create(1152, 0), table.create(1152, 0) } + -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 + local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } + local sub = table.create(32, 0) + local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part + local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band + local slot = 144000 * kbps + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone, flushed = false, false + while true do + local got = 0 + while got < 1152 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(1152 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, 1152 do + s[i] = 0 + end + local sb = sbs[c] + for t = 0, 35 do + Analysis.run(ana[c], s, t * 32 + 1, sub, 1) + for b = 0, 31 do + sb[b * 36 + t + 1] = sub[b + 1] + end + end + -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak + local sc = scf[c] + for b = 0, nbands - 1 do + for part = 0, 2 do + local m = 0 + local o = b * 36 + part * 12 + for t = 1, 12 do + local v = math.abs(sb[o + t]) + if v > m then + m = v + end + end + local idx = 62 + if m > 0 then + idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) + while idx > 0 and SCF[idx + 1] < m do + idx -= 1 + end + while idx < 62 and SCF[idx + 2] >= m do + idx += 1 + end + end + sc[b * 3 + part + 1] = idx + end + end + end + -- the frame size and the bits left for scalefactors and samples + local frameBytes = slot // rate + rest += slot % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = frameBytes * 8 - 32 + for b = 1, nbands do + avail -= bandBits[b] * nch + end + -- greedy allocation: the band with the most noise gets its next step while it fits + local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band + for c = 1, nch do + local sc = scf[c] + for b = 1, nbands do + local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) + level[c][b] = 20 * math.log10(SCF[best + 1]) + bal[c][b] = 0 + end + end + while true do + local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 + for c = 1, nch do + for b = 1, nbands do + local st = bal[c][b] + local s = steps[b] + if st < #s and level[c][b] > -110 then + local cur = if st == 0 then 0 else s[st][2] + local nxt = s[st + 1][2] + local noise = level[c][b] - (if st == 0 then 0 else SNR[cur]) + local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur)) + if st == 0 then + cost += 2 + 18 -- scfsi + three scalefactors + end + if cost <= avail and noise > bestNoise then + bestC, bestB, bestNoise, bestCost = c, b, noise, cost + end + end + end + end + if bestC == 0 then + break + end + bal[bestC][bestB] += 1 + avail -= bestCost + end + -- write the frame + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 2, 2) -- layer II + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if nch == 1 then 3 else 0, 2) + put(w, 0, 2) + put(w, 0, 1) + put(w, 1, 1) + put(w, 0, 2) + -- bit allocation + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b]) + end + end + -- scfsi (0: three scalefactors) and the scalefactors + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + put(w, 0, 2) + end + end + end + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + for part = 1, 3 do + put(w, scf[c][(b - 1) * 3 + part], 6) + end + end + end + end + -- samples: 12 granules of 3, band by band, channel by channel + for gr = 0, 11 do + local part = gr // 4 + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + if st > 0 then + local ba = steps[b][st][2] + local L = levels(ba) + local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] + local o = (b - 1) * 36 + gr * 3 + local sb = sbs[c] + local q0, q1, q2 + do + local function quant(x: number): number + local q = floor((x * inv + 1) * L / 2) + return if q < 0 then 0 elseif q > L - 1 then L - 1 else q + end + q0, q1, q2 = quant(sb[o + 1]), quant(sb[o + 2]), quant(sb[o + 3]) + end + if ba >= 17 then + put(w, q0 + L * (q1 + L * q2), tripleBits(ba)) + else + put(w, q0, ba) + put(w, q1, ba) + put(w, q2, ba) + end + end + end + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode2 diff --git a/src/Formats/audio/mp3/Encode3.luau b/src/Formats/audio/mp3/Encode3.luau new file mode 100644 index 0000000..39e6dbf --- /dev/null +++ b/src/Formats/audio/mp3/Encode3.luau @@ -0,0 +1,680 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only, +-- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0), +-- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono, +-- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the +-- analysis filterbank (audio/mp3/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, +-- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are +-- derived from the standard's decoder trees (audio/mp3/EncTables, from PDMP3, public domain). Never throws. +local E = require("@formats/audio/mp3/EncTables") +local T = require("@formats/audio/mp3/Tables") +local Analysis = require("@formats/audio/mp3/Analysis") + +local Encode3 = {} + +local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ Huffman codes +-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A +-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1 +local CODE: { [number]: { number } } = {} +local LEN: { [number]: { number } } = {} +local XLEN: { [number]: number } = {} + +local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) + local v = tree[p + 1] + if bit32.band(v, 0xFF00) == 0 then + local idx = bit32.band(v, 0xFF) + 1 + if lens[idx] == 0 then + codes[idx], lens[idx] = code, len + end + return + end + -- left (bit 0): offsets of 250+ chain + local q = p + while bit32.rshift(tree[q + 1], 8) >= 250 do + q += bit32.rshift(tree[q + 1], 8) + end + q += bit32.rshift(tree[q + 1], 8) + walk(tree, codes, lens, q, code * 2, len + 1) + q = p + while bit32.band(tree[q + 1], 0xFF) >= 250 do + q += bit32.band(tree[q + 1], 0xFF) + end + q += bit32.band(tree[q + 1], 0xFF) + walk(tree, codes, lens, q, code * 2 + 1, len + 1) +end + +for t = 1, 33 do + local src = if t >= 16 and t <= 23 then 16 elseif t >= 24 and t <= 31 then 24 else t + local tree = E.TREES[src] + if tree then + local codes, lens = table.create(256, 0), table.create(256, 0) + walk(tree, codes, lens, 0, 0, 0) + -- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy) + CODE[t], LEN[t] = codes, lens + local xl = 0 + for idx = 1, 256 do + if lens[idx] > 0 then + local x = (idx - 1) // 16 + if x + 1 > xl then + xl = x + 1 + end + end + end + XLEN[t] = xl + end +end +local LINBITS = E.LINBITS +-- the tables that hold values up to m (m <= 15), smallest first +local SMALL: { [number]: { number } } = {} +for m = 0, 15 do + local list = {} + for _, t in { 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 } do + if XLEN[t] and XLEN[t] - 1 >= m then + table.insert(list, t) + end + end + SMALL[m] = list +end + +-- ------------------------------------------------------------------------------------------------ bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end +Encode3.put = put + +-- ------------------------------------------------------------------------------------------------ constants +local RATES = { + -- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long) + [44100] = { 3, 0, 5 }, + [48000] = { 3, 1, 6 }, + [32000] = { 3, 2, 7 }, + [22050] = { 2, 0, 2 }, + [24000] = { 2, 1, 3 }, + [16000] = { 2, 2, 4 }, + [11025] = { 0, 0, 0 }, + [12000] = { 0, 1, 0 }, + [8000] = { 0, 2, 1 }, +} +Encode3.RATES = RATES +local BITRATES_V1 = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 } +local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } +Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +-- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2)) +local MDCT = table.create(18 * 36, 0) +for k = 0, 17 do + for i = 0, 35 do + MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9 + end +end +-- alias reduction coefficients +local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 } +local CS, CA = table.create(8, 0), table.create(8, 0) +for i = 1, 8 do + local s = sqrt(1 + CI[i] * CI[i]) + CS[i], CA[i] = 1 / s, CI[i] / s +end + +-- ------------------------------------------------------------------------------------------------ Huffman planning +type Plan = { + bits: number, + bigValues: number, -- pairs + count1: number, -- quadruples + tables: { number }, -- 3 region tables + region0: number, + region1: number, + c1table: number, -- 0 = A (table 32), 1 = B (33) + addr1: number, -- coefficient index where region 1 starts + addr2: number, +} + +local function newPlan(): Plan + return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } +end + +-- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i) +local function pairBits(ix: { number }, a: number, b: number, t: number): number + if t == 0 then + return 0 + end + local lens = LEN[t] + local lb = LINBITS[t] + local bits = 0 + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local extra = 0 + if x > 14 then + x = 15 + extra += lb + end + if y > 14 then + y = 15 + extra += lb + end + bits += lens[x * 16 + y + 1] + extra + if x ~= 0 then + bits += 1 + end + if y ~= 0 then + bits += 1 + end + end + return bits +end + +-- the best table for the pairs ix[a .. b): table, bits +local function chooseTable(ix: { number }, a: number, b: number): (number, number) + if b <= a then + return 0, 0 + end + local m = 0 + for i = a + 1, b do + local v = ix[i] + if v > m then + m = v + end + end + if m == 0 then + return 0, 0 + end + if m <= 15 then + local best, bestBits = 0, math.huge + for _, t in SMALL[m] do + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + end + return best, bestBits + end + local need = m - 15 + local best, bestBits = 0, math.huge + for _, group in { 16, 24 } do + for t = group, group + 7 do + if POW[LINBITS[t] + 1] - 1 >= need then + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + break + end + end + end + return best, bestBits +end + +-- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list) +local function plan(ix: { number }, bounds: { number }, p: Plan) + local i = 576 + while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do + i -= 2 + end + -- count1 region: quadruples of values <= 1 + local c1 = 0 + while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do + i -= 4 + c1 += 1 + end + local bv = i -- big_values * 2 coefficients + p.bigValues, p.count1 = bv // 2, c1 + -- count1 bits, table A vs B + local ba, bb = 0, 0 + local lensA = LEN[32] + for q = 0, c1 - 1 do + local o = bv + q * 4 + local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local s = v + w + x + y + ba += lensA[v * 8 + w * 4 + x * 2 + y + 1] + s + bb += 4 + s + end + p.c1table = if bb < ba then 1 else 0 + local bits = if bb < ba then bb else ba + -- regions: region 0 / 1 / 2 split at scalefactor band boundaries + local j = 0 + while j + 1 < #bounds and bounds[j + 2] <= bv do + j += 1 + end + local r0 = math.clamp(floor((j + 1) / 3), 0, 15) + local r1 = math.clamp(floor((j + 1) / 3), 0, 7) + if r0 + r1 + 2 > 22 then + r1 = 22 - r0 - 2 + end + local a1 = math.min(bounds[r0 + 2] or 576, bv) + local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv) + p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2 + local t1, b1 = chooseTable(ix, 0, a1) + local t2, b2 = chooseTable(ix, a1, a2) + local t3, b3 = chooseTable(ix, a2, bv) + p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3 + p.bits = bits + b1 + b2 + b3 +end + +local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) + if t == 0 then + return + end + local codes, lens = CODE[t], LEN[t] + local lb = LINBITS[t] + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local cx, cy = if x > 14 then 15 else x, if y > 14 then 15 else y + local idx = cx * 16 + cy + 1 + put(w, codes[idx], lens[idx]) + if cx == 15 then + put(w, x - 15, lb) + end + if x ~= 0 then + put(w, if sign[i + 1] then 1 else 0, 1) + end + if cy == 15 then + put(w, y - 15, lb) + end + if y ~= 0 then + put(w, if sign[i + 2] then 1 else 0, 1) + end + end +end + +local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) + local bv = p.bigValues * 2 + writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) + writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) + writePairs(w, ix, sign, p.addr2, bv, p.tables[3]) + local codesA, lensA = CODE[32], LEN[32] + for q = 0, p.count1 - 1 do + local o = bv + q * 4 + local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local idx = v * 8 + ww * 4 + x * 2 + y + if p.c1table == 1 then + put(w, 15 - idx, 4) -- table B: the 4 bits inverted + else + put(w, codesA[idx + 1], lensA[idx + 1]) + end + for k = 1, 4 do + if ix[o + k] ~= 0 then + put(w, if sign[o + k] then 1 else 0, 1) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ quantization +type Unit = { + xr: { number }, -- 576 MDCT coefficients + xa: { number }, -- |xr|^(3/4) + ix: { number }, + sign: { boolean }, + plan: Plan, + gain: number, +} + +local function newUnit(): Unit + return { + xr = table.create(576, 0), + xa = table.create(576, 0), + ix = table.create(576, 0), + sign = table.create(576, false), + plan = newPlan(), + gain = 210, + } +end + +-- quantize with global gain g: false when a value overflows 8206 +local function quantize(u: Unit, g: number): boolean + local step = 2 ^ (-(g - 210) * 3 / 16) + local xa, ix = u.xa, u.ix + for i = 1, 576 do + local v = floor(xa[i] * step + 0.4054) + if v > 8206 then + return false + end + ix[i] = v + end + return true +end + +-- the finest global gain whose Huffman size fits budget bits +local function rateLoop(u: Unit, budget: number, bounds: { number }) + local xr, xa, sign = u.xr, u.xa, u.sign + local maxa = 0 + for i = 1, 576 do + local v = xr[i] + sign[i] = v < 0 + local a = math.abs(v) ^ 0.75 + xa[i] = a + if a > maxa then + maxa = a + end + end + local p = u.plan + if maxa < 1e-12 then + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + u.gain = 0 + return + end + -- the gain where the largest value quantizes to 0: an upper bound + local lo, hi = 0, 255 + local best = -1 + while lo <= hi do + local mid = (lo + hi) // 2 + if quantize(u, mid) then + plan(u.ix, bounds, p) + if p.bits <= budget then + best = mid + hi = mid - 1 + else + lo = mid + 1 + end + else + lo = mid + 1 + end + end + if best < 0 then + best = 255 + end + quantize(u, best) + plan(u.ix, bounds, p) + if p.bits > budget then -- give up on this granule: silence fits any budget + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + end + u.gain = best +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + bitrate: number, -- kbps, valid for the version + mode: string, -- "stereo" | "joint" | "mono" + prefix: buffer?, -- bytes written before the first frame (an ID3v2 tag) +} + +-- encode(src, opts) -> buffer | nil, message +function Encode3.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex, group = info[1], info[2], info[3] + local mpeg1 = version == 3 + local granules = if mpeg1 then 2 else 1 + local spf = 576 * granules + local inCh = src.channels + local mode = opts.mode + local nch = if mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17) + local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate + -- scalefactor band starts (long blocks) + local bounds = { 0 } + do + local acc = 0 + for k = 0, 21 do + acc += T.g_scf_long[group * 23 + k] + table.insert(bounds, acc) + end + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + local need = buffer.len(pf) + if need > buffer.len(w.buf) - 16 then + w.buf = buffer.create(need + 65536) + end + buffer.copy(w.buf, 0, pf, 0, need) + w.pos = need + end + local ana = { Analysis.new(), Analysis.new() } + local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1] + local cur = { table.create(576, 0), table.create(576, 0) } + local units = {} + for g = 1, 2 do + units[g] = { newUnit(), newUnit() } + end + local pcm = { table.create(spf, 0), table.create(spf, 0) } + local sub = table.create(32, 0) + local z = table.create(36, 0) + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone = false + local flushed = false + while true do + -- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay) + local got = 0 + while got < spf and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(spf - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + if inCh > 1 then + l = (l + r) * 0.5 + end + pcm[1][got + i + 1] = l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true -- one silent frame after the input pushes its tail through the filterbank delay + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, spf do + s[i] = 0 + end + end + -- analysis + MDCT per granule and channel + for g = 1, granules do + for c = 1, nch do + local cu, pv = cur[c], prev[c] + local s = pcm[c] + for k = 0, 17 do + Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1) + for sb = 0, 31 do + local v = sub[sb + 1] + if sb % 2 == 1 and k % 2 == 1 then + v = -v -- frequency inversion of the odd subbands + end + cu[sb * 18 + k + 1] = v + end + end + local xr = units[g][c].xr + for sb = 0, 31 do + local o = sb * 18 + for i = 1, 18 do + z[i] = pv[o + i] + z[i + 18] = cu[o + i] + end + for k = 0, 17 do + local acc = 0 + local mb = k * 36 + for i = 1, 36 do + acc += MDCT[mb + i] * z[i] + end + xr[o + k + 1] = acc + end + end + -- alias reduction butterflies (the inverse of the decoder's) + for sb = 1, 31 do + local o = sb * 18 + for i = 0, 7 do + local a, b = xr[o - i], xr[o + i + 1] + xr[o - i] = a * CS[i + 1] + b * CA[i + 1] + xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1] + end + end + prev[c], cur[c] = cu, pv + end + if mode == "joint" then + local x0, x1 = units[g][1].xr, units[g][2].xr + local r2 = sqrt(0.5) + for i = 1, 576 do + local l, r = x0[i], x1[i] + x0[i], x1[i] = (l + r) * r2, (l - r) * r2 + end + end + end + -- the frame size + local frameBytes = slotNum // rate + rest += slotNum % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = (frameBytes - 4 - sideBytes) * 8 + local left = avail + local nUnits = granules * nch + local done = 0 + for g = 1, granules do + for c = 1, nch do + local budget = math.min(4095, left // (nUnits - done)) + local u = units[g][c] + rateLoop(u, budget, bounds) + left -= u.plan.bits + done += 1 + end + end + -- header + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 1, 2) -- layer III + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if mode == "mono" then 3 elseif mode == "joint" then 1 else 0, 2) + put(w, if mode == "joint" then 2 else 0, 2) -- mode extension: mid / side on, intensity off + put(w, 0, 1) + put(w, 1, 1) -- original + put(w, 0, 2) + -- side info + if mpeg1 then + put(w, 0, 9) -- main_data_begin + put(w, 0, if nch == 1 then 5 else 3) + for _ = 1, nch do + put(w, 0, 4) -- scfsi + end + else + put(w, 0, 8) + put(w, 0, if nch == 1 then 1 else 2) + end + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + local p = u.plan + put(w, p.bits, 12) -- part2_3_length (no scalefactor bits) + put(w, p.bigValues, 9) + put(w, u.gain, 8) + put(w, 0, if mpeg1 then 4 else 9) -- scalefac_compress + put(w, 0, 1) -- window switching off + put(w, p.tables[1], 5) + put(w, p.tables[2], 5) + put(w, p.tables[3], 5) + put(w, p.region0, 4) + put(w, p.region1, 3) + if mpeg1 then + put(w, 0, 1) -- preflag + end + put(w, 0, 1) -- scalefac_scale + put(w, p.c1table, 1) + end + end + -- main data + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + writeHuffman(w, u.ix, u.sign, u.plan) + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + -- ancillary padding to the frame size + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode3 diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 649970d..e3bd87d 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -4,8 +4,9 @@ -- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / -- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync -- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). --- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Not supported: encoding (see the mp3 encoder in the --- audio workstream), MPEG-2 multichannel extension, CRC checks. +-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III +-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from +-- the tags. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling. -- -- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, -- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) @@ -19,6 +20,9 @@ local Header = require("@formats/audio/mp3/Header") local Index = require("@formats/audio/mp3/Index") local Tags = require("@formats/audio/mp3/Tags") local Stream = require("@formats/audio/mp3/Stream") +local Encode3 = require("@formats/audio/mp3/Encode3") +local Encode2 = require("@formats/audio/mp3/Encode2") +local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Mp3 = { @@ -26,8 +30,8 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, } -- ------------------------------------------------------------------------------------------------ types @@ -35,6 +39,13 @@ export type OpenOptions = { maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31) } export type Decoder = Stream.Decoder +export type EncodeOptions = { + layer: number?, -- 3 (MP3, default) or 2 (MP2) + bitrate: number?, -- kbps, constant (default 128 for layer III, 192 for layer II; MPEG-2 / 2.5 rates: 64 / 96) + mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II, + -- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo" + id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags) +} -- ------------------------------------------------------------------------------------------------ constants local MAX_FRAMES = 2 ^ 31 @@ -85,6 +96,115 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +local ID3_FRAMES = { + { "title", "TIT2" }, + { "artist", "TPE1" }, + { "album", "TALB" }, + { "albumArtist", "TPE2" }, + { "year", "TDRC" }, + { "date", "TDRC" }, + { "track", "TRCK" }, + { "genre", "TCON" }, + { "composer", "TCOM" }, +} + +-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write +local function id3Tag(tags: { [string]: any }): buffer? + local w = Bytes.writer(256) + local seen: { [string]: boolean } = {} + local function syncsafe(v: number) + w:u8((v // 2097152) % 128) + w:u8((v // 16384) % 128) + w:u8((v // 128) % 128) + w:u8(v % 128) + end + for _, f in ID3_FRAMES do + local v = tags[f[1]] + if type(v) == "string" and #v > 0 and not seen[f[2]] then + seen[f[2]] = true + w:string(f[2]) + syncsafe(#v + 1) + w:u16be(0) + w:u8(3) -- UTF-8 + w:string(v) + end + end + if type(tags.comment) == "string" and #tags.comment > 0 then + local v = tags.comment + w:string("COMM") + syncsafe(#v + 5) + w:u16be(0) + w:u8(3) + w:string("eng") + w:u8(0) -- empty description + w:string(v) + end + local body = w:finish() + if buffer.len(body) == 0 then + return nil + end + local out = Bytes.writer(buffer.len(body) + 10) + out:string("ID3") + out:u8(4) + out:u8(0) + out:u8(0) + local n = buffer.len(body) + out:u8((n // 2097152) % 128) + out:u8((n // 16384) % 128) + out:u8((n // 128) % 128) + out:u8(n % 128) + out:bytes(body) + return out:finish() +end + +-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err +function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local layer = o.layer or 3 + if layer ~= 2 and layer ~= 3 then + return nil, Err.new(Err.ARG, "layer must be 2 or 3") + end + local Enc = if layer == 3 then Encode3 else Encode2 + local info = Enc.RATES[src.sampleRate] + if not info then + return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate))) + end + local mpeg1 = info[1] == 3 + local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo") + if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then + return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono") + end + if src.channels > 2 then + return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels") + end + if layer == 2 and mode == "joint" then + mode = "stereo" + end + local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) + if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then + return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate)) + end + if layer == 2 and mpeg1 then + -- the standard's allowed bit rate / mode combinations + if mode == "mono" and bitrate > 192 then + return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps") + elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then + return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)") + end + end + local prefix = if o.id3 == false then nil else id3Tag(src.tags) + local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix }) + if not out then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return out, nil +end + -- ------------------------------------------------------------------------------------------------ open -- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment) local function stringTags(t: any): { [string]: string } diff --git a/tests/audio/mp3.luau b/tests/audio/mp3.luau index f973803..9d4412a 100644 --- a/tests/audio/mp3.luau +++ b/tests/audio/mp3.luau @@ -82,7 +82,7 @@ local rand = T.rng(12345) t:eq(Mp3.name, "mp3", "name") t:eq(Mp3.category, "audio", "category") t:check(table.find(Mp3.extensions, "mp3") ~= nil and table.find(Mp3.extensions, "mp2") ~= nil, "extensions") -t:check(Mp3.caps.decode and not Mp3.caps.encode and Mp3.open ~= nil, "caps") +t:check(Mp3.caps.decode and Mp3.caps.encode and Mp3.open ~= nil, "caps") -- encode: ws-audio (tests/audio/mp3_encode.luau) -- ------------------------------------------------------------------------------------------------ decode vs references for _, c in Cases do @@ -487,8 +487,8 @@ do t:check(a and a.kind == "audio" and a.frames == 22050 and a.tags.title == "Test Title", "F.audio.load: " .. tostring(err)) local dec = F.audio.open(data) t:check(dec and dec.sampleRate == 44100 and dec.frames == 22050, "F.audio.open") - local _, serr = F.save(a, nil, { format = "mp3" }) - t:check(serr and serr.code == Err.UNSUPPORTED, "F.save mp3: read-only") + local saved, serr = F.save(a, nil, { format = "mp3" }) -- the layer III encoder (ws-audio) + t:check(saved and F.audio.load(saved).sampleRate == 44100, "F.save mp3: " .. tostring(serr)) end -- ------------------------------------------------------------------------------------------------ fuzz diff --git a/tests/audio/mp3_encode.luau b/tests/audio/mp3_encode.luau new file mode 100644 index 0000000..f710cc9 --- /dev/null +++ b/tests/audio/mp3_encode.luau @@ -0,0 +1,143 @@ +-- audio/mp3 encoder tests (layer III and layer II): every fixture-step encode (sample rates of MPEG-1 / 2 / 2.5, +-- bit rates 24 .. 384 kbps, stereo / joint / mono) decodes in ffmpeg without errors and in LAME, with the expected +-- length and an SNR over a per-bit-rate floor after aligning the decoder delay; our own decoder (the minimp3 port) +-- agrees; streaming from a Decoder gives the same bytes; the ID3v2 tag round-trips; option errors. +-- Fixtures: tools/fixtures/mp3_enc.py. +local T = require("@tests/T") +local Mp3 = require("@formats/audio/mp3") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/mp3_enc") +local Sigs = require("@tests/gen/mp3_enc_sigs") + +local t = T.suite("mp3_encode") + +local function audio(name: string): Types.Audio + local s = Sigs[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + return a +end + +-- SNR of y (delayed by lag frames) against x over frames [from, to) +local function snr(x: Types.Audio, y: Types.Audio, lag: number, from: number, to: number): number + local ch = x.channels + local sig, er = 0, 0 + for i = from, to - 1 do + local j = i + lag + if j >= 0 and j < y.frames then + for c = 0, ch - 1 do + local a = buffer.readf32(x.samples, (i * ch + c) * 4) + local b = buffer.readf32(y.samples, (j * y.channels + math.min(c, y.channels - 1)) * 4) + sig += a * a + er += (a - b) * (a - b) + end + end + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end + +-- the SNR floors (dB) on the music / sine / sweep signals, by layer and bit rate per channel +local function floorFor(e: any): number + if string.find(e.name, "silence", 1, true) then + return -math.huge + elseif string.find(e.name, "noise", 1, true) then + return 8 -- white noise has no spectral structure to exploit + end + local perCh = e.bitrate / (if e.mode == "mono" then 1 else 2) + local nyquistBand = e.rate <= 16000 -- low rates lose little to the encoder's band limit + if e.layer == 3 then + if perCh >= 64 then + return 14 + elseif perCh >= 32 or nyquistBand then + return 8 + end + return 4 + end + if perCh >= 96 then + return 14 + elseif perCh >= 48 then + return 8 + end + return 4 +end + +t:check(Mp3.caps.encode and Mp3.encode ~= nil, "caps.encode") + +local minByLayer = { [2] = math.huge, [3] = math.huge } +for _, e in Enc do + t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors") + t:check(e.ffRate == e.rate, e.name .. ": rate") + t:check(e.ffChannels == (if e.mode == "mono" then 1 else 2), e.name .. ": channels") + -- the stream covers the input: the encoder adds one frame of flush and the filterbank delay + local spf = if e.layer == 3 and e.rate < 32000 then 576 else 1152 + t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 3 * spf, string.format("%s: %d decoded frames for %d", e.name, e.ffFrames, e.frames)) + local f = floorFor(e) + t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB (floor %g)", e.name, e.ffSnr, f)) + if e.lameSnr then + t:check(e.lameSnr >= f, string.format("%s: LAME SNR %.1f dB (floor %g)", e.name, e.lameSnr, f)) + end + if f > -math.huge then + minByLayer[e.layer] = math.min(minByLayer[e.layer], e.ffSnr) + end + -- our decoder agrees with ffmpeg + local x = audio(e.sig) + local y, err = Mp3.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(y, e.name .. ": our decoder: " .. tostring(err)) + if e.channels == y.channels then + local s = snr(x, y, e.ffLag, 200, x.frames) + t:check(s >= f and math.abs(s - e.ffSnr) < 3, string.format("%s: our decoder %.1f dB, ffmpeg %.1f dB", e.name, s, e.ffSnr)) + end +end +t:note("%d encodes: ffmpeg + LAME decode them; lowest SNR layer III %.1f dB, layer II %.1f dB", #Enc, minByLayer[3], minByLayer[2]) + +-- streaming, tags, defaults +do + local a = audio("music_2_44100") + local f1 = Mp3.encode(a, { bitrate = 128 }) :: buffer + local f2 = Mp3.encode(Pcm.audioDecoder(a), { bitrate = 128 }) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + a.tags = { title = "Ünïcode title", artist = "An Artist", album = "Album", track = "4", comment = "made here" } + local f3 = Mp3.encode(a, { layer = 2 }) :: buffer + t:eq(buffer.readstring(f3, 0, 3), "ID3", "an ID3v2 tag in front") + local back = Mp3.open(Bytes.reader(f3)) :: any + t:eq(back.tags.title, "Ünïcode title", "title") + t:eq(back.tags.artist, "An Artist", "artist") + t:eq(back.tags.album, "Album", "album") + t:eq(back.tags.track, "4", "track") + t:eq(back.layer, 2, "layer II by default bit rate 192") + local f4 = Mp3.encode(a, { id3 = false }) :: buffer + t:check(buffer.readu8(f4, 0) == 0xFF, "id3 = false") + local m = Types.Audio.new(22050, 1, 3000) + local fm = Mp3.encode(m) :: buffer + local dm = Mp3.open(Bytes.reader(fm)) :: any + t:check(dm.channels == 1 and dm.sampleRate == 22050, "mono MPEG-2 default") + local empty = Mp3.encode(Types.Audio.new(44100, 2, 0)) :: buffer + t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame") +end + +-- errors +do + local function code(v: any, o: any): string? + local _, e = Mp3.encode(v, o) + return e and e.code + end + local a = Types.Audio.new(44100, 2, 100) + t:eq(code({}, nil), Err.ARG, "junk") + t:eq(code(a, { layer = 1 }), Err.ARG, "layer I") + t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps") + t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode") + t:eq(code(Types.Audio.new(44000, 2, 10), nil), Err.ARG, "44 kHz") + t:eq(code(Types.Audio.new(8000, 2, 10), { layer = 2 }), Err.ARG, "layer II at 8 kHz") + t:eq(code(Types.Audio.new(44100, 3, 10), nil), Err.ARG, "3 channels") + t:eq(code(a, { layer = 2, bitrate = 32 }), Err.ARG, "layer II stereo at 32 kbps") + t:eq(code(Types.Audio.new(44100, 1, 10), { layer = 2, bitrate = 320 }), Err.ARG, "layer II mono at 320 kbps") +end + +-- (the decoder's fuzz pass is in tests/audio/mp3.luau; the encoders take no untrusted bytes) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index cf64540..01e1e5e 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -144,3 +144,19 @@ do print(string.format("%-8s %-30s %8.0fx real time", runtime, "", 10 / dt)) end end +-- mp3 / mp2 encode (ws-audio): 10 s of 44.1 kHz stereo tones +do + local M3 = require("@formats/audio/mp3") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1) + buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3) + end + for _, cfg in { { layer = 3, bitrate = 128 }, { layer = 2, bitrate = 192 } } do + local dt = bench(string.format("mp%d encode %d kbps (10 s st)", cfg.layer, cfg.bitrate), 2, n * 8, function() + M3.encode(a, cfg) + end) + print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) + end +end diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py index e9a5207..566ce86 100644 --- a/tools/fixtures/_audio.py +++ b/tools/fixtures/_audio.py @@ -133,9 +133,13 @@ def ffdecode(ctx, data, fmt=None, ext="bin", extra=None): return rate, ch, from_f32le(raw) -def snr(ref, test, ch, max_lag=0, skip=0): +def snr(ref, test, ch, max_lag=0, skip=0, hints=None): """SNR (dB) of test vs ref over their common frames (after `skip` frames), best lag in [-max_lag, max_lag] - (test[i + lag] ~ ref[i]). Returns (snr, lag).""" + (test[i + lag] ~ ref[i]). hints: lags tried first; the search runs only when none gives 10 dB. Returns (snr, lag).""" + if hints: + got = max(snr(ref, test, ch, 0, skip, None) if h == 0 else _snr_at(ref, test, ch, h, skip) for h in hints) + if got[0] >= 10: + return got best = (-1e9, 0) nref, ntest = len(ref) // ch, len(test) // ch lags = range(-max_lag, max_lag + 1) if max_lag else [0] @@ -170,6 +174,20 @@ def snr(ref, test, ch, max_lag=0, skip=0): return best +def _snr_at(ref, test, ch, lag, skip): + sig = err = 0.0 + nref, ntest = len(ref) // ch, len(test) // ch + for i in range(skip, nref): + j = i + lag + if 0 <= j < ntest: + for c in range(ch): + a = ref[i * ch + c] + e = a - test[j * ch + c] + sig += a * a + err += e * e + return (200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0), lag) + + def luau_bin(): p = shutil.which("luau") if p: diff --git a/tools/fixtures/mp3_enc.py b/tools/fixtures/mp3_enc.py new file mode 100644 index 0000000..5b95717 --- /dev/null +++ b/tools/fixtures/mp3_enc.py @@ -0,0 +1,80 @@ +# MP3 / MP2 encoder fixtures (tools/fixtures.py): our layer III and layer II encoders run in the fixture step +# (tools/fixtures/_audio.py encode_luau_many) on test signals at every MPEG sample rate group, several bit rates and +# modes; ffmpeg (mp3float / mp2float) and LAME (`lame --decode`, layer III) decode the files. Recorded per file: ffmpeg's +# error output (must be empty), the decoded frame counts, and the SNR against the input after aligning the decoder delay. +# tests/gen/mp3_enc.luau { name, sig, layer, bitrate, mode, rate, channels, frames, ffErrors, ffFrames, ffSnr, +# ffLag, lameFrames?, lameSnr?, size, data } +# tests/gen/mp3_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } } +import importlib.util, io, os, wave + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/mp3", "src/Formats/codecs/Pcm"] + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, secs, rate): + name = "%s_%d_%d" % (kind, ch, rate) + if name not in sigs: + frames = int(secs * rate) + sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=ch * 7 + rate % 97))), rate, ch) + return name + + cases = [] # name, sig, layer, bitrate, mode + for kind in ("music", "sine", "sweep"): + for br in (64, 128, 192, 320): + cases.append(("l3-%s-44k-%d-joint" % (kind, br), sig(kind, 2, 1.0, 44100), 3, br, "joint")) + cases.append(("l3-music-44k-128-stereo", sig("music", 2, 1.0, 44100), 3, 128, "stereo")) + cases.append(("l3-music-48k-160-joint", sig("music", 2, 1.0, 48000), 3, 160, "joint")) + cases.append(("l3-music-32k-96-mono", sig("music", 1, 1.0, 32000), 3, 96, "mono")) + cases.append(("l3-noise-44k-128-mono", sig("noise", 1, 0.6, 44100), 3, 128, "mono")) + cases.append(("l3-music-22k-64-joint", sig("music", 2, 1.0, 22050), 3, 64, "joint")) + cases.append(("l3-music-24k-96-stereo", sig("music", 2, 1.0, 24000), 3, 96, "stereo")) + cases.append(("l3-sweep-16k-48-mono", sig("sweep", 1, 1.0, 16000), 3, 48, "mono")) + cases.append(("l3-music-11k-32-mono", sig("music", 1, 1.0, 11025), 3, 32, "mono")) + cases.append(("l3-music-8k-24-joint", sig("music", 2, 1.0, 8000), 3, 24, "joint")) + cases.append(("l3-music-12k-64-stereo", sig("music", 2, 1.0, 12000), 3, 64, "stereo")) + cases.append(("l3-silence-44k-128", sig("silence", 2, 0.3, 44100), 3, 128, "joint")) + cases.append(("l3-loud-44k-128", sig("loud", 2, 0.5, 44100), 3, 128, "joint")) + for kind in ("music", "sine", "sweep"): + for br in (128, 192, 256, 384): + cases.append(("l2-%s-44k-%d" % (kind, br), sig(kind, 2, 1.0, 44100), 2, br, "stereo")) + cases.append(("l2-music-48k-192", sig("music", 2, 1.0, 48000), 2, 192, "stereo")) + cases.append(("l2-music-32k-mono-96", sig("music", 1, 1.0, 32000), 2, 96, "mono")) + cases.append(("l2-music-44k-mono-64", sig("music", 1, 1.0, 44100), 2, 64, "mono")) + cases.append(("l2-music-24k-96", sig("music", 2, 1.0, 24000), 2, 96, "stereo")) + cases.append(("l2-sweep-16k-mono-48", sig("sweep", 1, 1.0, 16000), 2, 48, "mono")) + cases.append(("l2-loud-44k-192", sig("loud", 2, 0.5, 44100), 2, 192, "stereo")) + + ctx.emit("mp3_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + jobs = [(c[1], '{ layer = %d, bitrate = %d, mode = "%s" }' % (c[2], c[3], c[4])) for c in cases] + outs = A.encode_luau_many(ctx, "audio/mp3", jobs, "mp3_enc_sigs") + emitted = [] + for (name, sigmod, layer, br, mode), data in zip(cases, outs): + samples, rate, ch = sigs[sigmod] + ext = "mp3" if layer == 3 else "mp2" + errs = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, ext).decode(errors="replace") + frate, fch, dec = A.ffdecode(ctx, data, ext=ext) + dch = fch + ref = samples if dch == ch else [samples[i // dch] for i in range(len(samples) // ch * dch)] + snr, lag = A.snr(ref, dec, dch, max_lag=1600, skip=200, hints=[1057 if layer == 3 else 481]) if dch == ch else (-99.0, 0) + e = {"name": name, "sig": sigmod, "layer": layer, "bitrate": br, "mode": mode, "rate": rate, "channels": ch, + "frames": len(samples) // ch, "ffErrors": errs, "ffFrames": len(dec) // max(1, fch), "ffRate": frate, + "ffChannels": fch, "ffSnr": snr, "ffLag": lag, "size": len(data), "data": data} + if layer == 3: + wavb = A.tool(ctx, "lame", ["lame", "--quiet", "--decode", "{in}", "{out}"], data, "mp3", "wav") + with wave.open(io.BytesIO(wavb)) as wf: + lch, raw = wf.getnchannels(), wf.readframes(wf.getnframes()) + lame = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw), 2)] + if lch == ch: + ls, ll = A.snr(samples, lame, ch, max_lag=1600, skip=200, hints=[1057, 528, 529]) + e["lameSnr"], e["lameLag"] = ls, ll + e["lameFrames"] = len(lame) // lch + emitted.append(e) + print(" mp3_enc: %-28s %5d bytes ffmpeg %.1f dB (lag %d)%s%s" % (name, len(data), snr, lag, + (" lame %.1f dB" % e["lameSnr"]) if "lameSnr" in e else "", (" ERR " + errs.strip()[:60]) if errs.strip() else "")) + ctx.emit("mp3_enc", emitted) From 84d45c81900a0147ed87c58913cda9129194e598 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:22:52 -0500 Subject: [PATCH 21/28] 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 22/28] 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 }, From 55e50e203d8751ab404cae6922f626070ad19a93 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:24:14 -0500 Subject: [PATCH 23/28] test.sh: skip _helper modules (tests/**/_*.luau) --- tools/test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test.sh b/tools/test.sh index 5e80063..30868d2 100644 --- a/tools/test.sh +++ b/tools/test.sh @@ -14,7 +14,7 @@ python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; } python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; } python3 -I tools/build.py || { echo "FAILED: build"; exit 1; } passed=0 -for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' | sort); do +for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' -not -name '_*' | sort); do [ -n "$1" ] && [[ "$t" != *$1* ]] && continue for rt in $RUNTIMES; do echo "== $t ($rt)" From cb05744367bf6d8fb971a8ca7168c2b8a67868c1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:29:09 -0500 Subject: [PATCH 24/28] ws-audio: Vorbis encoder (audio/vorbis/Encode: long blocks, floor 1 fit to the envelope, square-polar coupling, residue 2 with 6 classes + cascades, fixed Laplacian-Huffman codebooks, exact granules, Ogg via containers/Ogg Mux) wired into audio/vorbis encode; fixtures: ogginfo clean, oggdec exact lengths + SNR floors, ffmpeg; bench line --- docs/FORMATS.md | 2 +- src/Formats/Registry.luau | 4 +- src/Formats/audio/vorbis/Encode.luau | 825 +++++++++++++++++++++++++++ src/Formats/audio/vorbis/init.luau | 46 +- tests/audio/vorbis_encode.luau | 110 ++++ tools/bench.luau | 14 + tools/fixtures/vorbis_enc.py | 74 +++ 7 files changed, 1068 insertions(+), 7 deletions(-) create mode 100644 src/Formats/audio/vorbis/Encode.luau create mode 100644 tests/audio/vorbis_encode.luau create mode 100644 tools/fixtures/vorbis_enc.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 72cc12e..278fe8e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -13,7 +13,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | 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 | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | -| audio | vorbis | .ogg .oga | yes | - | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | +| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 0b9fbc5..8f9252f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -116,8 +116,8 @@ local list: { Entry } = { path = "audio/vorbis", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255 }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, load = function() return require("@formats/audio/vorbis") end, diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau new file mode 100644 index 0000000..f15a212 --- /dev/null +++ b/src/Formats/audio/vorbis/Encode.luau @@ -0,0 +1,825 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification +-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the +-- Vorbis window, the MDCT (codecs/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a +-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality- +-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer +-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then +-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian +-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact +-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. +local Mdct = require("@formats/codecs/Mdct") +local Ogg = require("@formats/containers/Ogg") +local Tables = require("@formats/audio/vorbis/Tables") + +local Encode = {} + +local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +local N = 2048 +local N2 = 1024 +local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch) +local MULT = 2 -- floor1 multiplier (range 128) +local RANGE = 128 +local NCLASS = 6 + +-- ------------------------------------------------------------------------------------------------ LSB-first bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function newW(size: number): W + return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } +end + +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc + v * POW[w.cnt + 1] + local cnt = w.cnt + n + local b, p = w.buf, w.pos + if p + 8 > buffer.len(b) then + local nb = buffer.create(buffer.len(b) * 2 + 64) + buffer.copy(nb, 0, b, 0, p) + b = nb + w.buf = nb + end + while cnt >= 8 do + local byte = acc % 256 + writeu8(b, p, byte) + p += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +local function finish(w: W): buffer + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out +end + +local function putString(w: W, s: string) + for i = 1, #s do + put(w, string.byte(s, i), 8) + end +end + +local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end + +-- ------------------------------------------------------------------------------------------------ codebooks +type Book = { + dims: number, + entries: number, + lengths: { number }, + codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer) + lookup: number, -- 0 or 1 + minimum: number, + delta: number, + values: number, -- lookup1 values per dimension +} + +-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) +local function huffmanLengths(w: { number }): { number } + local n = #w + local total = 0 + for i = 1, n do + total += w[i] + end + local lens = table.create(n, 0) + if n == 1 then + lens[1] = 1 + return lens + end + local minw = total * 2 ^ -20 + -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues + local order = table.create(n, 0) + for i = 1, n do + order[i] = i + end + local weight = table.create(2 * n, 0) + local parent = table.create(2 * n, 0) + for i = 1, n do + weight[i] = math.max(w[i], minw) + end + table.sort(order, function(a: number, b: number): boolean + if weight[a] ~= weight[b] then + return weight[a] < weight[b] + end + return a < b + end) + local q1, h1 = order, 1 -- leaves, ascending + local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local nextId = n + local function pop(): number + local a = if h1 <= n then q1[h1] else nil + local b = if h2 <= t2 then q2[h2] else nil + if a and (not b or weight[a] <= weight[b]) then + h1 += 1 + return a + end + h2 += 1 + return b :: number + end + for _ = 1, n - 1 do + local a = pop() + local b = pop() + nextId += 1 + weight[nextId] = weight[a] + weight[b] + parent[a], parent[b] = nextId, nextId + t2 += 1 + q2[t2] = nextId + end + for i = 1, n do + local d, x = 0, i + while parent[x] ~= 0 do + x = parent[x] + d += 1 + end + lens[i] = d + end + return lens +end + +-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +local function assign(lens: { number }): { number } + local codes = table.create(#lens, 0) + local available = table.create(33, 0) + local first = true + for i, len in lens do + if len > 0 then + local code + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer + local msb = floor(code / POW[33 - len]) + local rev = 0 + for _ = 1, len do + rev = rev * 2 + msb % 2 + msb = floor(msb / 2) + end + codes[i] = rev + end + end + return codes +end + +local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book + local w = table.create(entries, 0) + for e = 0, entries - 1 do + w[e + 1] = weight(e) + end + local lens = huffmanLengths(w) + return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } +end + +-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) +local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book + local values = 2 * h + 1 + local entries = values ^ dims + return makeBook(dims, entries, function(e: number): number + local wt = 1 + local x = e + for _ = 1, dims do + local v = x % values - h + x = x // values + wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1) + end + return wt + end, 1, -h * scale, scale, values) +end + +local BOOK_FLOOR = makeBook(1, RANGE, function(e: number): number + return exp(-e / 7) + 0.002 +end, 0, 0, 0, 0) +local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } +local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e: number): number + return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1] +end, 0, 0, 0, 0) +local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) +local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4 +local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15 +local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240 +local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840 +local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E } +local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6 +-- the books of each residue class per pass (book numbers; -1 = none) +local CLASS_BOOKS = { + { -1, -1, -1 }, + { A_BOOK, -1, -1 }, + { B_BOOK, -1, -1 }, + { C_BOOK, -1, -1 }, + { D_BOOK, C_BOOK, -1 }, + { E_BOOK, D_BOOK, C_BOOK }, +} +local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } + +-- float32_pack (spec 9.2.2) of an integer-valued x +local function float32Pack(x: number): number + local sign = if x < 0 then 2147483648 else 0 + local m = abs(x) + local e = 788 + while m >= 2097152 do + m /= 2 + e += 1 + end + return sign + e * 2097152 + floor(m) +end + +local function writeBook(w: W, b: Book) + put(w, 0x564342, 24) + put(w, b.dims, 16) + put(w, b.entries, 24) + put(w, 0, 1) -- not ordered + put(w, 0, 1) -- not sparse + for i = 1, b.entries do + put(w, b.lengths[i] - 1, 5) + end + put(w, b.lookup, 4) + if b.lookup == 1 then + put(w, float32Pack(b.minimum), 32) + put(w, float32Pack(b.delta), 32) + local vb = ilog(b.values - 1) + put(w, vb - 1, 4) + put(w, 0, 1) -- sequence_p + for j = 0, b.values - 1 do + put(w, j, vb) + end + end +end + +local function putEntry(w: W, b: Book, e: number) + put(w, b.codes[e + 1], b.lengths[e + 1]) +end + +-- ------------------------------------------------------------------------------------------------ floor posts +-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good +local POSTS: { number } = { 0, N2 } +do + local xs = {} + local seen = { [0] = true, [N2] = true } + for j = 0, 27 do + local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies + while seen[x] do + x += 1 + end + seen[x] = true + table.insert(xs, x) + end + table.sort(xs) + -- bisection order over the sorted list + local queue = { { 1, #xs } } + local qh = 1 + while qh <= #queue do + local r = queue[qh] + qh += 1 + if r[1] <= r[2] then + local m = (r[1] + r[2]) // 2 + table.insert(POSTS, xs[m]) + table.insert(queue, { r[1], m - 1 }) + table.insert(queue, { m + 1, r[2] }) + end + end +end +local NPOSTS = #POSTS -- 30 +local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions +local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x +for i = 1, NPOSTS do + SORTED[i] = i +end +table.sort(SORTED, function(a: number, b: number): boolean + return POSTS[a] < POSTS[b] +end) +local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) +for j = 3, NPOSTS do + local lo, hi = -1, 65536 + local x = POSTS[j] + for k = 1, j - 1 do + local xv = POSTS[k] + if xv > lo and xv < x then + LOW[j], lo = k, xv + end + if xv < hi and xv > x then + HIGH[j], hi = k, xv + end + end +end +-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table +local DB = table.create(RANGE, 0) +for y = 0, RANGE - 1 do + DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) +end +local function yOf(db: number): number + local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) + return math.clamp(y, 0, RANGE - 1) +end + +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = (abs(dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) +local function renderFloor(Y: { number }, used: { boolean }, F: { number }) + local lx, ly = 0, Y[1] * MULT + for q = 2, NPOSTS do + local j = SORTED[q] + if not used[j] then + continue + end + local hx, hy = POSTS[j], Y[j] * MULT + -- draw_line(lx, ly, hx, hy) + local dy = hy - ly + local adx = hx - lx + local ady = abs(dy) + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= abs(base) * adx + local x, y, err = lx, ly, 0 + local x1 = math.min(hx, N2) + if x < x1 then + F[x + 1] = Tables[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + F[x + 1] = Tables[y % 256 + 1] + x += 1 + end + end + lx, ly = hx, hy + end + for x = lx + 1, N2 do + F[x] = Tables[ly % 256 + 1] + end +end + +-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) +local function floorVal(Y: { number }, j: number): number + local lo, hi = LOW[j], HIGH[j] + local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) + local t = Y[j] + local d = t - pred + if d == 0 then + return 0 + end + local highroom = RANGE - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 } + for _, v in cands do + if v > 0 and v < RANGE then + local got + if v >= room then + got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1 + elseif v % 2 == 1 then + got = pred - (v + 1) // 2 + else + got = pred + v // 2 + end + if got == t then + return v + end + end + end + return 0 -- unreachable for t in range; fall back to the prediction +end + +-- ------------------------------------------------------------------------------------------------ headers +local function identHeader(ch: number, rate: number, nominal: number): buffer + local w = newW(64) + put(w, 1, 8) + putString(w, "vorbis") + put(w, 0, 32) + put(w, ch, 8) + put(w, rate, 32) + put(w, 0, 32) + put(w, nominal, 32) + put(w, 0, 32) + put(w, 8, 4) -- blocksize 0: 256 + put(w, 11, 4) -- blocksize 1: 2048 + put(w, 1, 1) + return finish(w) +end + +local function commentHeader(vendor: string, tags: { [string]: string }): buffer + local w = newW(256) + put(w, 3, 8) + putString(w, "vorbis") + put(w, #vendor, 32) + putString(w, 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) + put(w, #keys, 32) + for _, k in keys do + local name = if k == "track" then "TRACKNUMBER" else string.upper(k) + local s = name .. "=" .. tags[k] + put(w, #s, 32) + putString(w, s) + end + put(w, 1, 1) + return finish(w) +end + +local function setupHeader(ch: number): buffer + local w = newW(8192) + put(w, 5, 8) + putString(w, "vorbis") + -- codebooks + put(w, #BOOKS - 1, 8) + for _, b in BOOKS do + writeBook(w, b) + end + -- time domain placeholders + put(w, 0, 6) + put(w, 0, 16) + -- one floor 1 + put(w, 0, 6) + put(w, 1, 16) + put(w, FLOOR_PARTS, 5) + for _ = 1, FLOOR_PARTS do + put(w, 0, 4) -- class 0 + end + put(w, 3, 3) -- class 0: 4 dimensions + put(w, 0, 2) -- no subclasses + put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1) + put(w, MULT - 1, 2) + put(w, 10, 4) -- rangebits: x in 0 .. 1024 + for j = 3, NPOSTS do + put(w, POSTS[j], 10) + end + -- one residue 2 + put(w, 0, 6) + put(w, 2, 16) + put(w, 0, 24) -- begin + put(w, N2 * ch, 24) -- end + put(w, PSIZE_PER_CHANNEL * ch - 1, 24) + put(w, NCLASS - 1, 6) + put(w, CLASS_BOOK, 8) + for c = 1, NCLASS do + local bits = 0 + for pass = 1, 3 do + if CLASS_BOOKS[c][pass] >= 0 then + bits += POW[pass] + end + end + put(w, bits % 8, 3) + if bits >= 8 then + put(w, 1, 1) + put(w, bits // 8, 5) + else + put(w, 0, 1) + end + end + for c = 1, NCLASS do + for pass = 1, 3 do + local b = CLASS_BOOKS[c][pass] + if b >= 0 then + put(w, b, 8) + end + end + end + -- one mapping + put(w, 0, 6) + put(w, 0, 16) + put(w, 0, 1) -- one submap + if ch == 2 then + put(w, 1, 1) + put(w, 0, 8) -- one coupling step + put(w, 0, 1) -- magnitude: channel 0 + put(w, 1, 1) -- angle: channel 1 + else + put(w, 0, 1) + end + put(w, 0, 2) + put(w, 0, 8) -- submap 0: time (unused) + put(w, 0, 8) -- floor 0 + put(w, 0, 8) -- residue 0 + -- one mode: long blocks + put(w, 0, 6) + put(w, 1, 1) + put(w, 0, 16) + put(w, 0, 16) + put(w, 0, 8) + put(w, 1, 1) -- framing + return finish(w) +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + quality: number, -- -1 .. 10 + vendor: string, + serial: number, +} + +-- the residue of one partition: vectors of each pass for class c +local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) + local b = CLASS_BOOKS[c][pass] + if b < 0 then + return + end + local book = BOOKS[b + 1] + local dims, h = book.dims, (book.values - 1) // 2 + local scale = book.delta + local values = book.values + local i = 0 + while i < psize do + local e = 0 + local m = 1 + for k = 0, dims - 1 do + local x = v[o + i + k + 1] + -- the part of x this pass carries (coarse passes take the rounded multiple of their scale) + local q + if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then + q = math.clamp(floor(x / scale + 0.5), -h, h) + else + q = math.clamp(x // scale, -h, h) + end + v[o + i + k + 1] = x - q * scale + e += (q + h) * m + m *= values + end + putEntry(w, book, e) + i += dims + end +end + +function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local ch, rate = src.channels, src.sampleRate + local q = math.clamp(opts.quality, -1, 10) + local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) + local mux = Ogg.muxer({ pageSize = 4096 }) + local stream = mux:stream(opts.serial) + local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000)) + stream:packet(identHeader(ch, rate, nominal), 0, { flush = true }) + stream:packet(commentHeader(opts.vendor, src.tags), 0) + stream:packet(setupHeader(ch), 0, { flush = true }) + local plan = Mdct.new(N) :: Mdct.Plan + local win = Mdct.window("vorbis", N) :: { number } + -- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024) + local frame = table.create(ch) + for c = 1, ch do + frame[c] = table.create(N, 0) + end + local blk = table.create(N, 0) + local X = table.create(ch) + local R = table.create(ch) + for c = 1, ch do + X[c] = table.create(N2, 0) + R[c] = table.create(N2, 0) + end + local F = table.create(N2, 0) + local Y = table.create(NPOSTS, 0) + local vals = table.create(NPOSTS, 0) + local used = table.create(NPOSTS, false) + local inter = table.create(N2 * ch, 0) + local psize = PSIZE_PER_CHANNEL * ch + local npart = N2 * ch // psize + local classes = table.create(npart + 2, 0) + local total = 0 + local srcDone = false + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local k = 0 + local lastWanted = -1 -- the last packet index needed (known once the input ends) + while true do + -- shift in the next 1024 input samples (zeros past the end) + for c = 1, ch do + local fr = frame[c] + table.move(fr, N2 + 1, N, 1) + end + local got = 0 + while got < N2 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(N2 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * ch * 4 + for c = 1, ch do + frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) + end + end + got += take + pendN -= take + pendOff += take + end + for c = 1, ch do + local fr = frame[c] + for i = N2 + got + 1, N do + fr[i] = 0 + end + end + total += got + if srcDone and lastWanted < 0 then + lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) + end + -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) + -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) + -- MDCT per channel + local energy = 0 + for c = 1, ch do + local fr = frame[c] + for i = 1, N do + blk[i] = fr[i] * win[i] + end + Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N) + local xc = X[c] + for i = 1, N2 do + energy += xc[i] * xc[i] + end + end + local w = newW(2048) + put(w, 0, 1) -- audio packet + -- (one mode: 0 bits) long block, previous and next long + put(w, 1, 1) + put(w, 1, 1) + local silent = energy < 1e-18 + if silent then + for _ = 1, ch do + put(w, 0, 1) -- no floor: the channel is zero + end + else + -- the floor from the loudest channel's band energies at each post + for j = 1, NPOSTS do + local x = POSTS[j] + -- the band around x: halfway to the neighbouring posts in x order + local idx = table.find(SORTED, j) :: number + local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0 + local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1 + if hi < lo then + hi = lo + end + local e = 0 + for c = 1, ch do + local xc = X[c] + local s = 0 + for i = lo + 1, math.min(hi + 1, N2) do + s += xc[i] * xc[i] + end + s /= (hi - lo + 1) + if s > e then + e = s + end + end + local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200 + Y[j] = yOf(db) + end + -- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero + used[1], used[2] = true, true + for j = 3, NPOSTS do + local v = floorVal(Y, j) + vals[j] = v + used[j] = v ~= 0 + if v ~= 0 then + used[LOW[j]], used[HIGH[j]] = true, true + end + end + renderFloor(Y, used, F) + -- residues: X / F rounded, then coupling, then interleaving + for c = 1, ch do + local xc, rc = X[c], R[c] + for i = 1, N2 do + local v = floor(xc[i] / F[i] + 0.5) + rc[i] = math.clamp(v, -4095, 4095) + end + end + if ch == 2 then + local l, r = R[1], R[2] + for i = 1, N2 do + local a, b = l[i], r[i] + local m, an + if abs(a) > abs(b) then + m = a + an = if a > 0 then a - b else b - a + else + m = b + an = if b > 0 then a - b else b - a + end + -- keep the angle inside the books' range + l[i], r[i] = m, math.clamp(an, -4095, 4095) + end + end + for c = 1, ch do + local rc = R[c] + for i = 1, N2 do + inter[(i - 1) * ch + c] = rc[i] + end + end + -- floors + for _ = 1, ch do + put(w, 1, 1) + put(w, Y[1], 7) + put(w, Y[2], 7) + for j = 3, NPOSTS do + putEntry(w, BOOK_FLOOR, vals[j]) + end + end + -- residue classes + for p = 0, npart - 1 do + local m = 0 + for i = 1, psize do + local a = abs(inter[p * psize + i]) + if a > m then + m = a + end + end + local c = 1 + while CLASS_MAX[c] < m do + c += 1 + end + classes[p + 1] = c + end + classes[npart + 1] = 1 + for pass = 1, 3 do + for p = 0, npart - 1, 2 do + if pass == 1 then + putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit + end + writePartition(w, inter, p * psize, psize, classes[p + 1], pass) + if p + 1 < npart then + writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass) + end + end + end + end + local pk = finish(w) + local last = lastWanted >= 0 and k >= lastWanted + local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge) + stream:packet(pk, granule, if last then { eos = true } else nil) + if last then + break + end + k += 1 + end + if src.err then + return nil, tostring(src.err) + end + return mux:finish(), nil +end + +-- the codebooks (tests check the Huffman lengths are a valid prefix code) +Encode.BOOKS = BOOKS + +return Encode diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau index 79b192f..e432adf 100644 --- a/src/Formats/audio/vorbis/init.luau +++ b/src/Formats/audio/vorbis/init.luau @@ -5,8 +5,10 @@ -- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). -- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, -- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level --- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Not supported: floor 0 (Err.UNSUPPORTED, as in --- stb_vorbis; no encoder has produced it since 2000), chained streams (the first logical Vorbis stream is decoded). +-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic +-- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook +-- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since +-- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") @@ -15,6 +17,8 @@ local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Setup = require("@formats/audio/vorbis/Setup") local Packet = require("@formats/audio/vorbis/Packet") +local Encode = require("@formats/audio/vorbis/Encode") +local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Vorbis = { @@ -22,13 +26,18 @@ local Vorbis = { category = "audio", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255 }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, } export type OpenOptions = { verify: boolean?, -- check the Ogg page CRCs (default true) } +export type EncodeOptions = { + quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB + -- less at the top of the spectrum), which sets the residue's quantization step + serial: number?, -- the Ogg stream serial number (default 0x464C5541) +} -- ------------------------------------------------------------------------------------------------ constants local TAG_KEYS = { tracknumber = "track", description = "comment" } @@ -109,6 +118,35 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err. return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err +function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local q = o.quality or 3 + if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then + return nil, Err.new(Err.ARG, "quality must be -1 .. 10") + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local serial = o.serial or 0x464C5541 + if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") + end + local out, msg = Encode.encode(src :: any, { quality = q, vendor = "formats-luau Vorbis encoder", serial = serial }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream diff --git a/tests/audio/vorbis_encode.luau b/tests/audio/vorbis_encode.luau new file mode 100644 index 0000000..c85a39d --- /dev/null +++ b/tests/audio/vorbis_encode.luau @@ -0,0 +1,110 @@ +-- audio/vorbis encoder tests: every fixture-step encode (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd +-- lengths, silence) passes ogginfo, decodes in oggdec (libvorbisfile) with the exact input length and an SNR over a +-- per-quality floor, and in ffmpeg; our own decoder gives the same; the codebooks are valid prefix codes; streaming +-- from a Decoder gives the same bytes; tags round-trip; option errors. Fixtures: tools/fixtures/vorbis_enc.py. +local T = require("@tests/T") +local Vorbis = require("@formats/audio/vorbis") +local VEnc = require("@formats/audio/vorbis/Encode") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/vorbis_enc") +local Sigs = require("@tests/gen/vorbis_enc_sigs") + +local t = T.suite("vorbis_encode") + +local function audio(name: string): Types.Audio + local s = Sigs[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + return a +end +local function snr(x: Types.Audio, y: Types.Audio): number + local sig, er = 0, 0 + for i = 0, math.min(x.frames, y.frames) * x.channels - 1 do + local a = buffer.readf32(x.samples, i * 4) + local d = a - buffer.readf32(y.samples, i * 4) + sig += a * a + er += d * d + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end +local function floorFor(q: number): number + return 8 + 1.2 * math.max(q, 0) +end + +t:check(Vorbis.caps.encode and Vorbis.encode ~= nil, "caps.encode") + +-- the codebooks: Kraft sums of exactly 1 (complete prefix codes) and lengths 1 .. 24 +for i, b in VEnc.BOOKS do + local k, okLen = 0, true + for _, l in b.lengths do + k += 2 ^ -l + okLen = okLen and l >= 1 and l <= 24 + end + t:check(math.abs(k - 1) < 1e-9 and okLen, "codebook " .. (i - 1) .. ": complete prefix code") +end + +local minSnr = math.huge +for _, e in Enc do + t:eq(e.ogginfo, "", e.name .. ": ogginfo reports no warnings / errors") + t:eq(e.oggdecFrames, e.frames, e.name .. ": oggdec frames = input frames") + t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors") + local silent = string.find(e.name, "silence", 1, true) ~= nil + local f = if silent then -math.huge else floorFor(e.quality) + t:check(e.oggdecSnr >= f, string.format("%s: oggdec SNR %.1f dB (floor %.1f)", e.name, e.oggdecSnr, f)) + if e.frames >= 2048 then + -- (ffmpeg does not trim the end of a stream that fits on one Ogg page: up to a block more) + t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 1024, string.format("%s: ffmpeg frames %d", e.name, e.ffFrames)) + t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB", e.name, e.ffSnr)) + end + if not silent then + minSnr = math.min(minSnr, e.oggdecSnr) + end + -- our decoder: the same length and quality (it is sample-exact with libvorbis) + local x = audio(e.sig) + local y, err = Vorbis.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(y, e.name .. ": our decoder: " .. tostring(err)) + t:eq(y.frames, e.frames, e.name .. ": our decoder's frames") + local s = snr(x, y) + t:check(math.abs(s - e.oggdecSnr) < 0.5 or s >= 100, string.format("%s: our decoder %.1f dB, oggdec %.1f dB", e.name, s, e.oggdecSnr)) +end +t:note("%d encodes pass ogginfo / oggdec / ffmpeg; lowest SNR %.1f dB", #Enc, minSnr) + +-- streaming, tags +do + local a = audio("music_2_3000_44100") + local f1 = Vorbis.encode(a) :: buffer + local f2 = Vorbis.encode(Pcm.audioDecoder(a)) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + a.tags = { title = "Tïtle", artist = "Artist", track = "9" } + local f3 = Vorbis.encode(a, { quality = 1, serial = 77 }) :: buffer + local d = Vorbis.open(Bytes.reader(f3)) :: any + t:eq(d.tags.title, "Tïtle", "title tag") + t:eq(d.tags.track, "9", "track tag") + t:check(string.find(d.vendor, "formats-luau", 1, true) ~= nil, "vendor") + local empty = Vorbis.encode(Types.Audio.new(44100, 1, 0)) :: buffer + local e0 = Vorbis.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty input") +end + +-- errors +do + local a = Types.Audio.new(44100, 2, 10) + local function code(v: any, o: any): string? + local _, e = Vorbis.encode(v, o) + return e and e.code + end + t:eq(code("x", nil), Err.ARG, "junk") + t:eq(code(a, { quality = 11 }), Err.ARG, "quality 11") + t:eq(code(a, { quality = -2 }), Err.ARG, "quality -2") + t:eq(code(a, { serial = -1 }), Err.ARG, "serial -1") + t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate") +end + +-- (the decoder's fuzz pass is in tests/audio/vorbis.luau; the encoder takes no untrusted bytes) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 01e1e5e..71ecaf0 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -160,3 +160,17 @@ do print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) end end +-- vorbis encode (ws-audio): 10 s of 44.1 kHz stereo tones at quality 3 +do + local Vb = require("@formats/audio/vorbis") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1) + buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3) + end + local dt = bench("vorbis encode q3 (10 s st)", 2, n * 8, function() + Vb.encode(a, { quality = 3 }) + end) + print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) +end diff --git a/tools/fixtures/vorbis_enc.py b/tools/fixtures/vorbis_enc.py new file mode 100644 index 0000000..8cfc69c --- /dev/null +++ b/tools/fixtures/vorbis_enc.py @@ -0,0 +1,74 @@ +# Vorbis encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py +# encode_luau_many) on test signals (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd lengths, silence); +# oggdec (libvorbisfile) and ffmpeg decode every file, ogginfo checks the stream. Recorded per file: ogginfo's warnings +# and errors, oggdec's frame count, the SNR of oggdec's and ffmpeg's decodes against the input (no delay: the +# granules are exact). +# tests/gen/vorbis_enc.luau { name, sig, quality, rate, channels, frames, ogginfo, oggdecFrames, oggdecSnr, +# ffFrames, ffSnr, ffErrors, kbps, data } +# tests/gen/vorbis_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } } +import importlib.util, os, re + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["src/Formats/audio/vorbis", "src/Formats/codecs", "src/Formats/containers/Ogg"] + + +WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k] + + +def reorder(x): + out = [0.0] * len(x) + for i in range(0, len(x) - 5, 6): + for k in range(6): + out[i + k] = x[i + WAVE_FROM_VORBIS6[k]] + return out + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, frames, rate): + name = "%s_%d_%d_%d" % (kind, ch, frames, rate) + if name not in sigs: + sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames % 1000 + ch))), rate, ch) + return name + + cases = [] + for q in (-1, 0, 3, 6, 10): + cases.append(("music-st-44k-q%d" % q, sig("music", 2, 44100, 44100), q)) + cases.append(("sine-st-44k-q3", sig("sine", 2, 30000, 44100), 3)) + cases.append(("sweep-mono-48k-q3", sig("sweep", 1, 40000, 48000), 3)) + cases.append(("noise-mono-22k-q5", sig("noise", 1, 15000, 22050), 5)) + cases.append(("music-mono-8k-q2", sig("music", 1, 9000, 8000), 2)) + cases.append(("music-st-96k-q4", sig("music", 2, 30000, 96000), 4)) + cases.append(("music-6ch-48k-q3", sig("music", 6, 20000, 48000), 3)) + cases.append(("square-st-32k-q5", sig("square", 2, 20000, 32000), 5)) + cases.append(("loud-st-44k-q8", sig("loud", 2, 20000, 44100), 8)) + cases.append(("silence-st-44k", sig("silence", 2, 10000, 44100), 3)) + for n in (1, 100, 1024, 1025, 3000): + cases.append(("len-%d" % n, sig("music", 2, n, 44100), 3)) + ctx.emit("vorbis_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + outs = A.encode_luau_many(ctx, "audio/vorbis", [(c[1], "{ quality = %d }" % c[2]) for c in cases], "vorbis_enc_sigs") + emitted = [] + for (name, sigmod, q), data in zip(cases, outs): + samples, rate, ch = sigs[sigmod] + frames = len(samples) // ch + info = A.tool(ctx, "vorbis-tools", ["sh", "-c", "ogginfo {in} 2>&1; true"], data, "ogg").decode(errors="replace") + problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l)) + raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") + od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)] + osnr, _ = A.snr(samples, od, ch) # (oggdec -R keeps the Vorbis channel order) + ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace") + _, fch, ff = A.ffdecode(ctx, data, ext="ogg") + if ch == 6: # ffmpeg reorders to WAVE order (FL FR FC LFE RL RR); Vorbis order is FL FC FR RL RR LFE + ff = reorder(ff) + fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0) + e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems, + "oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr, + "ffErrors": ffe, "kbps": len(data) * 8 / (frames / rate) / 1000, "data": data} + emitted.append(e) + print(" vorbis_enc: %-22s %7.1f kbps oggdec %d/%d frames %.1f dB ffmpeg %.1f dB%s" % (name, e["kbps"], e["oggdecFrames"], frames, + osnr, fsnr, (" OGGINFO " + problems[:80]) if problems else "")) + ctx.emit("vorbis_enc", emitted) From 7754646a86f585a4c124ce6106814fc7b04e2ecf Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:31:34 -0500 Subject: [PATCH 25/28] ws-music: music/it read + render (IT 2.14/2.15 decompression, NNA, filters, pitch-pan, OpenMPT note-fade coding), tracker tests tightened, MOD->XM + API checks, tracker bench lines, NOTICE --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/codecs/Tracker/Player.luau | 51 ++- src/Formats/codecs/Tracker/init.luau | 15 +- src/Formats/music/it/Itsex.luau | 120 +++++++ src/Formats/music/it/init.luau | 427 +++++++++++++++++++++++++ tests/music/it.luau | 84 +++++ tests/music/mod.luau | 30 +- tests/music/s3m.luau | 2 +- tests/music/xm.luau | 2 +- tools/bench.luau | 56 ++++ tools/fixtures/_tracker.py | 4 +- tools/fixtures/it.py | 186 +++++++++++ 14 files changed, 964 insertions(+), 28 deletions(-) create mode 100644 src/Formats/music/it/Itsex.luau create mode 100644 src/Formats/music/it/init.luau create mode 100644 tests/music/it.luau create mode 100644 tools/fixtures/it.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5ddcb80..3eb4e52 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ 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` | +| music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` | | music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | | music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | | music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index b69b7e3..3fd365c 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -5,6 +5,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 | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | +| `src/Formats/codecs/Tracker/`, `src/Formats/music/{mod,s3m,xm,it}/` | written for this library from the format documents: ProTracker 2.3 effect docs, the XM specification (Mr.H / Triton) and FT2 behaviour notes, ST3 TECH.DOC (Sami Tammilehto / Future Crew), ITTECH.TXT (Jeffrey Lim); OpenMPT (libopenmpt, BSD) was used only as the reference player in the tests, and its documented playback quirks (mix levels, MOD panning, FT2 E6x / tremor / instrument behaviour) are matched | no third-party code | +| `tools/fixtures/{mod,s3m,xm,it}.py` test modules | generated by the fixture scripts (synthesized samples) | no third-party data | | `src/Formats/codecs/SoundFont/` (Synth, the zone merging in Parse) | port of TinySoundFont v0.9 (tsf.h) by Bernhard Schelling, based on SFZero by Steve Folta | MIT: [TinySoundFont-LICENSE.txt](TinySoundFont-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 65f9734..6df5929 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "it", + category = "music", + path = "music/it", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, + load = function() + return require("@formats/music/it") + end, + }, { name = "midi", category = "music", diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau index bf0742d..84d2079 100644 --- a/src/Formats/codecs/Tracker/Player.luau +++ b/src/Formats/codecs/Tracker/Player.luau @@ -102,6 +102,7 @@ local function newChannel(i: number, pan: number, vol: number): any smp = nil :: any, vol = 0, pan = pan, + basePan = pan, chanVol = vol, period = 0, target = 0, @@ -220,6 +221,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any local pan = m.channelPan[i] or 128 local cv = m.channelVolume[i] or 64 local c = newChannel(i, pan, cv) + c.basePan = pan c.muted = m.channelMute[i] or false if pan == 512 then -- surround marker c.pan = 128 @@ -238,10 +240,8 @@ end -- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at -- volume 64 on one centred channel) function Player.masterGain(m: any, fmt: number): number - if fmt == IT then - return 0.5 * (m.mixVolume or 48) / 48 - elseif fmt == S3M then - return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the master volume, 64 = 0.5 + if fmt == IT or fmt == S3M then + return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 end if fmt == XM then return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count @@ -557,16 +557,21 @@ end local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) if smp then c.vol = smp.volume - if smp.pan then - c.pan = smp.pan + end + if st.fmt == IT then + -- IT: a sample's or instrument's default panning holds for its notes; the channel panning (set by the + -- effects) comes back for the others + local p = (smp and smp.pan) or (ins and ins.pan) + c.pan = p or c.basePan + if p then c.surround = false end + elseif smp and smp.pan then + c.pan = smp.pan + c.basePan = c.pan + c.surround = false end if ins and st.fmt == IT then - if ins.pan and not (smp and smp.pan) then - c.pan = ins.pan - c.surround = false - end if ins.cutoff then c.cutoff = ins.cutoff end @@ -615,7 +620,6 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb if insIdx > 0 then local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil if valid then - local prev = c.insIdx c.insIdx = insIdx local n = if hasNote then note else c.note local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) @@ -673,6 +677,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb c.tremorOn = true c.retrigCount = 0 v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + v.patNote = note c.period, c.target, c.base = period, period, base c.note, c.realNote = note, realNote c.smp, c.smpIdx = smp, smpIdx @@ -724,6 +729,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb c.vol = vcmd - 0x10 elseif vcmd >= 0xC0 and vcmd <= 0xCF then c.pan = (vcmd - 0xC0) * 16 + c.basePan = c.pan end elseif f == IT then local v = vcmd - 1 @@ -731,6 +737,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb c.vol = v elseif v >= 128 and v <= 192 then c.pan = (v - 128) * 4 + c.basePan = c.pan c.surround = false end end @@ -748,7 +755,7 @@ local function volSlideMod(c: any, param: number) end local function tonePorta(st: any, c: any, speed: number) - if c.target == 0 or c.period == c.target then + if c.period == c.target then return end if c.period < c.target then @@ -874,6 +881,7 @@ local function fxModXm(st: any, c: any, tick: number) elseif fx == 8 then if tick == 0 then c.pan = param + c.basePan = c.pan c.surround = false end elseif fx == 0xB then @@ -935,6 +943,7 @@ local function fxModXm(st: any, c: any, tick: number) elseif x == 8 then if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it c.pan = y * 17 + c.basePan = c.pan c.surround = false end elseif x == 9 then @@ -1011,8 +1020,10 @@ local function fxModXm(st: any, c: any, tick: number) local px, py = p // 16, p % 16 if px > 0 then c.pan = min(255, c.pan + px) + c.basePan = c.pan else c.pan = max(0, c.pan - py) + c.basePan = c.pan end end elseif fx == 27 then -- R @@ -1115,10 +1126,12 @@ local function volColXm(st: any, c: any, tick: number) elseif hi == 0xD then if tick > 0 then c.pan = max(0, c.pan - lo) + c.basePan = c.pan end elseif hi == 0xE then if tick > 0 then c.pan = min(255, c.pan + lo) + c.basePan = c.pan end elseif hi == 0xF then if lo > 0 then @@ -1230,6 +1243,7 @@ local function fxS3mIt(st: any, c: any, tick: number) end end c.pan = pan64 * 4 + c.basePan = c.pan c.surround = false elseif fx == 17 then -- Q retrigger + volume change local p = mem(st, c, "mRetrig", param) @@ -1308,6 +1322,7 @@ local function fxS3mIt(st: any, c: any, tick: number) elseif x == 8 then if tick == 0 then c.pan = y * 17 + c.basePan = c.pan c.surround = false end elseif x == 9 then @@ -1382,9 +1397,11 @@ local function fxS3mIt(st: any, c: any, tick: number) if tick == 0 then if it then c.pan = param + c.basePan = c.pan c.surround = false elseif param <= 0x80 then c.pan = param * 2 + c.basePan = c.pan c.surround = false elseif param == 0xA4 then c.surround = true @@ -1753,13 +1770,13 @@ local function updateVoice(st: any, v: any) end -- panning local pan = v.pan + if it and ins and (ins.pps or 0) ~= 0 then + pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256) + end if envPan ~= 0 then local range = 128 - abs(pan - 128) pan += envPan * range / 32 end - if it and ins and (ins.pps or 0) ~= 0 then - pan += (v.note - (ins.ppc or 60) - 1) * ins.pps / 2 - end pan = clamp(pan, 0, 256) pan = clamp(128 + (pan - 128) * st.separation, 0, 256) local g = vol * st.master @@ -1854,8 +1871,8 @@ function Player.tick(st: any): number updateVoice(st, v) end end - -- frames for this tick: 2.5 / tempo seconds, rounded per tick as OpenMPT / FT2 do - local frames = floor(st.sr * 2.5 / max(1, st.tempo) + 0.5) + -- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does) + local frames = floor(st.sr * 2.5 / max(1, st.tempo)) -- advance st.tick += 1 if st.tick >= st.speed + st.fineDelay then diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/Tracker/init.luau index 8412ef1..391ea94 100644 --- a/src/Formats/codecs/Tracker/init.luau +++ b/src/Formats/codecs/Tracker/init.luau @@ -70,6 +70,7 @@ export type Envelope = { susEnd: number, carry: boolean?, filter: boolean?, + raw: any?, -- format-specific fields kept for a faithful re-save (XM) } export type Pattern = { rows: number, data: buffer } @@ -262,12 +263,14 @@ local function fixEnvelope(e: any): (any, string?) return e end -local function fixLoop(s: number, e: number, t: number, len: number): (number, number, number) - if not num(t, 0, 2) or t == 0 then +local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number) + if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then return 0, 0, 0 end - s, e = math.floor(math.clamp(s, 0, len)), math.floor(math.clamp(e, 0, len)) - if e - s < 1 then + local s: number = math.floor(math.clamp(s0, 0, len)) + local e: number = math.floor(math.clamp(e0, 0, len)) + local t: number = math.floor(t0) + if e - s < 1 or t == 0 then return 0, 0, 0 end if t == 2 and e - s < 2 then @@ -378,7 +381,7 @@ function Tracker.validate(m: any): (boolean?, Err.Err?) ins.resonance = nil end end - return true + return true, nil end -- ------------------------------------------------------------------------------------------------ rendering @@ -402,7 +405,7 @@ function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) end frames += f end - return math.min(frames, maxFrames) / sr + return math.min(frames, maxFrames) / sr, nil end local function newPlayer(self: any) diff --git a/src/Formats/music/it/Itsex.luau b/src/Formats/music/it/Itsex.luau new file mode 100644 index 0000000..3a7daca --- /dev/null +++ b/src/Formats/music/it/Itsex.luau @@ -0,0 +1,120 @@ +--!strict +--!native +-- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). +-- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of +-- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. +-- +-- Never throws: every read is bounds-checked; corrupt streams return nil, message. +local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 + +local Itsex = {} + +-- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message +function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) + local out = buffer.create(frames * 4) + local blockLen = if bits == 16 then 0x4000 else 0x8000 + local topWidth = if bits == 16 then 17 else 9 + local fetchA = if bits == 16 then 4 else 3 + local lowerB = if bits == 16 then -8 else -4 + local upperB = if bits == 16 then 7 else 3 + local scale = if bits == 16 then 1 / 32768 else 1 / 128 + local wrap = if bits == 16 then 65536 else 256 + local half = wrap // 2 + local p = off + local done = 0 + while done < frames do + if p + 2 > limit then + return nil, "compressed sample truncated" + end + local clen = readu16(buf, p) + p += 2 + local bstart = p + local bend = p + clen + if bend > limit then + return nil, "compressed block runs past the end" + end + p = bend + -- bit reader over [bstart, bend) + local bytePos = bstart + local bitBuf = 0 + local bitCount = 0 + local function readBits(n: number): number + while bitCount < n do + if bytePos >= bend then + return -1 + end + bitBuf += readu8(buf, bytePos) * 2 ^ bitCount + bytePos += 1 + bitCount += 8 + end + local v = bitBuf % 2 ^ n + bitBuf = (bitBuf - v) / 2 ^ n + bitCount -= n + return v + end + local count = math.min(blockLen, frames - done) + local width = topWidth + local d1, d2 = 0, 0 + local i = 0 + while i < count do + if width < 1 or width > topWidth then + return nil, "bad bit width" + end + local v = readBits(width) + if v < 0 then + return nil, "compressed block ends early" + end + if width < 7 then + -- method A: a marker value, then the new width in fetchA bits + if v == 2 ^ (width - 1) then + local nw = readBits(fetchA) + if nw < 0 then + return nil, "compressed block ends early" + end + nw += 1 + width = if nw < width then nw else nw + 1 + continue + end + elseif width < topWidth then + -- method B: values just below the top of the range encode the new width + local border = bit32.rshift(if bits == 16 then 0xFFFF else 0xFF, topWidth - width) + lowerB + if v > border and v <= border + (upperB - lowerB + 1) then + local nw = v - border + width = if nw < width then nw else nw + 1 + continue + end + else + -- method C: the top bit flags a width change + if v >= wrap then + width = (v + 1) % 256 + continue + end + end + -- a delta, sign-extended from its width + local x = v + if width < topWidth then + local shift = 2 ^ width + if x >= shift / 2 then + x -= shift + end + else + x = v % wrap + if x >= half then + x -= wrap + end + end + d1 = (d1 + x + half) % wrap - half + local s = d1 + if it215 then + d2 = (d2 + d1 + half) % wrap - half + s = d2 + end + writef32(out, (done + i) * 4, s * scale) + i += 1 + end + done += count + end + return out, p - off +end + +return Itsex diff --git a/src/Formats/music/it/init.luau b/src/Formats/music/it/init.luau new file mode 100644 index 0000000..d73cec0 --- /dev/null +++ b/src/Formats/music/it/init.luau @@ -0,0 +1,427 @@ +--!strict +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the +-- codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to +-- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or +-- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, +-- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo +-- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. +-- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's +-- extension chunks (plugins, extended instrument properties), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") +local Itsex = require("@formats/music/it/Itsex") + +-- ------------------------------------------------------------------------------------------------ contract +local It = { + name = "it", + category = "music", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function It.sniff(r: Bytes.Reader): number + return if r:peek(4) == "IMPM" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 82-byte envelope of a new-format instrument +local function readEnvelope(r: Bytes.Reader, kind: string): any + local flags, n = r:u8(), r:u8() + local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8() + local e = Tracker.newEnvelope() + n = math.min(n, 25) + for i = 1, 25 do + local y, x = r:i8(), r:u16le() + if i <= n then + e.ticks[i] = x + e.values[i] = if kind == "vol" then math.clamp(y, 0, 64) else math.clamp(y, -32, 32) + end + end + r:skip(1) + e.enabled = bit32.band(flags, 1) ~= 0 and n > 0 + e.loop = bit32.band(flags, 2) ~= 0 + e.sustain = bit32.band(flags, 4) ~= 0 + e.carry = bit32.band(flags, 8) ~= 0 + e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0 + e.loopStart, e.loopEnd = lb + 1, le + 1 + e.susStart, e.susEnd = sb + 1, se + 1 + return e +end + +local function readInstrument(r: Bytes.Reader, old: boolean): (any?, string?) + if r:string(4) ~= "IMPI" then + return nil, "bad instrument signature" + end + local ins = Tracker.newInstrument() + r:skip(13) + if old then + -- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512 + local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:skip(2) + ins.fadeout = r:u16le() * 2 + ins.nna = r:u8() + ins.dct = if r:u8() ~= 0 then 1 else 0 + r:skip(4) + ins.name = r:fixed(26) + r:skip(6) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + r:skip(200) + local e = Tracker.newEnvelope() + for i = 1, 25 do + local t, v = r:u8(), r:u8() + if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then + r:skip((25 - i) * 2) + break + end + table.insert(e.ticks, t) + table.insert(e.values, math.min(v, 64)) + end + e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0 + e.loop = bit32.band(flg, 2) ~= 0 + e.sustain = bit32.band(flg, 4) ~= 0 + e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1 + ins.volEnv = e + return ins + end + ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3 + ins.fadeout = math.min(r:u16le(), 1024) + ins.pps, ins.ppc = r:i8(), r:u8() + ins.globalVolume = math.min(r:u8(), 128) + local dfp = r:u8() + if dfp < 128 then + ins.pan = math.min(dfp, 64) * 4 + end + r:skip(2 + 2 + 1 + 1) + ins.name = r:fixed(26) + local ifc, ifr = r:u8(), r:u8() + if ifc >= 128 then + ins.cutoff = ifc - 128 + end + if ifr >= 128 then + ins.resonance = ifr - 128 + end + r:skip(4) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + ins.volEnv = readEnvelope(r, "vol") + ins.panEnv = readEnvelope(r, "pan") + ins.pitchEnv = readEnvelope(r, "pitch") + if r.err then + return nil, "instrument truncated" + end + return ins +end + +function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(4) ~= "IMPM" then + return nil, Err.new(Err.CORRUPT, "no IMPM signature") + end + r:skip(4) + local title = r:fixed(26) + r:skip(2) + local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local msgLen, msgOff = r:u16le(), r:u32le() + r:skip(4) + local chnPan, chnVol = {}, {} + for i = 1, 64 do + chnPan[i] = r:u8() + end + for i = 1, 64 do + chnVol[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + local orders = {} + for i = 1, ordnum do + orders[i] = r:u8() + end + local insOff, smpOff, patOff = {}, {}, {} + for i = 1, insnum do + insOff[i] = r:u32le() + end + for i = 1, smpnum do + smpOff[i] = r:u32le() + end + for i = 1, patnum do + patOff[i] = r:u32le() + end + if r.err then + return nil, r.err + end + -- channels: the highest one any pattern uses + local nch = 1 + local packed: { Bytes.Reader? } = {} + local rowsOf: { number } = {} + for p = 1, patnum do + if patOff[p] > 0 then + local pr = r:sub(patOff[p]) + local len, rows = pr:u16le(), pr:u16le() + pr:skip(4) + if pr.err or rows < 1 or rows > 1024 then + return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p]) + end + local data = pr:slice(len) + packed[p], rowsOf[p] = data, rows + -- scan for the channel count + local scan = data:sub(0) + local seen: { [number]: number } = {} + while not scan:eof() do + local cv = scan:u8() + if cv == 0 then + continue + end + local ch = (cv - 1) % 64 + nch = math.max(nch, ch + 1) + local mask = 0 + if cv >= 128 then + mask = scan:u8() + seen[ch] = mask + else + mask = seen[ch] or 0 + end + if bit32.band(mask, 1) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 2) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 4) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 8) ~= 0 then + scan:skip(2) + end + end + else + rowsOf[p] = 64 + end + end + local m = Tracker.newModule("it", nch) + m.title = title + m.speed = if speed > 0 then speed else 6 + m.tempo = if tempo >= 31 then tempo else 125 + m.globalVolume = math.min(gv, 128) + m.mixVolume = math.min(mv, 128) + m.linear = bit32.band(flags, 8) ~= 0 + m.instrumentMode = bit32.band(flags, 4) ~= 0 + m.flags.oldEffects = bit32.band(flags, 16) ~= 0 + m.flags.compatGxx = bit32.band(flags, 32) ~= 0 + local stereo = bit32.band(flags, 1) ~= 0 + for i = 1, nch do + local p = chnPan[i] + if p >= 128 then + m.channelMute[i] = true + p -= 128 + end + if not stereo then + m.channelPan[i] = 128 + elseif p == 100 then + m.channelPan[i] = 512 + else + m.channelPan[i] = math.min(p, 64) * 4 + end + m.channelVolume[i] = math.min(chnVol[i], 64) + end + for i = 1, ordnum do + if orders[i] == 255 then + break + end + table.insert(m.order, orders[i]) + end + m.meta.source = { format = "it", tracker = cwt, compatible = cmwt } + if bit32.band(special, 1) ~= 0 and msgLen > 0 then + local mr = r:sub(msgOff, msgLen) + m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") + end + -- instruments + for i = 1, insnum do + local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) + if not ins then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i]) + end + m.instruments[i] = ins + end + -- samples + local total = 0 + for i = 1, smpnum do + local h = r:sub(smpOff[i], 80) + if h:string(4) ~= "IMPS" then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i]) + end + h:skip(13) + local s = Tracker.newSample() + m.samples[i] = s + local gvl, flg, vol = h:u8(), h:u8(), h:u8() + s.name = h:fixed(26) + local cvt, dfp = h:u8(), h:u8() + local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le() + local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8() + if h.err then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i) + end + s.globalVolume = math.min(gvl, 64) + s.volume = math.min(vol, 64) + if dfp >= 128 then + s.pan = math.min(dfp - 128, 64) * 4 + end + s.c5speed = if c5 > 0 then c5 else 8363 + s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4 + local bits = if bit32.band(flg, 2) ~= 0 then 16 else 8 + local nchs = if bit32.band(flg, 4) ~= 0 then 2 else 1 + s.bits = bits + if bit32.band(flg, 1) ~= 0 and len > 0 then + len = math.min(len, 2 ^ 26) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data: buffer? = nil + if bit32.band(flg, 8) ~= 0 then + -- compressed: each channel separately + local it215 = bit32.band(cvt, 4) ~= 0 + local p = r.base + ptr + local parts = {} + for c = 1, nchs do + local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215) + if not d then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used)) + end + parts[c] = d + p += used :: number + end + if nchs == 1 then + data = parts[1] + else + local inter = buffer.create(len * 8) + for f = 0, len - 1 do + buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4)) + buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4)) + end + data = inter + end + else + local bps = bits // 8 + local avail = math.max(0, r:size() - ptr) // (bps * nchs) + len = math.min(len, avail) + data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, { + bits = bits, + signed = bit32.band(cvt, 1) ~= 0, + bigEndian = bit32.band(cvt, 2) ~= 0, + delta = bit32.band(cvt, 4) ~= 0, + channels = nchs, + planar = true, + }) + end + if data then + s.data, s.length, s.channels = data, len, nchs + if bit32.band(flg, 16) ~= 0 then + s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), if bit32.band(flg, 64) ~= 0 then 2 else 1 + end + if bit32.band(flg, 32) ~= 0 then + s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), if bit32.band(flg, 128) ~= 0 then 2 else 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(rowsOf[p], nch) + m.patterns[p] = pat + local pr = packed[p] + if pr then + local d = pat.data + local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {} + local row = 0 + while row < pat.rows and not pr:eof() do + local cv = pr:u8() + if cv == 0 then + row += 1 + continue + end + local ch = (cv - 1) % 64 + local mask = if cv >= 128 then pr:u8() else (lastMask[ch] or 0) + lastMask[ch] = mask + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if bit32.band(mask, 1) ~= 0 then + local n = pr:u8() + -- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing + note = if n < 120 then n + 1 elseif n == 255 then 255 elseif n == 254 then 254 elseif n == 246 then 253 else 0 + lastNote[ch] = note + elseif bit32.band(mask, 16) ~= 0 then + note = lastNote[ch] or 0 + end + if bit32.band(mask, 2) ~= 0 then + ins = pr:u8() + lastIns[ch] = ins + elseif bit32.band(mask, 32) ~= 0 then + ins = lastIns[ch] or 0 + end + if bit32.band(mask, 4) ~= 0 then + vol = math.min(pr:u8(), 212) + 1 + lastVol[ch] = vol + elseif bit32.band(mask, 64) ~= 0 then + vol = lastVol[ch] or 0 + end + if bit32.band(mask, 8) ~= 0 then + fx, param = pr:u8(), pr:u8() + if fx > 26 then + fx, param = 0, 0 + end + lastFx[ch], lastParam[ch] = fx, param + elseif bit32.band(mask, 128) ~= 0 then + fx, param = lastFx[ch] or 0, lastParam[ch] or 0 + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = It.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return It diff --git a/tests/music/it.luau b/tests/music/it.luau new file mode 100644 index 0000000..b06ac8b --- /dev/null +++ b/tests/music/it.luau @@ -0,0 +1,84 @@ +-- music/it tests: generated Impulse Tracker modules (tools/fixtures/it.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local It = require("@formats/music/it") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/it_cases") + +local t = T.suite("it") + +t:eq(It.name, "it", "name") +t:eq(It.category, "music", "category") +t:check(It.caps.decode and not It.caps.encode, "caps") + +local function load(data: string): any + return It.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(It.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") +end + +-- compressed samples (IT 2.14 / 2.15, 8 and 16-bit, mono and stereo) decode to exactly the uncompressed data +for _, c in Cases do + if c.plain then + local a, b = load(c.data), load(c.plain) + local same = #a.samples == #b.samples + for i, s in a.samples do + local o = b.samples[i] + same = same and s.length == o.length and s.channels == o.channels and buffer.tostring(s.data) == buffer.tostring(o.data) + end + t:check(same, c.name .. ": samples equal the uncompressed ones") + end +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = It.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/music/mod.luau b/tests/music/mod.luau index 30935ae..84500de 100644 --- a/tests/music/mod.luau +++ b/tests/music/mod.luau @@ -18,7 +18,7 @@ local function load(data: string): any return Mod.decode(Bytes.reader(buffer.fromstring(data))) end -local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } for _, c in Cases do local m, err = load(c.data) @@ -47,6 +47,34 @@ for _, c in Cases do t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") end +-- MOD -> XM: the converted module plays as long, and sounds alike (XM has no channel panning and uses FT2's NTSC +-- Amiga clock, so only the duration and the band spectrum are compared) +local Xm = require("@formats/music/xm") +for _, c in Cases do + local m = load(c.data) + local xb, xerr = Xm.encode(m) + t:check(xb, c.name .. ": mod -> xm " .. tostring(xerr)) + local x = Xm.decode(Bytes.reader(xb :: buffer)) + t:check(x and x.format == "xm" and #x.instruments == #m.samples, c.name .. ": the xm decodes") + local dec = x:render() + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, c.name .. ": xm duration") + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:check(r.spectral > 0.9, string.format("%s: xm spectrum %.3f", c.name, r.spectral)) +end + +-- through the API: load sniffs the MOD, open gives a Decoder, save converts to XM, load(as audio) renders +do + local F = require("@formats") + local m, err = F.load(Cases[1].data) + t:check(m and m.kind == "music" and m.format == "mod", "F.load: " .. tostring(err)) + local dec = F.open(Cases[1].data) + t:check(dec and dec.channels == 2 and dec.sampleRate == 44100, "F.open: a Decoder") + local xb = F.save(m, nil, { format = "xm" }) + t:check(xb and F.load(xb).format == "xm", "F.save as xm") + t:eq(F.saveString(m, { format = "mod" }), Cases[1].data, "F.saveString keeps the MOD bytes") +end + -- seek: the position after a seek and the output continuing do local m = load(Cases[1].data) diff --git a/tests/music/s3m.luau b/tests/music/s3m.luau index 989ca30..ddff1a5 100644 --- a/tests/music/s3m.luau +++ b/tests/music/s3m.luau @@ -18,7 +18,7 @@ local function load(data: string): any return S3m.decode(Bytes.reader(buffer.fromstring(data))) end -local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } for _, c in Cases do local m, err = load(c.data) diff --git a/tests/music/xm.luau b/tests/music/xm.luau index 2e47118..b117848 100644 --- a/tests/music/xm.luau +++ b/tests/music/xm.luau @@ -18,7 +18,7 @@ local function load(data: string): any return Xm.decode(Bytes.reader(buffer.fromstring(data))) end -local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } for _, c in Cases do local m, err = load(c.data) diff --git a/tools/bench.luau b/tools/bench.luau index a353be8..0304171 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -116,3 +116,59 @@ do end print(string.format("%-8s %-30s %8.2f ms %7.1f M voice-samples/s", runtime, "synth 32 voices x 2 s", best * 1000, 32 * frames / best / 1e6)) end +-- the tracker engine: 32 channels of looped samples (one note each, linear interpolation, volume ramps), and an +-- IT-style module with background voices (NNA continue) and resonant filters on every channel +do + local Tracker = require("@formats/codecs/Tracker") + local function song(format: string, filter: boolean): any + local m = Tracker.newModule(format, 32) + m.order = { 0 } + m.patterns[1] = Tracker.newPattern(64, 32) + local s = Tracker.newSample("saw") + s.length = 1000 + s.data = buffer.create(4000) + for i = 0, 999 do + buffer.writef32(s.data, i * 4, (i % 100) / 50 - 1) + end + s.loopStart, s.loopEnd, s.loopType = 0, 1000, 1 + m.samples[1] = s + if format == "it" then + local ins = Tracker.newInstrument("nna") + for n = 1, 120 do + ins.sampleMap[n] = 1 + end + ins.nna = 1 + ins.fadeout = 64 + if filter then + ins.cutoff, ins.resonance = 60, 40 + end + m.instruments[1] = ins + end + for ch = 1, 32 do + for row = 0, 63, 16 do + Tracker.setCell(m, 0, row, ch, 37 + ch + row // 16, 1, 0, 0, 0) + end + end + return m + end + local function realtime(label: string, m: any, voices: number) + local best, frames = math.huge, 0 + local out = buffer.create(4096 * 8) + for _ = 1, 3 do + local dec = Tracker.render(m) :: any + frames = 0 + local t0 = os.clock() + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime %5.1f M voice-samples/s", runtime, label, best * 1000, frames / 44100 / best, voices * frames / best / 1e6)) + end + realtime("tracker 32 ch (mod)", song("mod", false), 32) + realtime("tracker 32 ch + NNA, filters", song("it", true), 64) +end diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index 482955d..eeef247 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -305,7 +305,7 @@ def write_it(title, samples, instruments, orders, patterns, channels, speed=6, t instruments: None (sample mode) or [{name, nna, dct, dca, fadeout, gbv, pan | None, pps, ppc, ifc, ifr, keymap: [(note, sample)] * 120, volenv / panenv / pitchenv: {points [(tick, value)], loop, sustain, filter}}]; patterns: [[row: [(note, ins, vol, cmd, param)] * channels]] with note 0 = none else IT note + 1 (1 = C-0) or - 255 / 254 / 253; vol None or the raw volume byte; cmd 0 = none (A = 1).""" + 255 off / 254 cut / 253 fade (stored as 246, like IT); vol None or the raw volume byte; cmd 0 = none (A = 1).""" ins_list = instruments or [] ordn = list(orders) + [255] flags = 1 | (4 if instruments else 0) | (8 if linear else 0) | (16 if old else 0) | (32 if compat else 0) @@ -351,7 +351,7 @@ def write_it(title, samples, instruments, orders, patterns, channels, speed=6, t if mask: pk += bytes([(ch + 1) | 128, mask]) if note: - pk.append(note - 1 if note < 253 else note) + pk.append(note - 1 if note < 253 else (246 if note == 253 else note)) if ins: pk.append(ins) if vol is not None: diff --git a/tools/fixtures/it.py b/tools/fixtures/it.py new file mode 100644 index 0000000..39ae6d6 --- /dev/null +++ b/tools/fixtures/it.py @@ -0,0 +1,186 @@ +# IT fixtures (tools/fixtures.py): generated Impulse Tracker modules exercising instruments (new note actions, +# duplicate checks, envelopes, filters, sustain loops, auto-vibrato, keymaps), sample mode with the IT effects, Amiga +# slides with old effects, and IT 2.14 / 2.15 compressed, 16-bit and stereo samples, rendered by openmpt123. +# tests/gen/it_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length), plain (for "compressed": the same song uncompressed) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + +A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27) +OFF, CUT, FADE = 255, 254, 253 + + +def empty(ch, rows=64): + return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, param=0): + p[row][ch] = (note, ins, vol, cmd, param) + + +def samples(compress=None): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c5": 8363, "loop": (0, 64, False), "compress": compress}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "c5": 16726, "loop": (0, 64, False), "gv": 48}, + {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 64, "c5": 11025, "loop": (0, 128, False), + "compress": compress}, + {"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c5": 8363, "pan": 16}, + {"name": "ping sus", "data": T.s8(T.synth("tri", 400, 50, 0.8)), "volume": 64, "c5": 9000, "sus": (100, 300, True), + "loop": (0, 400, False), "vib": (8, 16, 4, 0)}, + {"name": "stereo", "data": T.s16(T.synth("sine", 256, 32, 0.6) + T.synth("saw", 256, 64, 0.5)), "bits": 16, "stereo": True, + "volume": 56, "c5": 8363, "loop": (0, 256, True), "compress": compress}, + {"name": "pluck", "data": T.s8(T.synth("saw", 3000, 40, 0.8, decay=900)), "volume": 64, "c5": 8363}, + ] + + +def keymap(sample, transpose=0, split=None): + km = [] + for n in range(120): + smp = sample if split is None or n < split[0] else split[1] + km.append((max(0, min(119, n + transpose)), smp)) + return km + + +def instruments(): + return [ + {"name": "nna cont", "nna": 1, "fadeout": 256, "keymap": keymap(7), + "volenv": {"points": [(0, 64), (10, 48), (40, 0)]}}, + {"name": "nna off", "nna": 2, "fadeout": 128, "keymap": keymap(1), + "volenv": {"points": [(0, 0), (3, 64), (8, 40), (20, 30)], "sustain": (2, 3)}}, + {"name": "nna fade dct", "nna": 3, "dct": 1, "dca": 0, "fadeout": 64, "keymap": keymap(2)}, + {"name": "pan pitch", "fadeout": 512, "keymap": keymap(3, 12), "pan": 48, "pps": 16, "ppc": 60, + "panenv": {"points": [(0, -32), (16, 32), (32, -32)], "loop": (0, 2)}, + "pitchenv": {"points": [(0, 0), (10, 12), (20, -12), (30, 0)], "loop": (1, 2)}}, + {"name": "filter", "keymap": keymap(3), "ifc": 128 + 40, "ifr": 128 + 64, "fadeout": 300, + "pitchenv": {"points": [(0, -32), (30, 32), (60, -32)], "loop": (0, 2), "filter": True}}, + {"name": "sus loop", "keymap": keymap(5), "fadeout": 400, "gbv": 96}, + {"name": "split stereo", "keymap": keymap(6, 0, (60, 1)), "fadeout": 200, + "volenv": {"points": [(0, 64), (5, 32), (10, 64), (15, 32)], "sustain": (0, 3), "loop": (1, 2)}}, + ] + + +def song_instruments(compress=None): + a, b = empty(5), empty(5) + # new note actions: continue / note off / fade, with the duplicate check cutting same-note repeats + for i, n in enumerate((61, 64, 68, 73)): + put(a, i * 4, 0, n, 1) + put(a, i * 4, 1, n - 12, 2) + put(a, 16, 1, 0, 0, None, S, 0x71) + put(a, 20, 1, 49, 2) + put(a, 22, 1, 0, 0, None, S, 0x73) + put(a, 24, 1, 56, 2) + put(a, 28, 1, OFF) + for r in (0, 4, 8, 9, 12, 16): + put(a, r, 2, 61 if r != 12 else 64, 3) + put(a, 20, 2, 0, 0, None, S, 0x70) + put(a, 24, 2, 61, 3, None, S, 0x75) + put(a, 26, 2, 66, 3) + put(a, 30, 2, FADE) + # panning / pitch envelopes, pitch-pan separation, instrument pan + put(a, 32, 0, 37, 4) + put(a, 32, 1, 61, 4) + put(a, 40, 1, 73, 4, None, S, 0x7B) + put(a, 44, 1, 0, 0, None, S, 0x7C) + put(a, 48, 0, OFF) + put(a, 56, 1, CUT) + # filters: instrument cutoff + resonance, filter envelope, Zxx + put(a, 36, 3, 49, 5) + put(a, 44, 3, 0, 0, None, Z, 0x20) + put(a, 48, 3, 0, 0, None, Z, 0x60) + put(a, 52, 3, 0, 0, None, Z, 0x88) + put(a, 60, 3, OFF) + # sustain loop + ping-pong, auto-vibrato, instrument global volume, a stereo / mono key split + put(b, 0, 0, 61, 6) + put(b, 16, 0, OFF) + put(b, 0, 1, 49, 7) + put(b, 8, 1, 73, 7) + put(b, 16, 1, 49, 7, 32) + put(b, 24, 1, OFF) + put(b, 32, 1, 85, 7) + put(b, 8, 4, 61, 1, None, H, 0x44) + put(b, 12, 4, 61, 1, None, S, 0x77) + put(b, 20, 4, 0, 0, None, S, 0x78) + put(b, 40, 4, 61, 3, 0, M, 0x20) + put(b, 44, 4, 0, 0, None, N, 0x04) + put(b, 48, 4, 0, 0, None, N, 0x30) + return T.write_it("instruments", samples(compress), instruments(), [0, 1], [a, b], 5, speed=5, tempo=135, + pans=[16, 48, 32, 32, 40], mv=64) + + +def song_effects(linear=True, old=False, compat=False): + a, b = empty(4), empty(4) + put(a, 0, 0, 61, 1, 48, D, 0x00) + put(a, 4, 0, 0, 0, 70) + put(a, 5, 0, 0, 0, 80) + put(a, 8, 0, 0, 0, 88) + put(a, 12, 0, 0, 0, 99) + put(a, 16, 0, 0, 0, 110) + put(a, 20, 0, 0, 0, 120) + put(a, 24, 0, 49, 0, 196) + put(a, 28, 0, 0, 0, 205, H, 0x46) + put(a, 32, 0, 0, 0, 160) + put(a, 36, 0, 0, 0, None, Y, 0x48) + put(a, 44, 0, 0, 0, None, P, 0x08) + put(a, 48, 0, 0, 0, None, P, 0x30) + put(a, 52, 0, 0, 0, None, P, 0xF4) + put(a, 56, 0, 0, 0, None, X, 0xC0) + put(a, 0, 1, 49, 2, None, E, 0x04) + put(a, 4, 1, 0, 0, None, F, 0x10) + put(a, 8, 1, 0, 0, None, E, 0xF8) + put(a, 9, 1, 0, 0, None, F, 0xE8) + put(a, 12, 1, 49, 2, None, G, 0x08) + put(a, 13, 1, 61, 0, None, G, 0x00) + put(a, 16, 1, 0, 0, None, E, 0x00) + put(a, 20, 1, 56, 2, None, J, 0x37) + put(a, 24, 1, 0, 0, None, U, 0x88) + put(a, 28, 1, 0, 0, None, R, 0x46) + put(a, 32, 1, 0, 0, None, I, 0x31) + put(a, 36, 1, 0, 0, None, Q, 0x84) + put(a, 40, 1, 0, 0, None, K, 0x02) + put(a, 44, 1, 49, 2, None, L, 0x20) + put(a, 48, 1, 0, 0, None, O, 0x00) + put(a, 52, 1, 61, 4, None, O, 0x04) + put(a, 56, 1, 61, 4, None, S, 0xD3) + put(a, 60, 1, 61, 4, None, S, 0xC2) + put(a, 0, 2, 37, 3, None, V, 0x60) + put(a, 8, 2, 0, 0, None, W, 0x04) + put(a, 16, 2, 0, 0, None, W, 0x60) + put(a, 24, 2, 0, 0, None, Tt, 0x10 + 0x06) + put(a, 28, 2, 0, 0, None, Tt, 0x04) + put(a, 32, 2, 0, 0, None, Tt, 0x90) + put(a, 36, 2, 0, 0, None, S, 0xB0) + put(a, 38, 2, 0, 0, None, S, 0xB1) + put(a, 40, 2, 0, 0, None, S, 0xE2) + put(a, 44, 2, 0, 0, None, S, 0x63) + put(a, 48, 2, 0, 0, None, A, 0x04) + put(a, 52, 2, 0, 0, None, M, 0x30) + put(a, 56, 2, 0, 0, None, N, 0x02) + put(a, 0, 3, 73, 7, None, S, 0x91) + put(a, 16, 3, 73, 7, None, X, 0x40) + put(a, 32, 3, 61, 3, None, S, 0x8C) + put(b, 0, 0, 61, 1) + put(b, 0, 1, 64, 2) + put(b, 0, 2, 68, 3) + put(b, 8, 0, CUT) + put(b, 12, 1, OFF) + put(b, 16, 2, FADE) + put(b, 20, 3, 61, 7, None, B, 0x01) + return T.write_it("effects", samples(), None, [0, 1], [a, b], 4, speed=4, tempo=140, linear=linear, old=old, + compat=compat, pans=[0, 64, 20, 44], vols=[64, 48, 64, 56], gv=112, mv=80) + + +def generate(ctx): + cases = [] + plain = song_instruments() + for nm, data in (("instruments", plain), ("effects", song_effects()), ("amiga old", song_effects(False, True, True)), + ("compressed 2.14", song_instruments(214)), ("compressed 2.15", song_instruments(215))): + ref = T.reference(ctx, data, "it") + c = {"name": nm, "data": data, "ref": ref, "duration": ref["duration"]} + if nm.startswith("compressed"): + c["plain"] = plain + cases.append(c) + ctx.emit("it_cases", cases) From 4b5194f34328727e35fabda4046165097fad4c31 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:32:09 -0500 Subject: [PATCH 26/28] ws-music: tracker seek / loop tests --- tests/music/mod.luau | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/music/mod.luau b/tests/music/mod.luau index 84500de..5dc59fa 100644 --- a/tests/music/mod.luau +++ b/tests/music/mod.luau @@ -84,6 +84,28 @@ do local _, n = dec:read(1000) t:eq(n, 1000, "read after seek") t:check(Tracker.duration(m) == dec.duration, "duration()") + -- the same samples as playing up to that point (after the short fade-in that follows a seek) + local a, b = m:render(), m:render() + a:seek(3.5) + local at = math.floor(3.5 * S.SR) + while at > 0 do + local _, n = b:read(math.min(at, 8192)) + at -= n + end + local x, y = a:read(4096), b:read(4096) + local worst = 0 + for i = 256, 4095 * 2 do + worst = math.max(worst, math.abs(buffer.readf32(x, i * 4) - buffer.readf32(y, i * 4))) + end + t:check(worst < 1e-4, "seek then read matches reading through (" .. worst .. ")") + -- loop = true keeps playing past the end (frames / duration still give one pass) + local l = m:render({ loop = true, sampleRate = 8000 }) + local total = 0 + for _ = 1, 30 do + local _, n = l:read(8000) + total += n + end + t:check(total == 240000 and l.duration == dec.duration, "loop plays past the end") end -- the fuzz pass: decode, and a short render of whatever decodes From ea2e171bf079f2853f03c48f81f0b6f27cfebffb Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:32:26 -0500 Subject: [PATCH 27/28] ws-music: loop test compares durations at their own rates --- tests/music/mod.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/music/mod.luau b/tests/music/mod.luau index 5dc59fa..79e8941 100644 --- a/tests/music/mod.luau +++ b/tests/music/mod.luau @@ -105,7 +105,7 @@ do local _, n = l:read(8000) total += n end - t:check(total == 240000 and l.duration == dec.duration, "loop plays past the end") + t:check(total == 240000 and math.abs(l.duration - dec.duration) < 0.01, "loop plays past the end") end -- the fuzz pass: decode, and a short render of whatever decodes From 279304ef306220d0cfe2beb85deb2bd078e95142 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:34:04 -0500 Subject: [PATCH 28/28] fixtures: tracker generators load _tracker by path (tools/fixtures/ on sys.path shadowed xml with xml.py) --- tools/fixtures/it.py | 10 ++++++++-- tools/fixtures/mod.py | 10 ++++++++-- tools/fixtures/s3m.py | 10 ++++++++-- tools/fixtures/xm.py | 10 ++++++++-- 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/tools/fixtures/it.py b/tools/fixtures/it.py index 39ae6d6..493d525 100644 --- a/tools/fixtures/it.py +++ b/tools/fixtures/it.py @@ -5,8 +5,14 @@ # duration (openmpt's song length), plain (for "compressed": the same song uncompressed) } import os, sys -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import _tracker as T # noqa: E402 +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) INPUTS = ["tools/fixtures/_tracker.py"] diff --git a/tools/fixtures/mod.py b/tools/fixtures/mod.py index 6b63f81..25b9b67 100644 --- a/tools/fixtures/mod.py +++ b/tools/fixtures/mod.py @@ -3,8 +3,14 @@ # duration (openmpt's song length) } import os, sys -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import _tracker as T # noqa: E402 +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) INPUTS = ["tools/fixtures/_tracker.py"] diff --git a/tools/fixtures/s3m.py b/tools/fixtures/s3m.py index 17ea196..d8a983e 100644 --- a/tools/fixtures/s3m.py +++ b/tools/fixtures/s3m.py @@ -3,8 +3,14 @@ # duration (openmpt's song length) } import os, sys -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import _tracker as T # noqa: E402 +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) INPUTS = ["tools/fixtures/_tracker.py"] diff --git a/tools/fixtures/xm.py b/tools/fixtures/xm.py index fd40898..812302e 100644 --- a/tools/fixtures/xm.py +++ b/tools/fixtures/xm.py @@ -4,8 +4,14 @@ # duration (openmpt's song length) } import os, sys -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import _tracker as T # noqa: E402 +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) INPUTS = ["tools/fixtures/_tracker.py"]