absorb: audio/flac (from flac-luau 7083d0d: native + Ogg FLAC via a direct containers/Ogg require, Types.Decoder open with read(n, out?), decode to Audio, sniff incl. ID3 + fLaC); bit-exact vs flac -d on 46 generated streams; flac + wav bench lines

This commit is contained in:
4DBug committed 2026-10-31 08:39:09 -05:00
1 parent 3fb01e655f
commit 5bda4f8cbc
11 files changed
+1875 -2

No files matched your search

+1
View File
@@ -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: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.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 | 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 | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
+1
View File
@@ -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/flac/` | flac-luau 7083d0d (same author), written from RFC 9639 | no licence chosen yet; 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
+12
View File
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "flac",
category = "audio",
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 },
load = function()
return require("@formats/audio/flac")
end,
},
{
name = "mp3",
category = "audio",
+605
View File
@@ -0,0 +1,605 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits),
-- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check.
--
-- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit
-- words without bounds checks and instead compares its position with the data end once per sample. Nothing here
-- throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code).
local readu8, readu32 = buffer.readu8, buffer.readu32
local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift,
bit32.countlz, bit32.byteswap
local floor = math.floor
local Frame = {}
Frame.PAD = 32
-- CRC-8 (poly 0x07) and CRC-16 (poly 0x8005), MSB first, init 0
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 band(c, 0x80) ~= 0 then band(bxor(lshift(c, 1), 0x07), 0xFF) else band(lshift(c, 1), 0xFF)
end
CRC8[i + 1] = c
local d = lshift(i, 8)
for _ = 1, 8 do
d = if band(d, 0x8000) ~= 0 then band(bxor(lshift(d, 1), 0x8005), 0xFFFF) else band(lshift(d, 1), 0xFFFF)
end
CRC16[i + 1] = d
end
local function crc16(b: buffer, from: number, to: number): number
local c = 0
for i = from, to - 1 do
c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1])
end
return c
end
Frame.crc16 = crc16
local POW2 = table.create(64, 0)
for i = 0, 63 do
POW2[i + 1] = 2 ^ i
end
local BLOCK = { [1] = 192, [2] = 576, [3] = 1152, [4] = 2304, [5] = 4608, [8] = 256, [9] = 512, [10] = 1024,
[11] = 2048, [12] = 4096, [13] = 8192, [14] = 16384, [15] = 32768 }
local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [6] = 22050, [7] = 24000,
[8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 }
local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 }
export type Header = {
offset: number, -- byte offset of the sync code
size: number, -- header bytes, CRC-8 included
blockSize: number,
sampleRate: number,
channels: number,
assignment: number, -- 0..7 independent, 8 left/side, 9 side/right, 10 mid/side
bps: number,
variable: boolean, -- variable block size: number is a sample number, else a frame number
number: number,
}
-- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults
-- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header.
function Frame.header(b: buffer, pos: number, len: number, si: any): Header?
if pos < 0 or pos + 6 > len then
return nil
end
if readu8(b, pos) ~= 0xFF then
return nil
end
local b1 = readu8(b, pos + 1)
if band(b1, 0xFE) ~= 0xF8 then
return nil
end
local b2 = readu8(b, pos + 2)
local b3 = readu8(b, pos + 3)
local bsCode, rCode = rshift(b2, 4), band(b2, 15)
local chCode, sCode = rshift(b3, 4), band(rshift(b3, 1), 7)
if bsCode == 0 or rCode == 15 or chCode > 10 or sCode == 3 or band(b3, 1) ~= 0 then
return nil
end
-- UTF-8-like coded number
local p = pos + 4
local x = readu8(b, p)
p += 1
local num, more
if x < 0x80 then
num, more = x, 0
elseif x >= 0xC0 and x < 0xE0 then
num, more = band(x, 0x1F), 1
elseif x >= 0xE0 and x < 0xF0 then
num, more = band(x, 0x0F), 2
elseif x >= 0xF0 and x < 0xF8 then
num, more = band(x, 0x07), 3
elseif x >= 0xF8 and x < 0xFC then
num, more = band(x, 0x03), 4
elseif x >= 0xFC and x < 0xFE then
num, more = band(x, 0x01), 5
elseif x == 0xFE then
num, more = 0, 6
else
return nil
end
for _ = 1, more do
local c = readu8(b, p)
p += 1
if band(c, 0xC0) ~= 0x80 then
return nil
end
num = num * 64 + band(c, 0x3F)
end
local variable = band(b1, 1) == 1
if not variable and more > 5 then
return nil
end
local bs = BLOCK[bsCode]
if bsCode == 6 then
bs = readu8(b, p) + 1
p += 1
elseif bsCode == 7 then
bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1
p += 2
end
local rate = RATE[rCode]
if rCode == 0 then
rate = si and si.sampleRate or 0
elseif rCode == 12 then
rate = readu8(b, p) * 1000
p += 1
elseif rCode == 13 then
rate = readu8(b, p) * 256 + readu8(b, p + 1)
p += 2
elseif rCode == 14 then
rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10
p += 2
end
local bps = BITS[sCode]
if sCode == 0 then
bps = si and si.bitsPerSample or 0
end
if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then
return nil
end
-- CRC-8 over the header
local c = 0
for i = pos, p - 1 do
c = CRC8[bxor(c, readu8(b, i)) + 1]
end
if c ~= readu8(b, p) then
return nil
end
return {
offset = pos,
size = p + 1 - pos,
blockSize = bs,
sampleRate = rate or 0,
channels = if chCode < 8 then chCode + 1 else 2,
assignment = chCode,
bps = bps,
variable = variable,
number = num,
}
end
-- The first valid header at an offset in [pos, limit)
function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header?
local lim = math.min(limit, len - 6)
if pos < 0 then
pos = 0
end
while pos < lim do
if readu8(b, pos) == 0xFF then
local b1 = readu8(b, pos + 1)
if b1 == 0xF8 or b1 == 0xF9 then
local h = Frame.header(b, pos, len, si)
if h then
return h
end
end
end
pos += 1
end
return nil
end
-- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned)
local function bits(b: buffer, p: number, n: number): number
if n == 0 then
return 0
elseif n <= 24 then
return rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - n)
end
local hi = rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - (n - 16))
local q = p + n - 16
return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16)
end
local function sbits(b: buffer, p: number, n: number): number
local v = bits(b, p, n)
if n > 0 and v >= POW2[n] then
v -= POW2[n + 1]
end
return v
end
-- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1.
local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number
local method = bits(b, p, 2)
if method > 1 then
return -1
end
local porder = bits(b, p + 2, 4)
p += 6
local pbits = if method == 0 then 4 else 5
local escape = if method == 0 then 15 else 31
local parts = POW2[porder + 1]
local psize = rshift(n, porder)
if psize * parts ~= n or psize < order then
return -1
end
local i = order + 1
for part = 0, parts - 1 do
if p > lim then
return -1
end
local k = bits(b, p, pbits)
p += pbits
local stop = (part + 1) * psize
if k == escape then
local nb = bits(b, p, 5)
p += 5
if nb == 0 then
for j = i, stop do
s[j] = 0
end
else
local half, full = POW2[nb], POW2[nb + 1]
for j = i, stop do
if p > lim then
return -1
end
local v = bits(b, p, nb)
p += nb
if v >= half then
v -= full
end
s[j] = v
end
end
elseif k <= 24 then
-- the hot loop: unary quotient + k-bit remainder, zigzag
local pk = POW2[k + 1]
local rk = 32 - k
for j = i, stop do
if p > lim then
return -1
end
local sh = band(p, 7)
local w = lshift(byteswap(readu32(b, rshift(p, 3))), sh)
local q, r
if w ~= 0 then
q = countlz(w)
local used = q + 1 + k
if used <= 32 - sh then
r = if k == 0 then 0 else rshift(lshift(w, q + 1), rk)
p += used
else
p += q + 1
r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk)
p += k
end
else
-- a long run of zeros
q = 32 - sh
p += q
while true do
if p > lim then
return -1
end
local w2 = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7))
if w2 ~= 0 then
local z = countlz(w2)
q += z
p += z + 1
break
end
local adv = 32 - band(p, 7)
q += adv
p += adv
end
r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk)
p += k
end
local u = q * pk + r
local h = floor(u * 0.5)
s[j] = if h + h == u then h else -h - 1
end
else
-- k = 25..30 (Rice2): the remainder takes two reads
local pk = POW2[k + 1]
for j = i, stop do
if p > lim then
return -1
end
local q = 0
while true do
if p > lim then
return -1
end
local w = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7))
if w ~= 0 then
local z = countlz(w)
q += z
p += z + 1
break
end
local adv = 32 - band(p, 7)
q += adv
p += adv
end
local r = bits(b, p, k)
p += k
local u = q * pk + r
local h = floor(u * 0.5)
s[j] = if h + h == u then h else -h - 1
end
end
i = stop + 1
end
return p
end
local function fixed(s: { number }, n: number, order: number)
if order == 1 then
local a = s[1]
for i = 2, n do
a += s[i]
s[i] = a
end
elseif order == 2 then
local a, c = s[2], s[1]
for i = 3, n do
local v = s[i] + 2 * a - c
s[i] = v
c = a
a = v
end
elseif order == 3 then
local a, c, d = s[3], s[2], s[1]
for i = 4, n do
local v = s[i] + 3 * a - 3 * c + d
s[i] = v
d = c
c = a
a = v
end
elseif order == 4 then
local a, c, d, e = s[4], s[3], s[2], s[1]
for i = 5, n do
local v = s[i] + 4 * a - 6 * c + 4 * d - e
s[i] = v
e = d
d = c
c = a
a = v
end
end
end
-- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12
local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number)
local div = POW2[shift + 1]
local inv = 1 / div
if order <= 4 then
local c1, c2, c3, c4 = cf[1], cf[2] or 0, cf[3] or 0, cf[4] or 0
local s1, s2, s3, s4 = s[order], s[order - 1] or 0, s[order - 2] or 0, s[order - 3] or 0
for i = order + 1, n do
local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4) * inv)
s[i] = v
s4 = s3
s3 = s2
s2 = s1
s1 = v
end
elseif order <= 8 then
local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6] or 0, cf[7] or 0, cf[8] or 0
local s1, s2, s3, s4, s5 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4]
local s6, s7, s8 = s[order - 5] or 0, s[order - 6] or 0, s[order - 7] or 0
for i = order + 1, n do
local v = s[i]
+ floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8) * inv)
s[i] = v
s8 = s7
s7 = s6
s6 = s5
s5 = s4
s4 = s3
s3 = s2
s2 = s1
s1 = v
end
elseif order <= 12 then
local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7], cf[8]
local c9, c10, c11, c12 = cf[9], cf[10] or 0, cf[11] or 0, cf[12] or 0
local s1, s2, s3, s4, s5, s6 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4], s[order - 5]
local s7, s8, s9 = s[order - 6], s[order - 7], s[order - 8]
local s10, s11, s12 = s[order - 9] or 0, s[order - 10] or 0, s[order - 11] or 0
for i = order + 1, n do
local v = s[i]
+ floor(
(
c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6
+ c7 * s7 + c8 * s8 + c9 * s9 + c10 * s10 + c11 * s11 + c12 * s12
) * inv
)
s[i] = v
s12 = s11
s11 = s10
s10 = s9
s9 = s8
s8 = s7
s7 = s6
s6 = s5
s5 = s4
s4 = s3
s3 = s2
s2 = s1
s1 = v
end
else
for i = order + 1, n do
local sum = 0
for j = 1, order do
sum += cf[j] * s[i - j]
end
s[i] += floor(sum * inv)
end
end
end
-- One subframe into s[1..n]. Returns the new bit position, or -1.
local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number
if p > lim then
return -1
end
local hdr = bits(b, p, 8)
p += 8
if hdr >= 128 then
return -1
end
local typ = rshift(hdr, 1)
local wasted = 0
if band(hdr, 1) == 1 then
-- unary count of wasted bits (minus one)
while true do
if p > lim or wasted > 32 then
return -1
end
local bit = bits(b, p, 1)
p += 1
wasted += 1
if bit == 1 then
break
end
end
bps -= wasted
if bps < 1 then
return -1
end
end
if typ == 0 then
local v = sbits(b, p, bps)
p += bps
for i = 1, n do
s[i] = v
end
elseif typ == 1 then
for i = 1, n do
if p > lim then
return -1
end
s[i] = sbits(b, p, bps)
p += bps
end
elseif typ >= 8 and typ <= 12 then
local order = typ - 8
if order > n then
return -1
end
for i = 1, order do
if p > lim then
return -1
end
s[i] = sbits(b, p, bps)
p += bps
end
p = residual(b, p, lim, s, n, order)
if p < 0 then
return -1
end
fixed(s, n, order)
elseif typ >= 32 then
local order = typ - 31
if order > n then
return -1
end
for i = 1, order do
if p > lim then
return -1
end
s[i] = sbits(b, p, bps)
p += bps
end
local prec = bits(b, p, 4) + 1
p += 4
if prec == 16 then
return -1
end
local shift = sbits(b, p, 5)
p += 5
if shift < 0 then
return -1
end
for j = 1, order do
if p > lim then
return -1
end
cf[j] = sbits(b, p, prec)
p += prec
end
for j = order + 1, 12 do
cf[j] = 0 -- the unrolled filters read up to 12 coefficients
end
p = residual(b, p, lim, s, n, order)
if p < 0 then
return -1
end
lpc(s, n, cf, order, shift)
else
return -1
end
if wasted > 0 then
local m = POW2[wasted + 1]
for i = 1, n do
s[i] *= m
end
end
return p
end
-- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize
-- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err.
function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?)
local n = h.blockSize
local lim = len * 8
local p = (h.offset + h.size) * 8
local asg = h.assignment
for c = 1, h.channels do
local bps = h.bps
if (asg == 8 and c == 2) or (asg == 9 and c == 1) or (asg == 10 and c == 2) then
bps += 1 -- the side channel
end
p = subframe(b, p, lim, chans[c], n, bps, cf)
if p < 0 then
return nil, "bad subframe"
end
end
local e = rshift(p + 7, 3) -- byte align
if e + 2 > len then
return nil, "truncated frame"
end
if checkCrc then
local want = readu8(b, e) * 256 + readu8(b, e + 1)
if crc16(b, h.offset, e) ~= want then
return nil, "crc16 mismatch"
end
end
if asg >= 8 then
local l, r = chans[1], chans[2]
if asg == 8 then
for i = 1, n do
r[i] = l[i] - r[i]
end
elseif asg == 9 then
for i = 1, n do
l[i] += r[i]
end
else
for i = 1, n do
local side = r[i]
local m = l[i] * 2 + (side % 2)
l[i] = (m + side) * 0.5
r[i] = (m - side) * 0.5
end
end
end
return e + 2, nil
end
return Frame
+220
View File
@@ -0,0 +1,220 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is
-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code).
local readu8, readu32 = buffer.readu8, buffer.readu32
local Meta = {}
local function be16(b: buffer, p: number): number
return readu8(b, p) * 256 + readu8(b, p + 1)
end
local function be24(b: buffer, p: number): number
return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2)
end
local function be32(b: buffer, p: number): number
return be16(b, p) * 65536 + be16(b, p + 2)
end
export type StreamInfo = {
minBlockSize: number,
maxBlockSize: number,
minFrameSize: number, -- 0 = unknown
maxFrameSize: number,
sampleRate: number,
channels: number,
bitsPerSample: number,
totalSamples: number, -- 0 = unknown
md5: string, -- 32 hex digits (all zero = not set)
}
export type SeekPoint = { sample: number, offset: number, samples: number }
export type Picture = {
type: number,
mime: string,
description: string,
width: number,
height: number,
depth: number,
colors: number,
offset: number, -- the image bytes are buf[offset .. offset + size - 1]
size: number,
}
export type Info = {
streamInfo: StreamInfo,
seekTable: { SeekPoint },
vendor: string,
tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; "
comments: { { key: string, value: string } }, -- every comment in order
pictures: { Picture },
firstFrame: number, -- byte offset just after the last metadata block
}
local function streamInfo(b: buffer, p: number): StreamInfo
local b12, b13 = readu8(b, p + 12), readu8(b, p + 13)
local hex = table.create(16)
for i = 0, 15 do
hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i))
end
return {
minBlockSize = be16(b, p),
maxBlockSize = be16(b, p + 2),
minFrameSize = be24(b, p + 4),
maxFrameSize = be24(b, p + 7),
sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4),
channels = bit32.band(bit32.rshift(b12, 1), 7) + 1,
bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1,
totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14),
md5 = table.concat(hex),
}
end
local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean
if p + 4 > e then
return false
end
local vl = readu32(b, p)
p += 4
if p + vl > e then
return false
end
info.vendor = buffer.readstring(b, p, vl)
p += vl
if p + 4 > e then
return false
end
local n = readu32(b, p)
p += 4
for _ = 1, n do
if p + 4 > e then
return false
end
local l = readu32(b, p)
p += 4
if p + l > e then
return false
end
local s = buffer.readstring(b, p, l)
p += l
local eq = string.find(s, "=", 1, true)
if eq then
local key, value = string.upper(string.sub(s, 1, eq - 1)), string.sub(s, eq + 1)
table.insert(info.comments, { key = key, value = value })
local old = info.tags[key]
info.tags[key] = if old then old .. "; " .. value else value
end
end
return true
end
local function picture(b: buffer, p: number, e: number): Picture?
if p + 8 > e then
return nil
end
local typ = be32(b, p)
local ml = be32(b, p + 4)
p += 8
if p + ml + 4 > e then
return nil
end
local mime = buffer.readstring(b, p, ml)
p += ml
local dl = be32(b, p)
p += 4
if p + dl + 20 > e then
return nil
end
local desc = buffer.readstring(b, p, dl)
p += dl
local pic = {
type = typ,
mime = mime,
description = desc,
width = be32(b, p),
height = be32(b, p + 4),
depth = be32(b, p + 8),
colors = be32(b, p + 12),
offset = p + 20,
size = be32(b, p + 16),
}
if pic.offset + pic.size > e then
return nil
end
return pic
end
-- Parse the metadata blocks that follow "fLaC" at pos (data ends at len)
function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?)
if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then
return nil, "Flac: no fLaC marker"
end
local info: Info = {
streamInfo = nil :: any,
seekTable = {},
vendor = "",
tags = {},
comments = {},
pictures = {},
firstFrame = 0,
}
local p = pos + 4
while true do
if p + 4 > len then
return nil, "Flac: truncated metadata"
end
local h = readu8(b, p)
local last = h >= 128
local typ = bit32.band(h, 127)
local size = be24(b, p + 1)
p += 4
local e = p + size
if e > len then
return nil, "Flac: truncated metadata block"
end
if typ == 0 then
if size < 34 then
return nil, "Flac: bad STREAMINFO"
end
info.streamInfo = streamInfo(b, p)
elseif typ == 3 then
for q = p, e - 18, 18 do
local hi = be32(b, q)
if hi ~= 0xFFFFFFFF then -- placeholder points are all ones
table.insert(info.seekTable, {
sample = hi * 4294967296 + be32(b, q + 4),
offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12),
samples = be16(b, q + 16),
})
end
end
elseif typ == 4 then
vorbisComment(b, p, e, info) -- a broken comment block leaves what was read
elseif typ == 6 then
local pic = picture(b, p, e)
if pic then
table.insert(info.pictures, pic)
end
elseif typ == 127 then
return nil, "Flac: invalid metadata block type"
end
p = e
if last then
break
end
end
if not info.streamInfo then
return nil, "Flac: no STREAMINFO"
end
local si = info.streamInfo
if si.sampleRate == 0 then
return nil, "Flac: bad STREAMINFO values"
end
info.firstFrame = p
return info, nil
end
return Meta
+383
View File
@@ -0,0 +1,383 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through
-- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table,
-- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed
-- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an
-- injected module). Nothing throws: open returns nil, message, code.
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local Frame = require("@formats/audio/flac/Frame")
local Meta = require("@formats/audio/flac/Meta")
local Stream = {}
local writef32, writei32 = buffer.writef32, buffer.writei32
type Header = any -- Frame.Header
local PAD = Frame.PAD
export type Decoder = {
sampleRate: number,
channels: number,
bitsPerSample: number,
frames: number, -- total sample frames (per channel); 0 if unknown and not found
duration: number, -- seconds
bitrate: number, -- average bits per second of the audio data
tags: { [string]: string },
comments: { { key: string, value: string } },
vendor: string,
md5: string,
seekTable: { any },
pictures: { any },
container: string, -- "flac" | "ogg"
read: (Decoder, number, buffer?) -> (buffer, number),
readInt: (Decoder, number, buffer?) -> (buffer, number),
seek: (Decoder, number) -> boolean,
seekSample: (Decoder, number) -> boolean,
position: (Decoder) -> (number, number),
}
local Dec = {}
Dec.__index = Dec
-- the sample number of a frame
local function sampleOf(self: any, h: Header): number
return if h.variable then h.number else h.number * self._nominal
end
-- a header that also matches the stream (guards the sync search against false syncs)
local function plausible(self: any, h: Header): boolean
if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then
return false
end
if self.frames > 0 and sampleOf(self, h) >= self.frames then
return false
end
return true
end
local function findFrame(self: any, pos: number, limit: number): Header?
local b, len, si = self._b, self._len, self._si
while true do
local h = Frame.find(b, pos, limit, len, si)
if not h then
return nil
end
if plausible(self, h) then
return h
end
pos = h.offset + 1
end
end
local function ensure(self: any, n: number)
if n > self._cap then
for c = 1, self.channels do
self._chans[c] = table.create(n, 0)
end
self._cap = n
end
end
-- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end.
local function decodeAt(self: any, pos: number): boolean
local b, len = self._b, self._len
while true do
local h = Frame.header(b, pos, len, self._si)
if not h or not plausible(self, h) then
h = findFrame(self, pos, len)
if not h then
self._pos = len
return false
end
end
ensure(self, h.blockSize)
local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc)
if nextPos then
local s = sampleOf(self, h)
local n = h.blockSize
if self.frames > 0 and s + n > self.frames then
n = math.max(0, self.frames - s)
end
self._pos = nextPos
self._fs = s
self._fn = n
self._cur = 0
return true
end
pos = h.offset + 1
end
end
local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number)
local ch = self.channels
local want = math.floor(tonumber(maxFrames) or 0)
if not (want >= 0) then
want = 0 -- negative or NaN
end
want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB
local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4
local out = if reuse then dst :: buffer else buffer.create(want * ch * 4)
local got = 0
local scale = 1 / 2 ^ (self.bitsPerSample - 1)
local stride = ch * 4
while got < want do
if self._cur >= self._fn then
if self._pos >= self._len or not decodeAt(self, self._pos) then
self._fs += self._cur
self._cur, self._fn = 0, 0
break
end
end
local take = math.min(want - got, self._fn - self._cur)
local from = self._cur + 1
local to = self._cur + take
for c = 1, ch do
local s = self._chans[c]
local o = (got * ch + c - 1) * 4
if asInt then
for i = from, to do
writei32(out, o, s[i])
o += stride
end
else
for i = from, to do
writef32(out, o, s[i] * scale)
o += stride
end
end
end
self._cur += take
got += take
end
if got < want and not reuse then
local short = buffer.create(got * ch * 4)
buffer.copy(short, 0, out, 0, got * ch * 4)
out = short
end
return out, got
end
-- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is
-- reused when big enough.
function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number)
return pull(self, maxFrames, false, out)
end
-- The same as interleaved i32 integer samples (bit-exact, right-aligned)
function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number)
return pull(self, maxFrames, true, out)
end
-- seconds, sample frame of the next frame read() returns
function Dec.position(self: any): (number, number)
local s = self._fs + self._cur
return s / self.sampleRate, s
end
-- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets
-- by sync search, then walks frame headers forward. Returns false if the stream has no frame there.
function Dec.seekSample(self: any, t: number): boolean
t = math.floor(tonumber(t) or 0)
if not (t >= 0) then
t = 0 -- negative or NaN
end
if self.frames > 0 and t >= self.frames then
self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0
return true
end
if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then
self._cur = t - self._fs
return true
end
local first, len = self._first, self._len
local lo, hi = first, len
for _, sp in self.seekTable do
local o = first + sp.offset
if o < len then
if sp.sample <= t then
lo = math.max(lo, o)
else
hi = math.min(hi, o)
break
end
end
end
local window = math.max(16384, 2 * self._si.maxFrameSize)
while hi - lo > window do
local mid = (lo + hi) // 2
local h = findFrame(self, mid, hi)
if h and sampleOf(self, h) <= t then
lo = h.offset
else
hi = mid
end
end
local pos = lo
while true do
local h = findFrame(self, pos, len)
if not h then
self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0
return false
end
local s = sampleOf(self, h)
if s + h.blockSize > t then
if decodeAt(self, h.offset) then
if self._fs <= t and t < self._fs + self._fn then
self._cur = t - self._fs
return true
elseif self._fs > t then
return false -- a hole in the stream: we are at the next frame
end
pos = self._pos
else
return false
end
else
pos = h.offset + h.size
end
end
end
function Dec.seek(self: any, seconds: number): boolean
return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5))
end
-- Find the total length from the last frame (when STREAMINFO does not give it)
local function scanLength(self: any): number
local len = self._len
local step = math.max(65536, 2 * self._si.maxFrameSize)
local from = len
while from > self._first do
local start = math.max(self._first, from - step)
local best: Header? = nil
local pos = start
while true do
local h = findFrame(self, pos, from)
if not h then
break
end
best = h
pos = h.offset + 1
end
if best then
local s = sampleOf(self, best)
-- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here
return s + best.blockSize
end
from = start
end
return 0
end
local function skipId3(b: buffer, base: number, len: number): number
local p = 0
while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do
local sz = 0
for i = 6, 9 do
sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127)
end
local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0
p += 10 + sz + (if footer then 10 else 0)
end
return p
end
-- opts.crc16 = false skips the per-frame CRC-16 check
function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?)
local b, len, container
if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then
local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen))
if not demux then
return nil, (err :: any).message, "CORRUPT"
end
local serial = demux:find("flac")
if not serial then
return nil, "no FLAC stream in the Ogg file", "CORRUPT"
end
-- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet)
local packets, total = {}, 0
for p in demux:packets(serial) do
local off, size = p.offset, p.size
if #packets == 0 then
if size < 13 then
return nil, "bad Ogg FLAC header", "CORRUPT"
end
off += 9
size -= 9
end
table.insert(packets, { p.data, off, size })
total += size
end
b = buffer.create(total + PAD)
local o = 0
for _, p in packets do
buffer.copy(b, o, p[1], p[2], p[3])
o += p[3]
end
len = total
container = "ogg"
else
local start = skipId3(buf, base, srcLen)
if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then
return nil, "not a FLAC file", "CORRUPT"
end
len = srcLen - start
b = buffer.create(len + PAD)
buffer.copy(b, 0, buf, base + start, len)
container = "flac"
end
local info, err = Meta.parse(b, 0, len)
if not info then
return nil, err, "CORRUPT"
end
local si = info.streamInfo
local self = setmetatable({
sampleRate = si.sampleRate,
channels = si.channels,
bitsPerSample = si.bitsPerSample,
frames = si.totalSamples,
duration = 0,
bitrate = 0,
tags = info.tags,
comments = info.comments,
vendor = info.vendor,
md5 = si.md5,
seekTable = info.seekTable,
pictures = info.pictures,
container = container,
_b = b,
_len = len,
_si = si,
_first = info.firstFrame,
_pos = info.firstFrame,
_chans = {},
_cap = 0,
_cf = table.create(32, 0),
_crc = not (opts and opts.crc16 == false),
_fs = 0,
_fn = 0,
_cur = 0,
_nominal = math.max(si.maxBlockSize, 1),
}, Dec)
ensure(self, math.max(si.maxBlockSize, 16))
local h = findFrame(self, info.firstFrame, len)
if h then
if not h.variable then
self._nominal = h.blockSize
end
end
if self.frames == 0 then
self.frames = scanLength(self)
end
self.duration = self.frames / self.sampleRate
if self.duration > 0 then
self.bitrate = (len - info.firstFrame) * 8 / self.duration
end
return self :: any, nil
end
Stream.Dec = Dec
return Stream
+131
View File
@@ -0,0 +1,131 @@
--!strict
-- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author,
-- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module.
-- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals
-- 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.
--
-- 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
-- local i32, n = dec:readInt(4096) -- bit-exact integer samples
-- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio
-- ------------------------------------------------------------------------------------------------ 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 Stream = require("@formats/audio/flac/Stream")
-- ------------------------------------------------------------------------------------------------ contract
local Flac = {
name = "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 },
}
-- ------------------------------------------------------------------------------------------------ types
export type Decoder = Stream.Decoder
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)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Flac.sniff(r: Bytes.Reader): number
local head = r:peek(4)
if head == "fLaC" then
return 1
end
if head == "OggS" then
-- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping)
local nseg = r:peekU8(26)
if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then
return 1
end
return 0
end
if string.sub(head, 1, 3) == "ID3" then
-- an ID3v2 tag, then fLaC (mp3 files start with ID3 too)
local sz = 0
for i = 6, 9 do
local v = r:peekU8(i)
if v < 0 then
return 0
end
sz = sz * 128 + bit32.band(v, 127)
end
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
return if r:peek(4, 10 + sz + (if footer then 10 else 0)) == "fLaC" then 1 else 0
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Flac.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
local ch = d.channels
local parts, total = {}, 0
if d.frames > 0 then
local out, n = d:read(d.frames)
table.insert(parts, out)
total = n
end
while true do -- frames past what STREAMINFO / the scan said
local out, n = d:read(65536)
if n == 0 then
break
end
table.insert(parts, out)
total += n
if total > limit then
return nil, Err.new(Err.LIMIT, "stream over the frame limit")
end
end
local a = Types.Audio.new(d.sampleRate, ch, total)
local o = 0
for _, p in parts do
local n = math.min(buffer.len(p), total * ch * 4 - o)
buffer.copy(a.samples, o, p, 0, n)
o += n
end
a.tags = d.tags
a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts)
if not dec then
return nil, Err.new(code or Err.CORRUPT, tostring(msg))
end
return dec, nil
end
-- ------------------------------------------------------------------------------------------------ extras
Flac.Stream = Stream
Flac.Ogg = Ogg
return Flac
+203
View File
@@ -0,0 +1,203 @@
-- audio/flac tests: every fixture from tools/fixtures/flac.py (flac 0-8, 4-32 bits, 1-6 channels, odd rates and block
-- sizes, LPC order 32, wasted bits, every stereo mode, ffmpeg's encoder, Ogg FLAC, ID3v2 in front) decoded bit-exact
-- against `flac -d`; sample-accurate seeking; f32 scaling and output reuse; decode() to an Audio from a sub-range
-- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass.
-- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py.
local T = require("@tests/T")
local Flac = require("@formats/audio/flac")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local F = require("@formats")
local Cases = require("@tests/gen/flac_cases")
local t = T.suite("flac")
local function open(b: any, opts: any?): (any, any)
return Flac.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts)
end
local byName = {}
for _, c in Cases do
byName[c.name] = c
end
t:eq(Flac.name, "flac", "name")
t:check(Flac.caps.decode and not Flac.caps.encode, "caps")
local seekChecks = 0
for _, fx in Cases do
local name = fx.name
local dec, err = open(fx.data)
t:check(dec, name .. ": open: " .. tostring(err))
t:check(dec.sampleRate == fx.rate and dec.channels == fx.channels and dec.bitsPerSample == fx.bps, name .. ": format")
t:eq(dec.frames, fx.frames, name .. ": frames")
t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration")
t:eq(dec.container, if fx.ogg then "ogg" else "flac", name .. ": container")
local ch = dec.channels
local all = table.create(fx.frames * ch, 0)
local crc, n, k = 0, 0, 0
local sizes = { 4096, 1, 777, 10000, 3 }
while true do
k += 1
local out, got = dec:readInt(sizes[k % #sizes + 1])
if got == 0 then
break
end
crc = Crc32.of(out, 0, got * ch * 4, crc)
for i = 0, got * ch - 1 do
all[n * ch + i + 1] = buffer.readi32(out, i * 4)
end
n += got
end
t:eq(n, fx.frames, name .. ": decoded frames")
t:eq(crc, fx.crc, name .. ": samples identical to flac -d")
t:eq(select(2, dec:position()), fx.frames, name .. ": position at end")
-- f32 scaling, output reuse
dec:seekSample(0)
local reuse = buffer.create(100 * ch * 4)
local f, gotf = dec:read(100, reuse)
t:check(f == reuse, name .. ": output buffer reused")
local scale = 2 ^ (fx.bps - 1)
local bad = 0
for i = 0, math.min(gotf, 100) * ch - 1 do
if math.abs(buffer.readf32(f, i * 4) - all[i + 1] / scale) >= 1e-7 then
bad += 1
end
end
t:eq(bad, 0, name .. ": f32 samples")
-- seeking
local rand = T.rng(99)
local targets = { 0, 1, fx.frames - 1, fx.frames // 2, 4096, 4095, 4097, 1152, 1151 }
for _ = 1, 12 do
table.insert(targets, rand(fx.frames))
end
for _, s in targets do
if s >= 0 and s < fx.frames then
t:check(dec:seekSample(s), name .. ": seek " .. s)
t:eq(select(2, dec:position()), s, name .. ": position after seek " .. s)
local out, got = dec:readInt(50)
t:eq(got, math.min(50, fx.frames - s), name .. ": read after seek")
local diff = 0
for i = 0, got * ch - 1 do
if buffer.readi32(out, i * 4) ~= all[s * ch + i + 1] then
diff += 1
end
end
t:eq(diff, 0, name .. ": samples after seek " .. s)
seekChecks += 1
end
end
dec:seek(dec.duration / 3)
local _, pos = dec:position()
t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds")
dec:seek(dec.duration + 5)
t:eq(select(2, dec:read(10)), 0, name .. ": read past the end")
for key, v in fx.tags or {} do
t:eq(dec.tags[key], v, name .. ": tag " .. key)
end
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff")
end
t:note("%d fixtures bit-exact against flac -d, %d seeks", #Cases, seekChecks)
-- decode() from a sub-range Reader
for _, name in { "s16_l5", "ogg_s16", "id3", "s24_96k" } do
local fx = byName[name]
local big = buffer.create(#fx.data + 13)
buffer.writestring(big, 6, fx.data)
local a, err = Flac.decode(Bytes.reader(big, 6, #fx.data))
t:check(a and a.kind == "audio" and a.frames == fx.frames and a.channels == fx.channels, name .. ": decode: " .. tostring(err))
local d = open(fx.data)
local ref = d:read(fx.frames)
t:check(buffer.tostring(ref) == buffer.tostring(a.samples), name .. ": decode = read")
t:eq(a.meta.source.bitDepth, fx.bps, name .. ": meta.source")
end
-- tags and pictures
do
local dec = open(byName.s16_noseek.data)
t:check(#dec.pictures == 1 and dec.pictures[1].mime == "image/png" and dec.pictures[1].width == 1, "picture")
t:eq(#dec.seekTable, 0, "no seek table")
t:check(string.find(dec.vendor, "reference libFLAC", 1, true), "vendor")
t:eq(#dec.md5, 32, "md5")
end
-- STREAMINFO without a total length: found from the last frame
for _, name in { "s16_l5", "varblock", "bs17" } do
local fx = byName[name]
local b = buffer.fromstring(fx.data)
buffer.writeu8(b, 8 + 13, bit32.band(buffer.readu8(b, 8 + 13), 0xF0))
buffer.writeu32(b, 8 + 14, 0)
local dec = open(b)
t:check(dec and dec.frames == fx.frames, name .. ": length from the last frame")
local crc, n = 0, 0
while true do
local out, got = dec:readInt(5000)
if got == 0 then
break
end
crc = Crc32.of(out, 0, got * dec.channels * 4, crc)
n += got
end
t:check(n == fx.frames and crc == fx.crc, name .. ": decode without total length")
end
-- sniff, errors, the api
do
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xxfLaC"))), 1, "sniff ID3 + fLaC")
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xx\255\251"))), 0, "sniff ID3 + mp3")
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF")
local _, e1 = open("fLaC")
t:check(e1 and Err.is(e1), "no metadata: " .. tostring(e1))
local _, e2 = open(buffer.create(0))
t:check(e2 and e2.code == Err.CORRUPT, "empty")
local fx = byName.ogg_s16
t:eq(F.detect(fx.data), "flac", "F.detect Ogg FLAC")
local a = F.audio.load(fx.data)
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))
end
-- a damaged frame is dropped, the rest decodes
do
local src = buffer.fromstring(byName.s16_l5.data)
local len = buffer.len(src)
buffer.writeu8(src, len // 2, bit32.bxor(buffer.readu8(src, len // 2), 0x55))
local d = open(src)
local total = 0
while true do
local _, got = d:read(4096)
if got == 0 then
break
end
total += got
end
t:check(total < d.frames and total >= d.frames - 2 * 4096, "one damaged frame dropped: " .. total)
end
-- fuzz
local samples = {}
for _, name in { "s16_l5", "ogg_s16", "id3", "varblock", "s32_rice2", "u8_mono", "bits4" } do
table.insert(samples, byName[name].data)
end
t:fuzz("open + read + seek", function(b: buffer)
local d = Flac.open(Bytes.reader(b))
if d then
local guard = 0
while select(2, d:read(4096)) > 0 and guard < 200 do
guard += 1
end
d:seek(0.1)
d:read(100)
d:seekSample(d.frames // 2)
d:read(100)
end
return d
end, samples, { mutations = 12, keepHeader = 42 })
t:fuzz("decode", function(b: buffer)
return Flac.decode(Bytes.reader(b))
end, samples, { mutations = 6, garbage = 60 })
t:done()
+32 -1
View File
@@ -1,6 +1,7 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time).
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone.
local Deflate = require("@formats/codecs/Deflate")
local Crc32 = require("@formats/core/Crc32")
local Bytes = require("@formats/core/Bytes")
@@ -13,6 +14,10 @@ local Opus = require("@formats/audio/opus")
local OpusCelt = require("@tests/gen/opus_celt_st_128")
local OpusSilk = require("@tests/gen/opus_silk_wb_st")
local OpusHybrid = require("@tests/gen/opus_hybrid_st")
local Flac = require("@formats/audio/flac")
local FC = require("@tests/gen/flac_cases")
local Wav = require("@formats/audio/wav")
local Types = require("@formats/Types")
local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau"
@@ -84,3 +89,29 @@ for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", Op
Opus.decode(Bytes.reader(b))
end)
end
for _, name in { "s16_long", "s24_96k" } do
for _, c in FC do
if c.name == name then
local b = buffer.fromstring(c.data)
local dec = assert(Flac.open(Bytes.reader(b)))
local secs = dec.duration
local dt = bench("flac decode " .. name, 5, dec.frames * dec.channels * 4, function()
Flac.decode(Bytes.reader(b))
end)
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt))
end
end
end
do
local a = Types.Audio.new(44100, 2, 44100 * 10)
for i = 0, 44100 * 20 - 1 do
buffer.writef32(a.samples, i * 4, math.sin(i * 0.01) * 0.5)
end
bench("wav encode s16 (10 s stereo)", 5, buffer.len(a.samples), function()
Wav.encode(a)
end)
local file = assert(Wav.encode(a))
bench("wav decode s16 (10 s stereo)", 5, buffer.len(a.samples), function()
Wav.decode(Bytes.reader(file))
end)
end
+1 -1
View File
@@ -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 flac > /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
+286
View File
@@ -0,0 +1,286 @@
# FLAC fixtures (tools/fixtures.py): audio/flac. Ported from flac-luau tools/gen_fixtures.py.
# tests/gen/flac_cases.luau streams from the reference encoder (flac 0-8, 4-32 bits, 1-6 channels, odd rates and
# block sizes, LPC order 32, wasted bits, Rice2, Ogg FLAC, tags + a picture), ffmpeg's
# encoder (every stereo mode), a spliced variable-block stream, an ID3v2 tag in front;
# each with the zlib CRC-32 of `flac -d`'s samples (i32 LE, interleaved)
import base64, math, os, random, struct, tempfile, zlib
CTX = None
TMP = None
CASES = []
def signal(secs, rate, ch, bits, kind="music", seed=1, wasted=0):
"""Interleaved ints in the signed `bits` range."""
rnd = random.Random(seed)
n = int(secs * rate)
top = (1 << (bits - 1)) - 1
out = []
notes = [(rnd.uniform(80, 900), rnd.uniform(0, n), rnd.uniform(0.2, 0.6) * rate) for _ in range(int(secs * 6) + 2)]
for i in range(n):
t = i / rate
for c in range(ch):
if kind == "silence":
v = 0.0
elif kind == "noise":
v = rnd.uniform(-0.9, 0.9)
elif kind == "smooth": # slow polynomial-like curves (high fixed orders)
v = 0.8 * math.sin(2 * math.pi * (1000 + 300 * c) * t)
elif kind == "loudnoise": # full scale tone + strong noise: large Rice parameters at 32 bits
v = 0.6 * math.sin(2 * math.pi * 440 * t) + 0.08 * (rnd.random() - 0.5)
elif kind == "square": # constant runs
v = 0.5 if (i // 300) % 2 else -0.25
else:
v = 0.0
for f, st, dur in notes:
if st <= i < st + dur:
e = math.exp(-3 * (i - st) / dur) * min(1.0, (i - st) / 200)
v += 0.2 * e * (math.sin(2 * math.pi * f * (1 + 0.003 * c) * t) +
0.4 * math.sin(4 * math.pi * f * t + c) + 0.15 * math.sin(6 * math.pi * f * t))
v += 0.002 * (rnd.random() - 0.5) + 0.05 * math.sin(2 * math.pi * 55 * t)
x = int(max(-1.0, min(1.0, v)) * top)
if wasted:
x = (x >> wasted) << wasted
out.append(x)
return out
def write_wav(path, ints, ch, rate, bits):
container = (bits + 7) // 8 * 8
data = bytearray()
for v in ints:
x = v << (container - bits)
if container == 8:
data.append((x + 128) & 255)
else:
data += x.to_bytes(container // 8, "little", signed=True)
guid = b"\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71"
fmt = struct.pack("<HHIIHHHHI16s", 0xFFFE, ch, rate, rate * ch * container // 8, ch * container // 8, container,
22, bits, 0, guid)
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + bytes(data)
open(path, "wb").write(b"RIFF" + struct.pack("<I", len(body)) + body)
def read_ref(flac_path, bits):
"""Reference ints from flac -d."""
if bits in (8, 16, 24, 32):
raw = flac_path + ".raw"
CTX.nix("flac", ["flac", "-s", "-f", "-d", "--force-raw-format", "--endian=little", "--sign=signed", flac_path, "-o", raw])
d = open(raw, "rb").read()
w = bits // 8
return [int.from_bytes(d[i:i + w], "little", signed=True) for i in range(0, len(d), w)]
wav = flac_path + ".wav"
CTX.nix("flac", ["flac", "-s", "-f", "-d", flac_path, "-o", wav])
d = open(wav, "rb").read()
container = struct.unpack_from("<H", d, 34)[0]
i = 12
while d[i:i + 4] != b"data":
i += 8 + struct.unpack_from("<I", d, i + 4)[0]
size = struct.unpack_from("<I", d, i + 4)[0]
d = d[i + 8:i + 8 + size]
w = container // 8
out = []
for j in range(0, len(d), w):
x = d[j] - 128 if w == 1 else int.from_bytes(d[j:j + w], "little", signed=True)
out.append(x >> (container - bits))
return out
def crc_ints(ints):
return zlib.crc32(b"".join(struct.pack("<i", v) for v in ints))
def emit(name, path, rate, ch, bits, note, ogg=False, tags=None, prefix=b""):
ref = read_ref(path, bits)
data = prefix + open(path, "rb").read()
c = {"name": name, "note": note, "data": data, "rate": rate, "channels": ch, "bps": bits, "frames": len(ref) // ch,
"crc": crc_ints(ref), "ogg": ogg}
if tags:
c["tags"] = tags
CASES.append(c)
def flac(name, secs, rate, ch, bits, args, kind="music", wasted=0, note=None, ogg=False, tags=None, seed=1):
wav = os.path.join(TMP, name + ".wav")
out = os.path.join(TMP, name + (".oga" if ogg else ".flac"))
write_wav(wav, signal(secs, rate, ch, bits, kind, seed, wasted), ch, rate, bits)
CTX.nix("flac", ["flac", "-s", "-f"] + args + [wav, "-o", out])
emit(name, out, rate, ch, bits, note or "flac " + " ".join(args), ogg=ogg, tags=tags)
return out
CRC8 = []
for i in range(256):
c = i
for _ in range(8):
c = ((c << 1) ^ 0x07) & 0xFF if c & 0x80 else (c << 1) & 0xFF
CRC8.append(c)
def crc8(d):
c = 0
for x in d:
c = CRC8[c ^ x]
return c
def crc16(d):
c = 0
for x in d:
c ^= x << 8
for _ in range(8):
c = ((c << 1) ^ 0x8005) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def utf8num(n):
if n < 0x80:
return bytes([n])
out = []
lim = 0x3F
while True:
out.append(0x80 | (n & 0x3F))
n >>= 6
lim >>= 1
if n <= lim:
break
k = len(out) + 1
first = ((0xFF00 >> k) & 0xFF) | n
return bytes([first]) + bytes(reversed(out))
def frames_of(data):
"""(offset, header_len, end) of each frame of a fixed-blocksize native stream (CRC-validated)."""
p = 4
while True:
h = data[p]
size = int.from_bytes(data[p + 1:p + 4], "big")
p += 4 + size
if h & 0x80:
break
syncs = []
for i in range(p, len(data) - 1):
if data[i] == 0xFF and data[i + 1] == 0xF8:
syncs.append(i)
frames, start = [], syncs[0]
k = 1
while start < len(data):
found = None
for e in syncs[k:] + [len(data)]:
if e > start and crc16(data[start:e - 2]) == int.from_bytes(data[e - 2:e], "big"):
found = e
break
frames.append((start, found))
k = syncs.index(found) + 1 if found in syncs else len(syncs)
start = found
return p, frames
def make_varblock():
"""Frames of two encodes (block 4096 and 1152) spliced every 36864 samples, headers rewritten as variable."""
ints = signal(2.0, 44100, 2, 16, "music", 4)
wav = os.path.join(TMP, "vb.wav")
write_wav(wav, ints, 2, 44100, 16)
enc = {}
for bs in (4096, 1152):
out = os.path.join(TMP, "vb%d.flac" % bs)
CTX.nix("flac", ["flac", "-s", "-f", "-5", "--no-seektable", "--no-padding", "-b", str(bs), wav, "-o", out])
enc[bs] = open(out, "rb").read()
first, fa = frames_of(enc[4096])
_, fb = frames_of(enc[1152])
out = bytearray(enc[4096][:first])
sample, use, maxf = 0, 4096, 0
total = len(ints) // 2
while sample < total:
frames = fa if use == 4096 else fb
fi = sample // use
for j in range(fi, min(fi + 36864 // use, len(frames))):
a, e = frames[j]
fr = enc[use][a:e]
# old header: 4 bytes, the coded frame number, optional fields; rebuild with the sample number
b0 = fr[4]
nl = 1 if b0 < 0x80 else (2 if b0 < 0xE0 else 3 if b0 < 0xF0 else 4 if b0 < 0xF8 else 5 if b0 < 0xFC else 6)
bscode = fr[2] >> 4
extra = {6: 1, 7: 2}.get(bscode, 0) + {12: 1, 13: 2, 14: 2}.get(fr[2] & 15, 0)
hlen = 4 + nl + extra
hdr = bytes([0xFF, 0xF9]) + fr[2:4] + utf8num(sample + (j - fi) * use) + fr[4 + nl:hlen]
body = hdr + bytes([crc8(hdr)]) + fr[hlen + 1:-2]
body += crc16(body).to_bytes(2, "big")
out += body
maxf = max(maxf, len(body))
sample = (fi + min(36864 // use, len(frames) - fi)) * use
use = 1152 if use == 4096 else 4096
# STREAMINFO: min block 1152, max 4096, frame sizes unknown
out[8:10] = (1152).to_bytes(2, "big")
out[10:12] = (4096).to_bytes(2, "big")
out[12:18] = bytes(6)
path = os.path.join(TMP, "varblock.flac")
open(path, "wb").write(bytes(out))
emit("varblock", path, 44100, 2, 16, "variable block size: 4096 / 1152 frames spliced, sample-number headers")
def ffmpeg(name, secs, rate, ch, bits, args, kind="music"):
wav = os.path.join(TMP, name + ".wav")
out = os.path.join(TMP, name + ".flac")
write_wav(wav, signal(secs, rate, ch, bits, kind, 5), ch, rate, bits)
CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav] + args + [out])
emit(name, out, rate, ch, bits, "ffmpeg " + " ".join(args))
def generate(ctx):
global CTX, TMP
CTX = ctx
TMP = tempfile.mkdtemp()
CASES.clear()
for lv in range(9):
flac("s16_l%d" % lv, 0.4, 44100, 2, 16, ["-%d" % lv])
flac("s16_long", 3.0, 44100, 2, 16, ["-5", "-S", "0.5s"], seed=2,
note="flac -5, 3 s, seek points every 0.5 s (bench + seek)")
png = os.path.join(TMP, "p.png")
open(png, "wb").write(base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="))
flac("s16_noseek", 2.0, 44100, 2, 16, ["-6", "--no-seektable", "-T", "ARTIST=Some One", "-T", "TITLE=Test Tone",
"--picture", png], seed=3,
note="no seektable (bisection seek), tags, a picture", tags={"ARTIST": "Some One", "TITLE": "Test Tone"})
flac("u8_mono", 0.5, 22050, 1, 8, ["-5"])
flac("s24_96k", 0.3, 96000, 2, 24, ["-8"])
flac("s24_l0", 0.3, 48000, 2, 24, ["-0"])
flac("s32", 0.2, 48000, 2, 32, ["-5"])
flac("s32_l8", 0.2, 48000, 2, 32, ["-8"], kind="noise", note="flac -8, 32-bit noise (verbatim / escapes)")
flac("ch6", 0.3, 48000, 6, 16, ["-5"])
flac("ch3_24", 0.2, 44100, 3, 24, ["-7"])
flac("rate37000", 0.4, 37000, 1, 16, ["-5"])
flac("rate11025", 0.4, 11025, 2, 16, ["-3"])
flac("rate352800", 0.05, 352800, 2, 24, ["-5", "--lax"])
flac("rate100001", 0.1, 100001, 1, 16, ["-5", "--lax"], note="a rate only STREAMINFO can hold")
flac("rate7", 30.0, 7, 1, 16, ["-5", "--lax", "-b", "16"], note="7 Hz")
flac("bs17", 0.2, 44100, 1, 16, ["-5", "--lax", "-b", "17"])
flac("bs4609", 0.5, 44100, 2, 16, ["-8", "--lax", "-b", "4609"])
flac("bs65535", 1.6, 44100, 2, 16, ["-5", "--lax", "-b", "65535", "-r", "15"])
flac("lpc32", 0.3, 44100, 2, 16, ["--lax", "-b", "1001", "-l", "32", "-r", "0,8", "-e", "-p"],
note="LPC order 32, block 1001, exhaustive")
flac("bits12", 0.3, 44100, 2, 12, ["-5"])
flac("bits20", 0.3, 44100, 2, 20, ["-8"])
flac("bits4", 0.3, 8000, 1, 4, ["-5", "--lax"])
flac("wasted", 0.3, 44100, 2, 16, ["-5"], wasted=3, note="low 3 bits zero (wasted bits)")
flac("smooth", 0.3, 44100, 2, 24, ["-2"], kind="smooth", note="flac -2, 24-bit pure tones (fixed order 4)")
flac("s32_rice2", 0.2, 48000, 2, 32, ["-5"], kind="loudnoise", note="32-bit tone + noise (Rice2, k > 24)")
make_varblock()
flac("silence", 0.3, 44100, 2, 16, ["-5"], kind="silence")
flac("square", 0.3, 44100, 2, 16, ["-5"], kind="square")
flac("noise16", 0.3, 44100, 2, 16, ["-5"], kind="noise")
flac("ogg_s16", 1.0, 44100, 2, 16, ["-5", "--ogg"], ogg=True, note="Ogg FLAC")
for mode in ("left_side", "right_side", "mid_side", "indep"):
ffmpeg("ff_" + mode, 0.3, 44100, 2, 16, ["-c:a", "flac", "-ch_mode", mode])
ffmpeg("ff_l12", 0.4, 44100, 2, 16, ["-c:a", "flac", "-compression_level", "12"])
ffmpeg("ff_s24", 0.3, 48000, 2, 24, ["-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24",
"-compression_level", "8"])
ffmpeg("ff_exact", 0.3, 44100, 2, 16, ["-c:a", "flac", "-exact_rice_parameters", "1", "-multi_dim_quant", "1",
"-lpc_type", "cholesky", "-lpc_passes", "2"])
# an ID3v2 tag in front of fLaC
src = os.path.join(TMP, "s16_l5.flac")
id3 = b"ID3\x04\x00\x00" + bytes([0, 0, 0, 20]) + b"TIT2\x00\x00\x00\x0a\x00\x00\x03hello id3"
emit("id3", src, 44100, 2, 16, "s16_l5 with an ID3v2 tag in front", prefix=id3)
ctx.emit("flac_cases", CASES)