From 471b7636ef3fab3733fcef28117486730f06bb4a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:04:31 -0500 Subject: [PATCH] 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)