rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,988 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8
|
||||
-- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive /
|
||||
-- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum),
|
||||
-- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with
|
||||
-- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted
|
||||
-- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 /
|
||||
-- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional
|
||||
-- SEEKTABLE. Streams: input blocks are pulled from a codecs/audio/Pcm Source, so a Decoder is encoded without decoding it
|
||||
-- whole. Never throws: bad options are rejected by audio/flac before calling in.
|
||||
local Bits = require("@rosetta/core/Bits")
|
||||
local Md5 = require("@rosetta/core/Md5")
|
||||
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
|
||||
local Frame = require("@rosetta/codecs/audio/Flac/Frame")
|
||||
|
||||
local Encode = {}
|
||||
|
||||
local floor, abs, log = math.floor, math.abs, math.log
|
||||
local readf32, writeu8 = buffer.readf32, buffer.writeu8
|
||||
|
||||
local POW = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
POW[i + 1] = 2 ^ i
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ CRCs
|
||||
-- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here)
|
||||
local function crc8(b: buffer, o: number, n: number): number
|
||||
return Frame.crc8(b, o, o + n)
|
||||
end
|
||||
local function crc16(b: buffer, o: number, n: number): number
|
||||
return Frame.crc16(b, o, o + n)
|
||||
end
|
||||
Encode.crc8, Encode.crc16 = crc8, crc16
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit writer (MSB first)
|
||||
type W = Bits.RawWriter
|
||||
|
||||
local function ensure(w: W, n: number)
|
||||
local need = w.pos + n + 16
|
||||
local cap = buffer.len(w.buf)
|
||||
if need > cap then
|
||||
local nb = buffer.create(math.max(cap * 2, need))
|
||||
buffer.copy(nb, 0, w.buf, 0, w.pos)
|
||||
w.buf = nb
|
||||
end
|
||||
end
|
||||
|
||||
local put = Bits.msbPut
|
||||
|
||||
local function putSigned(w: W, v: number, n: number)
|
||||
put(w, if v < 0 then v + POW[n + 1] else v, n)
|
||||
end
|
||||
|
||||
local function alignByte(w: W)
|
||||
if w.cnt > 0 then
|
||||
put(w, 0, 8 - w.cnt)
|
||||
end
|
||||
end
|
||||
|
||||
local function putUtf8(w: W, v: number)
|
||||
if v < 0x80 then
|
||||
put(w, v, 8)
|
||||
return
|
||||
end
|
||||
local n = if v < 0x800 then 2 elseif v < 0x10000 then 3 elseif v < 0x200000 then 4 elseif v < 0x4000000 then 5 elseif v < 0x80000000 then 6 else 7
|
||||
local first = if n == 7 then 0xFE else (0xFF00 // POW[n + 1]) % 256 -- n leading ones
|
||||
local shift = 6 * (n - 1)
|
||||
put(w, first + floor(v / POW[shift + 1]), 8)
|
||||
for k = n - 2, 0, -1 do
|
||||
put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ presets
|
||||
export type Config = {
|
||||
blockSize: number,
|
||||
maxLpcOrder: number,
|
||||
maxPartitionOrder: number,
|
||||
stereo: string, -- "independent" | "adaptive" | "exhaustive"
|
||||
exhaustiveOrder: boolean,
|
||||
}
|
||||
local PRESETS: { Config } = {
|
||||
{ blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false },
|
||||
{ blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false },
|
||||
{ blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false },
|
||||
{ blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false },
|
||||
{ blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false },
|
||||
{ blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false },
|
||||
{ blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false },
|
||||
{ blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false },
|
||||
{ blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true },
|
||||
}
|
||||
Encode.PRESETS = PRESETS
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ analysis
|
||||
-- a subframe plan for one channel signal
|
||||
type Plan = {
|
||||
kind: number, -- 0 constant, 1 verbatim, 2 fixed, 3 lpc
|
||||
bits: number, -- estimated size in bits (with the subframe header)
|
||||
order: number,
|
||||
wasted: number,
|
||||
bps: number, -- sample size after removing wasted bits
|
||||
res: { number }, -- residual (fixed / lpc), indices 1..n
|
||||
porder: number,
|
||||
params: { number },
|
||||
method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit)
|
||||
qlp: { number },
|
||||
shift: number,
|
||||
precision: number,
|
||||
x: { number }, -- the (shifted) samples
|
||||
}
|
||||
|
||||
local function newPlan(n: number): Plan
|
||||
return {
|
||||
kind = 1,
|
||||
bits = 0,
|
||||
order = 0,
|
||||
wasted = 0,
|
||||
bps = 16,
|
||||
res = table.create(n, 0),
|
||||
porder = 0,
|
||||
params = table.create(64, 0),
|
||||
method = 0,
|
||||
qlp = table.create(32, 0),
|
||||
shift = 0,
|
||||
precision = 0,
|
||||
x = table.create(n, 0),
|
||||
}
|
||||
end
|
||||
|
||||
-- scratch per encoder
|
||||
type Scratch = {
|
||||
sums: { number },
|
||||
counts: { number },
|
||||
ks: { number },
|
||||
bestKs: { number },
|
||||
tmpRes: { number },
|
||||
win: { number },
|
||||
winN: number,
|
||||
wx: { number },
|
||||
autoc: { number },
|
||||
lpc: { { number } },
|
||||
err: { number },
|
||||
qlp: { number },
|
||||
}
|
||||
|
||||
-- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters)
|
||||
local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number)
|
||||
-- the finest usable partition order
|
||||
local p = maxP
|
||||
while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do
|
||||
p -= 1
|
||||
end
|
||||
local sums, counts = sc.sums, sc.counts
|
||||
local parts = POW[p + 1]
|
||||
local ps = n // parts
|
||||
-- sums of zig-zag values at the finest order
|
||||
for j = 0, parts - 1 do
|
||||
local s = 0
|
||||
local a = if j == 0 then order + 1 else j * ps + 1
|
||||
local e = (j + 1) * ps
|
||||
for i = a, e do
|
||||
local r = res[i]
|
||||
s += if r >= 0 then 2 * r else -2 * r - 1
|
||||
end
|
||||
sums[j + 1] = s
|
||||
counts[j + 1] = e - a + 1
|
||||
end
|
||||
local bestBits, bestP, bestMethod = math.huge, 0, 0
|
||||
local ks, bestKs = sc.ks, sc.bestKs
|
||||
local q = p
|
||||
while true do
|
||||
local np = POW[q + 1]
|
||||
local total = 0
|
||||
local maxk = 0
|
||||
for j = 1, np do
|
||||
local s, c = sums[j], counts[j]
|
||||
local k = 0
|
||||
local cost = s + c -- k = 0: unary s, plus one stop bit per sample
|
||||
if c > 0 and s > c then
|
||||
local k0 = floor(log(s / c) / 0.6931471805599453)
|
||||
for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do
|
||||
local cc = c * (kk + 1) + floor(s / POW[kk + 1])
|
||||
if cc < cost then
|
||||
cost, k = cc, kk
|
||||
end
|
||||
end
|
||||
end
|
||||
ks[j] = k
|
||||
if k > maxk then
|
||||
maxk = k
|
||||
end
|
||||
total += cost
|
||||
end
|
||||
local method = if maxk > 14 then 1 else 0
|
||||
total += np * (if method == 1 then 5 else 4) + 2 + 4
|
||||
if total < bestBits then
|
||||
bestBits, bestP, bestMethod = total, q, method
|
||||
for j = 1, np do
|
||||
bestKs[j] = ks[j]
|
||||
end
|
||||
end
|
||||
if q == 0 then
|
||||
break
|
||||
end
|
||||
-- merge pairs into the next coarser order
|
||||
for j = 1, np // 2 do
|
||||
sums[j] = sums[2 * j - 1] + sums[2 * j]
|
||||
counts[j] = counts[2 * j - 1] + counts[2 * j]
|
||||
end
|
||||
q -= 1
|
||||
end
|
||||
return bestBits, bestP, bestMethod
|
||||
end
|
||||
|
||||
local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number)
|
||||
plan.porder, plan.method = porder, method
|
||||
local params = plan.params
|
||||
for j = 1, POW[porder + 1] do
|
||||
params[j] = sc.bestKs[j]
|
||||
end
|
||||
end
|
||||
|
||||
-- fixed predictor residuals
|
||||
local function fixedResidual(x: { number }, n: number, order: number, res: { number })
|
||||
for i = 1, order do
|
||||
res[i] = 0
|
||||
end
|
||||
if order == 0 then
|
||||
for i = 1, n do
|
||||
res[i] = x[i]
|
||||
end
|
||||
elseif order == 1 then
|
||||
for i = 2, n do
|
||||
res[i] = x[i] - x[i - 1]
|
||||
end
|
||||
elseif order == 2 then
|
||||
for i = 3, n do
|
||||
res[i] = x[i] - 2 * x[i - 1] + x[i - 2]
|
||||
end
|
||||
elseif order == 3 then
|
||||
for i = 4, n do
|
||||
res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3]
|
||||
end
|
||||
else
|
||||
for i = 5, n do
|
||||
res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the fixed order with the smallest residual magnitude (libFLAC's estimate)
|
||||
local function bestFixedOrder(x: { number }, n: number): (number, number)
|
||||
if n <= 4 then
|
||||
return 0, 0
|
||||
end
|
||||
local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0
|
||||
local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1]
|
||||
for i = 5, n do
|
||||
local e0 = x[i]
|
||||
local e1 = e0 - a
|
||||
local e2 = e1 - b
|
||||
local e3 = e2 - c
|
||||
local e4 = e3 - d
|
||||
s0 += abs(e0)
|
||||
s1 += abs(e1)
|
||||
s2 += abs(e2)
|
||||
s3 += abs(e3)
|
||||
s4 += abs(e4)
|
||||
a, b, c, d = e0, e1, e2, e3
|
||||
end
|
||||
local best, bs = 0, s0
|
||||
if s1 < bs then
|
||||
best, bs = 1, s1
|
||||
end
|
||||
if s2 < bs then
|
||||
best, bs = 2, s2
|
||||
end
|
||||
if s3 < bs then
|
||||
best, bs = 3, s3
|
||||
end
|
||||
if s4 < bs then
|
||||
best, bs = 4, s4
|
||||
end
|
||||
return best, bs
|
||||
end
|
||||
Encode.bestFixedOrder = bestFixedOrder
|
||||
|
||||
-- libFLAC's default QLP coefficient precision for a block size
|
||||
local function qlpPrecision(bps: number, n: number): number
|
||||
if bps > 16 then
|
||||
return 15
|
||||
end
|
||||
if n <= 192 then
|
||||
return 7
|
||||
elseif n <= 384 then
|
||||
return 8
|
||||
elseif n <= 576 then
|
||||
return 9
|
||||
elseif n <= 1152 then
|
||||
return 10
|
||||
elseif n <= 2304 then
|
||||
return 11
|
||||
elseif n <= 4608 then
|
||||
return 12
|
||||
end
|
||||
return 13
|
||||
end
|
||||
|
||||
-- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil
|
||||
local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number?
|
||||
local cmax = 0
|
||||
for i = 1, order do
|
||||
local a = abs(lp[i])
|
||||
if a > cmax then
|
||||
cmax = a
|
||||
end
|
||||
end
|
||||
if cmax <= 0 or cmax ~= cmax or cmax == math.huge then
|
||||
return nil
|
||||
end
|
||||
local log2cmax = 0
|
||||
while cmax >= 1 do
|
||||
cmax /= 2
|
||||
log2cmax += 1
|
||||
end
|
||||
while cmax < 0.5 do
|
||||
cmax *= 2
|
||||
log2cmax -= 1
|
||||
end
|
||||
-- frexp: cmax = m * 2^log2cmax with m in [0.5, 1)
|
||||
log2cmax -= 1
|
||||
local p = precision - 1
|
||||
local qmax = POW[p + 1] - 1
|
||||
local qmin = -POW[p + 1]
|
||||
local shift = p - log2cmax - 1
|
||||
if shift > 15 then
|
||||
shift = 15
|
||||
elseif shift < 0 then
|
||||
return nil
|
||||
end
|
||||
local err = 0
|
||||
local scale = POW[shift + 1]
|
||||
for i = 1, order do
|
||||
err += lp[i] * scale
|
||||
local q = floor(err + 0.5)
|
||||
if q > qmax then
|
||||
q = qmax
|
||||
elseif q < qmin then
|
||||
q = qmin
|
||||
end
|
||||
err -= q
|
||||
qlp[i] = q
|
||||
end
|
||||
return shift
|
||||
end
|
||||
|
||||
local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number })
|
||||
local d = POW[shift + 1]
|
||||
for i = 1, order do
|
||||
res[i] = 0
|
||||
end
|
||||
for i = order + 1, n do
|
||||
local s = 0
|
||||
for j = 1, order do
|
||||
s += qlp[j] * x[i - j]
|
||||
end
|
||||
res[i] = x[i] - floor(s / d)
|
||||
end
|
||||
end
|
||||
|
||||
-- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order
|
||||
local function levinson(sc: Scratch, maxOrder: number): number
|
||||
local r = sc.autoc
|
||||
local e = r[1]
|
||||
if e <= 0 then
|
||||
return 0
|
||||
end
|
||||
local a = table.create(maxOrder + 1, 0)
|
||||
local tmp = table.create(maxOrder + 1, 0)
|
||||
for o = 1, maxOrder do
|
||||
local acc = r[o + 1]
|
||||
for j = 1, o - 1 do
|
||||
acc -= a[j] * r[o - j + 1]
|
||||
end
|
||||
local k = acc / e
|
||||
for j = 1, o - 1 do
|
||||
tmp[j] = a[j] - k * a[o - j]
|
||||
end
|
||||
for j = 1, o - 1 do
|
||||
a[j] = tmp[j]
|
||||
end
|
||||
a[o] = k
|
||||
e *= (1 - k * k)
|
||||
local row = sc.lpc[o]
|
||||
for j = 1, o do
|
||||
row[j] = a[j]
|
||||
end
|
||||
sc.err[o] = e
|
||||
if e <= 0 then
|
||||
return o
|
||||
end
|
||||
end
|
||||
return maxOrder
|
||||
end
|
||||
|
||||
-- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays)
|
||||
local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan)
|
||||
local x = plan.x
|
||||
-- constant?
|
||||
local first = src[1]
|
||||
local constant = true
|
||||
for i = 1, n do
|
||||
local v = src[i]
|
||||
if v ~= first then
|
||||
constant = false
|
||||
end
|
||||
end
|
||||
if constant then
|
||||
plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps
|
||||
plan.res[1] = first
|
||||
return
|
||||
end
|
||||
-- wasted bits: the common trailing zeros
|
||||
local wasted = 0
|
||||
do
|
||||
local w = 0
|
||||
while w < bps - 1 do
|
||||
local m = POW[w + 2]
|
||||
local all = true
|
||||
for i = 1, n do
|
||||
if src[i] % m ~= 0 then
|
||||
all = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if not all then
|
||||
break
|
||||
end
|
||||
w += 1
|
||||
end
|
||||
wasted = w
|
||||
end
|
||||
local d = POW[wasted + 1]
|
||||
for i = 1, n do
|
||||
x[i] = src[i] / d
|
||||
end
|
||||
local b = bps - wasted
|
||||
local hdr = 8 + wasted
|
||||
plan.wasted, plan.bps = wasted, b
|
||||
-- verbatim
|
||||
plan.kind, plan.bits = 1, hdr + n * b
|
||||
-- fixed
|
||||
local fo = bestFixedOrder(x, n)
|
||||
if n > fo then
|
||||
local tmp = sc.tmpRes
|
||||
fixedResidual(x, n, fo, tmp)
|
||||
local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder)
|
||||
local bits = hdr + fo * b + rb
|
||||
if bits < plan.bits then
|
||||
plan.kind, plan.bits, plan.order = 2, bits, fo
|
||||
sc.tmpRes, plan.res = plan.res, tmp
|
||||
keepRice(sc, plan, po, me)
|
||||
end
|
||||
end
|
||||
-- lpc
|
||||
local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32)
|
||||
if maxOrder > 0 then
|
||||
-- windowed autocorrelation
|
||||
local win = sc.win
|
||||
if sc.winN ~= n then
|
||||
-- tukey(0.5)
|
||||
local np = floor(0.25 * n)
|
||||
for i = 1, n do
|
||||
win[i] = 1
|
||||
end
|
||||
if np > 0 then
|
||||
for i = 0, np - 1 do
|
||||
local v = 0.5 - 0.5 * math.cos(math.pi * i / np)
|
||||
win[i + 1] = v
|
||||
win[n - i] = v
|
||||
end
|
||||
end
|
||||
sc.winN = n
|
||||
end
|
||||
local wx = sc.wx
|
||||
for i = 1, n do
|
||||
wx[i] = x[i] * win[i]
|
||||
end
|
||||
local ac = sc.autoc
|
||||
for lag = 0, maxOrder do
|
||||
local s = 0
|
||||
for i = lag + 1, n do
|
||||
s += wx[i] * wx[i - lag]
|
||||
end
|
||||
ac[lag + 1] = s
|
||||
end
|
||||
local top = levinson(sc, maxOrder)
|
||||
if top > 0 then
|
||||
local precision = qlpPrecision(b, n)
|
||||
local orders = {}
|
||||
if cfg.exhaustiveOrder then
|
||||
for o = 1, top do
|
||||
table.insert(orders, o)
|
||||
end
|
||||
else
|
||||
-- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision
|
||||
local bestO, bestE = 1, math.huge
|
||||
for o = 1, top do
|
||||
local e = sc.err[o]
|
||||
local est = if e > 0 then (n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) else -math.huge
|
||||
if est < bestE then
|
||||
bestO, bestE = o, est
|
||||
end
|
||||
end
|
||||
orders[1] = bestO
|
||||
end
|
||||
local qlp = sc.qlp
|
||||
for _, o in orders do
|
||||
local prec = precision
|
||||
local shift = quantize(sc.lpc[o], o, prec, qlp)
|
||||
if shift then
|
||||
local tmp = sc.tmpRes
|
||||
lpcResidual(x, n, o, qlp, shift, tmp)
|
||||
local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder)
|
||||
local bits = hdr + o * b + 4 + 5 + o * prec + rb
|
||||
if bits < plan.bits then
|
||||
plan.kind, plan.bits, plan.order = 3, bits, o
|
||||
plan.shift, plan.precision = shift, prec
|
||||
for j = 1, o do
|
||||
plan.qlp[j] = qlp[j]
|
||||
end
|
||||
sc.tmpRes, plan.res = plan.res, tmp
|
||||
keepRice(sc, plan, po, me)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writing
|
||||
local function writeResidual(w: W, plan: Plan, n: number)
|
||||
local method = plan.method
|
||||
put(w, method, 2)
|
||||
local porder = plan.porder
|
||||
put(w, porder, 4)
|
||||
local parts = POW[porder + 1]
|
||||
local ps = n // parts
|
||||
local res = plan.res
|
||||
local pbits = if method == 1 then 5 else 4
|
||||
for j = 0, parts - 1 do
|
||||
local k = plan.params[j + 1]
|
||||
put(w, k, pbits)
|
||||
local a = if j == 0 then plan.order + 1 else j * ps + 1
|
||||
local e = (j + 1) * ps
|
||||
local mk = POW[k + 1]
|
||||
for i = a, e do
|
||||
local r = res[i]
|
||||
local u = if r >= 0 then 2 * r else -2 * r - 1
|
||||
local hi = floor(u / mk)
|
||||
local lo = u - hi * mk
|
||||
if hi + 1 + k <= 32 then
|
||||
put(w, mk + lo, hi + 1 + k)
|
||||
else
|
||||
local q = hi
|
||||
while q > 24 do
|
||||
put(w, 0, 24)
|
||||
q -= 24
|
||||
end
|
||||
put(w, 1, q + 1)
|
||||
put(w, lo, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function writeSubframe(w: W, plan: Plan, n: number)
|
||||
local kind = plan.kind
|
||||
local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1
|
||||
put(w, 0, 1)
|
||||
put(w, typ, 6)
|
||||
if kind ~= 0 and plan.wasted > 0 then
|
||||
put(w, 1, 1)
|
||||
put(w, 1, plan.wasted) -- k - 1 zeros, then a one
|
||||
else
|
||||
put(w, 0, 1)
|
||||
end
|
||||
local b = plan.bps
|
||||
if kind == 0 then
|
||||
putSigned(w, plan.res[1], b)
|
||||
return
|
||||
end
|
||||
local x = plan.x
|
||||
if kind == 1 then
|
||||
for i = 1, n do
|
||||
putSigned(w, x[i], b)
|
||||
end
|
||||
return
|
||||
end
|
||||
for i = 1, plan.order do
|
||||
putSigned(w, x[i], b)
|
||||
end
|
||||
if kind == 3 then
|
||||
put(w, plan.precision - 1, 4)
|
||||
put(w, plan.shift, 5)
|
||||
for j = 1, plan.order do
|
||||
putSigned(w, plan.qlp[j], plan.precision)
|
||||
end
|
||||
end
|
||||
writeResidual(w, plan, n)
|
||||
end
|
||||
|
||||
local RATE_CODES: { [number]: number } = {
|
||||
[88200] = 1,
|
||||
[176400] = 2,
|
||||
[192000] = 3,
|
||||
[8000] = 4,
|
||||
[16000] = 5,
|
||||
[22050] = 6,
|
||||
[24000] = 7,
|
||||
[32000] = 8,
|
||||
[44100] = 9,
|
||||
[48000] = 10,
|
||||
[96000] = 11,
|
||||
}
|
||||
local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 }
|
||||
|
||||
local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16)
|
||||
if n == 192 then
|
||||
return 1, 0
|
||||
end
|
||||
for k = 2, 5 do
|
||||
if n == 576 * POW[k - 1] then
|
||||
return k, 0
|
||||
end
|
||||
end
|
||||
for k = 8, 15 do
|
||||
if n == 256 * POW[k - 7] then
|
||||
return k, 0
|
||||
end
|
||||
end
|
||||
if n <= 256 then
|
||||
return 6, 8
|
||||
end
|
||||
return 7, 16
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encoder
|
||||
export type Source = {
|
||||
sampleRate: number,
|
||||
channels: number,
|
||||
frames: number,
|
||||
tags: { [string]: string },
|
||||
read: (self: any, n: number, out: buffer?) -> (buffer, number),
|
||||
err: any,
|
||||
}
|
||||
export type Options = {
|
||||
level: number,
|
||||
bits: number,
|
||||
blockSize: number?,
|
||||
seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE)
|
||||
padding: number, -- bytes of PADDING
|
||||
vendor: string,
|
||||
}
|
||||
|
||||
-- encode(src, opts) -> buffer | nil, message
|
||||
function Encode.encode(src: Source, opts: Options): (buffer?, string?)
|
||||
local cfg = PRESETS[opts.level + 1]
|
||||
local ch, rate, bps = src.channels, src.sampleRate, opts.bits
|
||||
local bs = opts.blockSize or cfg.blockSize
|
||||
local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 }
|
||||
-- metadata
|
||||
put(w, 0x664C6143, 32) -- "fLaC"
|
||||
put(w, 0, 1)
|
||||
put(w, 0, 7)
|
||||
put(w, 34, 24)
|
||||
local siData = w.pos
|
||||
for _ = 1, 34 do
|
||||
put(w, 0, 8)
|
||||
end
|
||||
-- seek table placeholders (when the length is known)
|
||||
local seekPoints = 0
|
||||
local seekAt = 0
|
||||
local interval = floor(opts.seekInterval * rate)
|
||||
if interval > 0 and src.frames > 0 then
|
||||
seekPoints = (src.frames - 1) // interval + 1
|
||||
if seekPoints > 65535 // 18 * 18 then
|
||||
seekPoints = 0
|
||||
end
|
||||
end
|
||||
-- vorbis comment
|
||||
local comments = VorbisComment.fields(src.tags)
|
||||
local vendor = opts.vendor
|
||||
local vcLen = 4 + #vendor + 4
|
||||
for _, c in comments do
|
||||
vcLen += 4 + #c
|
||||
end
|
||||
-- SEEKTABLE
|
||||
if seekPoints > 0 then
|
||||
put(w, 0, 1)
|
||||
put(w, 3, 7)
|
||||
put(w, seekPoints * 18, 24)
|
||||
seekAt = w.pos
|
||||
ensure(w, seekPoints * 18)
|
||||
for _ = 1, seekPoints do
|
||||
put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it
|
||||
put(w, 0xFFFFFFFF, 32)
|
||||
put(w, 0, 32) -- byte offset
|
||||
put(w, 0, 32)
|
||||
put(w, 0, 16) -- frame samples
|
||||
end
|
||||
end
|
||||
-- VORBIS_COMMENT (little-endian lengths)
|
||||
local function le32(v: number)
|
||||
put(w, v % 256, 8)
|
||||
put(w, (v // 256) % 256, 8)
|
||||
put(w, (v // 65536) % 256, 8)
|
||||
put(w, v // 16777216, 8)
|
||||
end
|
||||
ensure(w, vcLen + 8)
|
||||
put(w, if opts.padding > 0 then 0 else 1, 1) -- the last metadata block unless PADDING follows
|
||||
put(w, 4, 7)
|
||||
put(w, vcLen, 24)
|
||||
le32(#vendor)
|
||||
for i = 1, #vendor do
|
||||
put(w, string.byte(vendor, i), 8)
|
||||
end
|
||||
le32(#comments)
|
||||
for _, c in comments do
|
||||
ensure(w, #c + 8)
|
||||
le32(#c)
|
||||
for i = 1, #c do
|
||||
put(w, string.byte(c, i), 8)
|
||||
end
|
||||
end
|
||||
if opts.padding > 0 then
|
||||
ensure(w, opts.padding + 8)
|
||||
put(w, 1, 1)
|
||||
put(w, 1, 7)
|
||||
put(w, opts.padding, 24)
|
||||
for _ = 1, opts.padding do
|
||||
put(w, 0, 8)
|
||||
end
|
||||
end
|
||||
local audioStart = w.pos
|
||||
-- frames
|
||||
local md5 = Md5.new()
|
||||
local mbytes = (bps + 7) // 8
|
||||
local mbuf = buffer.create(bs * ch * mbytes)
|
||||
local scale = POW[bps]
|
||||
local maxv, minv = scale - 1, -scale
|
||||
local X: { { number } } = table.create(ch) :: any
|
||||
for c = 1, ch do
|
||||
X[c] = table.create(bs, 0)
|
||||
end
|
||||
local side = table.create(bs, 0)
|
||||
local mid = table.create(bs, 0)
|
||||
local plans = {}
|
||||
for i = 1, 4 do
|
||||
plans[i] = newPlan(bs)
|
||||
end
|
||||
for c = 1, ch do
|
||||
plans[4 + c] = newPlan(bs)
|
||||
end
|
||||
local lpcRows = {}
|
||||
for o = 1, 32 do
|
||||
lpcRows[o] = table.create(o, 0)
|
||||
end
|
||||
local sc: Scratch = {
|
||||
sums = table.create(64, 0),
|
||||
counts = table.create(64, 0),
|
||||
ks = table.create(64, 0),
|
||||
bestKs = table.create(64, 0),
|
||||
tmpRes = table.create(bs, 0),
|
||||
win = table.create(bs, 0),
|
||||
winN = 0,
|
||||
wx = table.create(bs, 0),
|
||||
autoc = table.create(33, 0),
|
||||
lpc = lpcRows,
|
||||
err = table.create(32, 0),
|
||||
qlp = table.create(32, 0),
|
||||
}
|
||||
local frameNo = 0
|
||||
local total = 0
|
||||
local minFrame, maxFrame = math.huge, 0
|
||||
local seekNext = 0
|
||||
local seekIdx = 0
|
||||
local rateCode = RATE_CODES[rate] or 0
|
||||
local sizeCode = SIZE_CODES[bps] or 0
|
||||
local tmp: buffer? = nil
|
||||
local pendingBuf: buffer? = nil
|
||||
local pendingN, pendingOff = 0, 0
|
||||
-- read exactly bs frames (fewer only at the end)
|
||||
local function readBlock(): (buffer?, number)
|
||||
local out = buffer.create(bs * ch * 4)
|
||||
local got = 0
|
||||
while got < bs do
|
||||
if pendingN == 0 then
|
||||
local b, n = src:read(math.max(bs, 4096), tmp)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
tmp = b
|
||||
pendingBuf, pendingN, pendingOff = b, n, 0
|
||||
end
|
||||
local take = math.min(bs - got, pendingN)
|
||||
buffer.copy(out, got * ch * 4, pendingBuf :: buffer, pendingOff * ch * 4, take * ch * 4)
|
||||
got += take
|
||||
pendingN -= take
|
||||
pendingOff += take
|
||||
end
|
||||
return out, got
|
||||
end
|
||||
while true do
|
||||
local fb, n = readBlock()
|
||||
if n <= 0 or fb == nil then
|
||||
break
|
||||
end
|
||||
-- to integers (+ the MD5 bytes, signed little endian)
|
||||
local mo = 0
|
||||
for i = 0, n - 1 do
|
||||
for c = 1, ch do
|
||||
local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5)
|
||||
if v ~= v then
|
||||
v = 0
|
||||
elseif v > maxv then
|
||||
v = maxv
|
||||
elseif v < minv then
|
||||
v = minv
|
||||
end
|
||||
X[c][i + 1] = v
|
||||
local u = if v < 0 then v + 4294967296 else v
|
||||
for k = 0, mbytes - 1 do
|
||||
writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256)
|
||||
mo += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
md5:update(mbuf, 0, mo)
|
||||
-- channel decorrelation
|
||||
local assign = ch - 1
|
||||
local chosen: { Plan } = {}
|
||||
if ch == 2 and cfg.stereo ~= "independent" then
|
||||
local L, R = X[1], X[2]
|
||||
for i = 1, n do
|
||||
local l, r = L[i], R[i]
|
||||
side[i] = l - r
|
||||
mid[i] = floor((l + r) / 2)
|
||||
end
|
||||
local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4]
|
||||
if cfg.stereo == "adaptive" then
|
||||
local _, el = bestFixedOrder(L, n)
|
||||
local _, er = bestFixedOrder(R, n)
|
||||
local _, em = bestFixedOrder(mid, n)
|
||||
local _, es = bestFixedOrder(side, n)
|
||||
-- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real
|
||||
local best = math.min(el + es, er + es, em + es)
|
||||
analyze(sc, cfg, L, n, bps, pl)
|
||||
analyze(sc, cfg, R, n, bps, pr)
|
||||
chosen, assign = { pl, pr }, 1
|
||||
if best < el + er then
|
||||
analyze(sc, cfg, side, n, bps + 1, ps)
|
||||
if best == em + es then
|
||||
analyze(sc, cfg, mid, n, bps, pm)
|
||||
if pm.bits + ps.bits < pl.bits + pr.bits then
|
||||
chosen, assign = { pm, ps }, 10
|
||||
end
|
||||
elseif best == el + es then
|
||||
if pl.bits + ps.bits < pl.bits + pr.bits then
|
||||
chosen, assign = { pl, ps }, 8
|
||||
end
|
||||
elseif ps.bits + pr.bits < pl.bits + pr.bits then
|
||||
chosen, assign = { ps, pr }, 9
|
||||
end
|
||||
end
|
||||
else
|
||||
analyze(sc, cfg, L, n, bps, pl)
|
||||
analyze(sc, cfg, R, n, bps, pr)
|
||||
analyze(sc, cfg, mid, n, bps, pm)
|
||||
analyze(sc, cfg, side, n, bps + 1, ps)
|
||||
local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits
|
||||
local best = math.min(lr, ls, rs, msb)
|
||||
if best == lr then
|
||||
chosen, assign = { pl, pr }, 1
|
||||
elseif best == msb then
|
||||
chosen, assign = { pm, ps }, 10
|
||||
elseif best == ls then
|
||||
chosen, assign = { pl, ps }, 8
|
||||
else
|
||||
chosen, assign = { ps, pr }, 9
|
||||
end
|
||||
end
|
||||
else
|
||||
for c = 1, ch do
|
||||
analyze(sc, cfg, X[c], n, bps, plans[4 + c])
|
||||
chosen[c] = plans[4 + c]
|
||||
end
|
||||
end
|
||||
-- the frame
|
||||
local need = n * ch * 4 + 64
|
||||
for _, p in chosen do
|
||||
need += (p.bits // 8) + 8
|
||||
end
|
||||
ensure(w, need)
|
||||
local start = w.pos
|
||||
-- seek points: the first frame at or after each multiple of the interval
|
||||
while seekIdx < seekPoints and total >= seekNext do
|
||||
local at = seekAt + seekIdx * 18
|
||||
local sn, off = total, start - audioStart
|
||||
local tb = w.buf
|
||||
for k = 0, 7 do
|
||||
writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256)
|
||||
writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256)
|
||||
end
|
||||
writeu8(tb, at + 16, n // 256)
|
||||
writeu8(tb, at + 17, n % 256)
|
||||
seekIdx += 1
|
||||
seekNext = seekIdx * interval
|
||||
end
|
||||
put(w, 0x3FFE, 14)
|
||||
put(w, 0, 1)
|
||||
put(w, 0, 1) -- fixed block size
|
||||
local bcode, bextra = blockCode(n)
|
||||
put(w, bcode, 4)
|
||||
put(w, rateCode, 4)
|
||||
put(w, assign, 4)
|
||||
put(w, sizeCode, 3)
|
||||
put(w, 0, 1)
|
||||
putUtf8(w, frameNo)
|
||||
if bextra > 0 then
|
||||
put(w, n - 1, bextra)
|
||||
end
|
||||
put(w, crc8(w.buf, start, w.pos - start), 8)
|
||||
for _, p in chosen do
|
||||
writeSubframe(w, p, n)
|
||||
end
|
||||
alignByte(w)
|
||||
local c16 = crc16(w.buf, start, w.pos - start)
|
||||
put(w, c16, 16)
|
||||
local fsize = w.pos - start
|
||||
if fsize < minFrame then
|
||||
minFrame = fsize
|
||||
end
|
||||
if fsize > maxFrame then
|
||||
maxFrame = fsize
|
||||
end
|
||||
frameNo += 1
|
||||
total += n
|
||||
if n < bs then
|
||||
break
|
||||
end
|
||||
end
|
||||
if src.err then
|
||||
return nil, tostring(src.err)
|
||||
end
|
||||
-- unused seek points stay placeholders; STREAMINFO
|
||||
local out = buffer.create(w.pos)
|
||||
buffer.copy(out, 0, w.buf, 0, w.pos)
|
||||
local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest())
|
||||
buffer.copy(out, siData, si, 0, 34)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- streaminfo(...) -> the 34-byte STREAMINFO body
|
||||
function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer
|
||||
local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 }
|
||||
put(w, bs, 16)
|
||||
put(w, bs, 16)
|
||||
put(w, minFrame, 24)
|
||||
put(w, maxFrame, 24)
|
||||
put(w, rate, 20)
|
||||
put(w, ch - 1, 3)
|
||||
put(w, bps - 1, 5)
|
||||
put(w, floor(total / 2 ^ 32), 4)
|
||||
put(w, total % 2 ^ 32, 32)
|
||||
for i = 1, 16 do
|
||||
put(w, string.byte(md5, i), 8)
|
||||
end
|
||||
local out = buffer.create(34)
|
||||
buffer.copy(out, 0, w.buf, 0, 34)
|
||||
return out
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,610 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/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 function crc8(b: buffer, from: number, to: number): number
|
||||
local c = 0
|
||||
for i = from, to - 1 do
|
||||
c = CRC8[bxor(c, readu8(b, i)) + 1]
|
||||
end
|
||||
return c
|
||||
end
|
||||
Frame.crc8 = crc8
|
||||
|
||||
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
|
||||
if crc8(b, pos, p) ~= 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
|
||||
@@ -0,0 +1,11 @@
|
||||
--!strict
|
||||
-- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim,
|
||||
-- fixed, LPC, Rice residuals, stereo decorrelation) with CRC-8 / CRC-16 (Frame), and the frame encoder (Encode).
|
||||
-- Absorbed from flac-luau 7083d0d (same author); the encoder is new. Native FLAC / Ogg FLAC streams, metadata and
|
||||
-- seeking are audio/flac.
|
||||
local Flac = {
|
||||
Frame = require("@rosetta/codecs/audio/Flac/Frame"),
|
||||
Encode = require("@rosetta/codecs/audio/Flac/Encode"),
|
||||
}
|
||||
|
||||
return Flac
|
||||
Reference in new issue
Block a user