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

+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