ws-m4a: codecs/Aac (AAC-LC decoder: ASC / PCE / ADTS, all tools, SBR/PS extension hook), codecs/Alac (decoder + encoder), audio/m4a (AAC + ALAC read, ALAC write, tags, gapless, seek), audio/aac (ADTS), audio/caf (lpcm/alac/aac/ulaw/alaw read, lpcm/alac write); fixtures checked by ffmpeg / fdkaac / MP4Box
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
8b29568e0f
commit
f66594908c
22 files changed
+5380
No files matched your search
@@ -0,0 +1,427 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
|
||||
-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes,
|
||||
-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple
|
||||
-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message.
|
||||
local readu32, readu8 = buffer.readu32, buffer.readu8
|
||||
local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot
|
||||
local floor = math.floor
|
||||
|
||||
local Decode = {}
|
||||
|
||||
export type State = {
|
||||
frameLength: number,
|
||||
bitDepth: number,
|
||||
pb: number,
|
||||
mb: number,
|
||||
kb: number,
|
||||
channels: number,
|
||||
maxRun: number,
|
||||
scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked)
|
||||
pred: { { number } }, -- per element channel (0, 1): residuals / predictor output
|
||||
mix: { { number } },
|
||||
shift: { number },
|
||||
out: { number }, -- interleaved output samples (integers), frames * channels
|
||||
}
|
||||
|
||||
local POW = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
POW[i + 1] = 2 ^ i
|
||||
end
|
||||
|
||||
-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25.
|
||||
local function bitsAt(b: buffer, pos: number, n: number): number
|
||||
local w = byteswap(readu32(b, rshift(pos, 3)))
|
||||
return rshift(lshift(w, band(pos, 7)), 32 - n)
|
||||
end
|
||||
|
||||
local function signExtend(v: number, bits: number): number
|
||||
local m = POW[bits + 1]
|
||||
v = v % m
|
||||
if v >= m / 2 then
|
||||
v -= m
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits
|
||||
local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number)
|
||||
local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7))
|
||||
local pre = countlz(bnot(w))
|
||||
if pre >= 9 then
|
||||
pos += 9
|
||||
local v
|
||||
if bps > 25 then
|
||||
v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16)
|
||||
else
|
||||
v = bitsAt(b, pos, bps)
|
||||
end
|
||||
return v, pos + bps
|
||||
end
|
||||
pos += pre + 1
|
||||
if k == 1 then
|
||||
return pre, pos
|
||||
end
|
||||
local v = bitsAt(b, pos, k)
|
||||
local x = pre * m
|
||||
if v > 1 then
|
||||
return x + v - 1, pos + k
|
||||
end
|
||||
return x, pos + k - 1
|
||||
end
|
||||
|
||||
-- residuals: n values into out[1..n]; returns the new bit position or -1
|
||||
local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number
|
||||
local history = st.mb
|
||||
local kb = st.kb
|
||||
local signMod = 0
|
||||
local i = 1
|
||||
while i <= n do
|
||||
if pos > limit then
|
||||
return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes
|
||||
end
|
||||
local k = 31 - countlz(floor(history / 512) + 3)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local x
|
||||
x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps)
|
||||
x += signMod
|
||||
signMod = 0
|
||||
out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2
|
||||
if x > 0xFFFF then
|
||||
history = 0xFFFF
|
||||
else
|
||||
history += x * mult - floor(history * mult / 512)
|
||||
end
|
||||
if history < 128 and i < n then
|
||||
if pos > limit then
|
||||
return -1
|
||||
end
|
||||
local lg = if history > 0 then 31 - countlz(history) else 0
|
||||
k = 7 - lg + floor((history + 16) / 64)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local run
|
||||
run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16)
|
||||
if run > 0 then
|
||||
if run > n - i then
|
||||
return -1
|
||||
end
|
||||
for j = i + 1, i + run do
|
||||
out[j] = 0
|
||||
end
|
||||
i += run
|
||||
end
|
||||
if run < 0xFFFF then
|
||||
signMod = 1 -- the next value is not 0 (unless the run hit its maximum)
|
||||
end
|
||||
history = 0
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
return pos
|
||||
end
|
||||
|
||||
-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place
|
||||
local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
|
||||
out[1] = err[1]
|
||||
if n <= 1 then
|
||||
return
|
||||
end
|
||||
if order == 0 then
|
||||
if out ~= err then
|
||||
for i = 2, n do
|
||||
out[i] = err[i]
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
if order == 31 then
|
||||
for i = 2, n do
|
||||
out[i] = signExtend(out[i - 1] + err[i], bps)
|
||||
end
|
||||
return
|
||||
end
|
||||
local i = 2
|
||||
while i <= order + 1 and i <= n do
|
||||
out[i] = signExtend(out[i - 1] + err[i], bps)
|
||||
i += 1
|
||||
end
|
||||
local half = if quant > 0 then POW[quant] else 0
|
||||
local qd = POW[quant + 1]
|
||||
-- coefs[1] multiplies the most recent sample
|
||||
while i <= n do
|
||||
local d = out[i - order - 1]
|
||||
local val = 0
|
||||
for j = 1, order do
|
||||
val += (out[i - j] - d) * coefs[j]
|
||||
end
|
||||
val = floor((val + half) / qd)
|
||||
local e = err[i]
|
||||
out[i] = signExtend(val + d + e, bps)
|
||||
if e ~= 0 then
|
||||
local es = if e > 0 then 1 else -1
|
||||
-- adapt from the oldest sample to the newest while the error keeps its sign
|
||||
for j = order, 1, -1 do
|
||||
if e * es <= 0 then
|
||||
break
|
||||
end
|
||||
local v = d - out[i - j]
|
||||
local sgn = if v > 0 then es elseif v < 0 then -es else 0
|
||||
coefs[j] -= sgn
|
||||
e -= floor(v * sgn / qd) * (order - j + 1)
|
||||
end
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the
|
||||
-- ALAC element order.
|
||||
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
|
||||
if len <= 0 then
|
||||
return nil, "empty packet"
|
||||
end
|
||||
local b = st.scratch
|
||||
if buffer.len(b) < len + 16 then
|
||||
b = buffer.create(len + 64)
|
||||
st.scratch = b
|
||||
end
|
||||
buffer.copy(b, 0, buf, off, len)
|
||||
buffer.fill(b, len, 0, 16)
|
||||
local limit = len * 8
|
||||
local pos = 0
|
||||
local channels = st.channels
|
||||
local ch = 0 -- next output channel
|
||||
local frames = -1
|
||||
local out = st.out
|
||||
while true do
|
||||
if pos + 3 > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
local tag = bitsAt(b, pos, 3)
|
||||
pos += 3
|
||||
if tag == 7 then -- END
|
||||
break
|
||||
elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE
|
||||
local nch = if tag == 1 then 2 else 1
|
||||
if ch + nch > channels then
|
||||
return nil, "more channels than the configuration"
|
||||
end
|
||||
pos += 4 -- element instance tag
|
||||
if bitsAt(b, pos, 12) ~= 0 then
|
||||
return nil, "bad element header"
|
||||
end
|
||||
pos += 12
|
||||
local h = bitsAt(b, pos, 4)
|
||||
pos += 4
|
||||
local partial = rshift(h, 3)
|
||||
local shiftBytes = band(rshift(h, 1), 3)
|
||||
local escape = band(h, 1)
|
||||
if shiftBytes == 3 then
|
||||
return nil, "bad shift"
|
||||
end
|
||||
local n = st.frameLength
|
||||
if partial == 1 then
|
||||
n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16)
|
||||
pos += 32
|
||||
end
|
||||
if n < 1 or n > st.frameLength then
|
||||
return nil, "bad frame length " .. n
|
||||
end
|
||||
if frames >= 0 and n ~= frames then
|
||||
return nil, "elements of different lengths"
|
||||
end
|
||||
frames = n
|
||||
if #out < n * channels then
|
||||
for k = #out + 1, n * channels do
|
||||
out[k] = 0
|
||||
end
|
||||
end
|
||||
local shift = shiftBytes * 8
|
||||
local bps = st.bitDepth - shift + nch - 1
|
||||
if bps > 32 or bps < 1 then
|
||||
return nil, "bad sample size"
|
||||
end
|
||||
if pos > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
local mixBits, mixRes = 0, 0
|
||||
local p0, p1 = st.pred[1], st.pred[2]
|
||||
local m0, m1 = st.mix[1], st.mix[2]
|
||||
local shiftBuf = st.shift
|
||||
if escape == 0 then
|
||||
mixBits = bitsAt(b, pos, 8)
|
||||
mixRes = bitsAt(b, pos + 8, 8)
|
||||
pos += 16
|
||||
if mixRes >= 128 then
|
||||
mixRes -= 256
|
||||
end
|
||||
local mode, denShift, pbFactor, order = {}, {}, {}, {}
|
||||
local coefs = { {}, {} }
|
||||
for c = 1, nch do
|
||||
local x = bitsAt(b, pos, 8)
|
||||
local y = bitsAt(b, pos + 8, 8)
|
||||
pos += 16
|
||||
mode[c], denShift[c] = rshift(x, 4), band(x, 15)
|
||||
pbFactor[c], order[c] = rshift(y, 5), band(y, 31)
|
||||
if pos + order[c] * 16 > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
for j = 1, order[c] do
|
||||
local v = bitsAt(b, pos, 16)
|
||||
pos += 16
|
||||
coefs[c][j] = if v >= 32768 then v - 65536 else v
|
||||
end
|
||||
end
|
||||
if pos > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
local shiftPos = pos
|
||||
if shift > 0 then
|
||||
pos += shift * n * nch
|
||||
end
|
||||
for c = 1, nch do
|
||||
local p = if c == 1 then p0 else p1
|
||||
local mb = if c == 1 then m0 else m1
|
||||
pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st)
|
||||
if pos < 0 or pos > limit then
|
||||
return nil, "bad residuals"
|
||||
end
|
||||
if mode[c] == 15 then
|
||||
predict(p, p, n, bps, {}, 31, 0)
|
||||
elseif mode[c] ~= 0 then
|
||||
return nil, "unknown prediction mode " .. mode[c]
|
||||
end
|
||||
predict(p, mb, n, bps, coefs[c], order[c], denShift[c])
|
||||
end
|
||||
if shift > 0 then
|
||||
local sp = shiftPos
|
||||
for i = 1, n * nch do
|
||||
shiftBuf[i] = bitsAt(b, sp, shift)
|
||||
sp += shift
|
||||
end
|
||||
end
|
||||
else
|
||||
-- uncompressed: interleaved samples of bitDepth bits
|
||||
local bits = st.bitDepth
|
||||
if pos + n * nch * bits > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
for i = 1, n do
|
||||
for c = 1, nch do
|
||||
local v
|
||||
if bits > 25 then
|
||||
v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16)
|
||||
else
|
||||
v = bitsAt(b, pos, bits)
|
||||
end
|
||||
pos += bits
|
||||
v = signExtend(v, bits)
|
||||
if c == 1 then
|
||||
m0[i] = v
|
||||
else
|
||||
m1[i] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
shift = 0
|
||||
end
|
||||
-- unmix + shifted bytes -> interleaved output
|
||||
local sm = POW[shift + 1]
|
||||
if nch == 2 then
|
||||
local den = POW[mixBits + 1]
|
||||
for i = 1, n do
|
||||
local u, v = m0[i], m1[i]
|
||||
local l, r
|
||||
if mixRes ~= 0 then
|
||||
l = u + v - floor(mixRes * v / den)
|
||||
r = l - v
|
||||
else
|
||||
l, r = u, v
|
||||
end
|
||||
if shift > 0 then
|
||||
l = l * sm + shiftBuf[2 * i - 1]
|
||||
r = r * sm + shiftBuf[2 * i]
|
||||
end
|
||||
local o = (i - 1) * channels + ch + 1
|
||||
out[o] = l
|
||||
out[o + 1] = r
|
||||
end
|
||||
else
|
||||
for i = 1, n do
|
||||
local v = m0[i]
|
||||
if shift > 0 then
|
||||
v = v * sm + shiftBuf[i]
|
||||
end
|
||||
out[(i - 1) * channels + ch + 1] = v
|
||||
end
|
||||
end
|
||||
ch += nch
|
||||
elseif tag == 4 then -- DSE
|
||||
pos += 4
|
||||
local align = bitsAt(b, pos, 1)
|
||||
local count = bitsAt(b, pos + 1, 8)
|
||||
pos += 9
|
||||
if count == 255 then
|
||||
count += bitsAt(b, pos, 8)
|
||||
pos += 8
|
||||
end
|
||||
if align == 1 then
|
||||
pos = (pos + 7) // 8 * 8
|
||||
end
|
||||
pos += count * 8
|
||||
elseif tag == 6 then -- FIL
|
||||
local count = bitsAt(b, pos, 4)
|
||||
pos += 4
|
||||
if count == 15 then
|
||||
count += bitsAt(b, pos, 8) - 1
|
||||
pos += 8
|
||||
end
|
||||
pos += count * 8
|
||||
else
|
||||
return nil, "unsupported element " .. tag
|
||||
end
|
||||
if pos > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
end
|
||||
if frames < 0 then
|
||||
return 0, nil
|
||||
end
|
||||
if ch < channels then
|
||||
-- missing channels: silence
|
||||
for i = 1, frames do
|
||||
for c = ch + 1, channels do
|
||||
out[(i - 1) * channels + c] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
return frames, nil
|
||||
end
|
||||
|
||||
-- the scratch state for a configuration
|
||||
function Decode.state(cfg: any): State
|
||||
local n = cfg.frameLength
|
||||
return {
|
||||
frameLength = n,
|
||||
bitDepth = cfg.bitDepth,
|
||||
pb = cfg.pb,
|
||||
mb = cfg.mb,
|
||||
kb = cfg.kb,
|
||||
channels = cfg.channels,
|
||||
maxRun = cfg.maxRun,
|
||||
scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64),
|
||||
pred = { table.create(n, 0), table.create(n, 0) },
|
||||
mix = { table.create(n, 0), table.create(n, 0) },
|
||||
shift = table.create(n * 2, 0),
|
||||
out = table.create(n * cfg.channels, 0),
|
||||
}
|
||||
end
|
||||
|
||||
local _ = readu8
|
||||
return Decode
|
||||
@@ -0,0 +1,427 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
|
||||
-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
|
||||
-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
|
||||
-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
|
||||
-- input. Written for this library from the ALAC format; no third-party code. Never throws.
|
||||
local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
local floor, abs = math.floor, math.abs
|
||||
|
||||
local Encode = {}
|
||||
|
||||
local POW = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
POW[i + 1] = 2 ^ i
|
||||
end
|
||||
|
||||
local DENSHIFT = 9
|
||||
local PB_FACTOR = 4
|
||||
|
||||
export type State = {
|
||||
frameLength: number,
|
||||
bitDepth: number,
|
||||
pb: number,
|
||||
mb: number,
|
||||
kb: number,
|
||||
channels: number,
|
||||
out: buffer, -- packet scratch
|
||||
pos: number, -- bit position in out
|
||||
cap: number, -- bits available
|
||||
u: { number },
|
||||
v: { number },
|
||||
err: { number },
|
||||
work: { number },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit writer
|
||||
local function put(st: State, v: number, n: number)
|
||||
local pos = st.pos
|
||||
if pos + n > st.cap then
|
||||
st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame
|
||||
return
|
||||
end
|
||||
local b = st.out
|
||||
while n > 0 do
|
||||
local byte = rshift(pos, 3)
|
||||
local free = 8 - band(pos, 7)
|
||||
local take = if n < free then n else free
|
||||
local bits = band(rshift(v, n - take), POW[take + 1] - 1)
|
||||
writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take)))
|
||||
pos += take
|
||||
n -= take
|
||||
end
|
||||
st.pos = pos
|
||||
end
|
||||
|
||||
local function putBig(st: State, v: number, n: number)
|
||||
if n > 24 then
|
||||
local lo = v % 65536
|
||||
put(st, (v - lo) / 65536, n - 16)
|
||||
put(st, lo, 16)
|
||||
else
|
||||
put(st, v, n)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rice code
|
||||
local function signExtend(v: number, bits: number): number
|
||||
local m = POW[bits + 1]
|
||||
v = v % m
|
||||
if v >= m / 2 then
|
||||
v -= m
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- the bits of one scalar (no writing)
|
||||
local function scalarBits(x: number, k: number, m: number, bps: number): number
|
||||
local pre = if k == 1 then x else floor(x / m)
|
||||
if pre >= 9 then
|
||||
return 9 + bps
|
||||
end
|
||||
if k == 1 then
|
||||
return pre + 1
|
||||
end
|
||||
local r = x - pre * m
|
||||
return pre + 1 + (if r == 0 then k - 1 else k)
|
||||
end
|
||||
|
||||
local function scalar(st: State, x: number, k: number, m: number, bps: number)
|
||||
local pre = if k == 1 then x else floor(x / m)
|
||||
if pre >= 9 then
|
||||
put(st, 511, 9)
|
||||
putBig(st, x, bps)
|
||||
return
|
||||
end
|
||||
-- pre ones and a zero
|
||||
put(st, POW[pre + 2] - 2, pre + 1)
|
||||
if k ~= 1 then
|
||||
local r = x - pre * m
|
||||
if r == 0 then
|
||||
put(st, 0, k - 1)
|
||||
else
|
||||
put(st, r + 1, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- code the residuals e[1..n] (write = false: just count the bits)
|
||||
local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number
|
||||
local history = st.mb
|
||||
local kb = st.kb
|
||||
local signMod = 0
|
||||
local bits = 0
|
||||
local i = 1
|
||||
while i <= n do
|
||||
local k = 31 - countlz(floor(history / 512) + 3)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local v = e[i]
|
||||
local zz = if v >= 0 then 2 * v else -2 * v - 1
|
||||
local x = zz - signMod
|
||||
signMod = 0
|
||||
local m = POW[k + 1] - 1
|
||||
if write then
|
||||
scalar(st, x, k, m, bps)
|
||||
else
|
||||
bits += scalarBits(x, k, m, bps)
|
||||
end
|
||||
if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back
|
||||
history = 0xFFFF
|
||||
else
|
||||
history += zz * mult - floor(history * mult / 512)
|
||||
end
|
||||
if history < 128 and i < n then
|
||||
local lg = if history > 0 then 31 - countlz(history) else 0
|
||||
k = 7 - lg + floor((history + 16) / 64)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local run = 0
|
||||
while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do
|
||||
run += 1
|
||||
end
|
||||
m = POW[k + 1] - 1
|
||||
if write then
|
||||
scalar(st, run, k, m, 16)
|
||||
else
|
||||
bits += scalarBits(run, k, m, 16)
|
||||
end
|
||||
i += run
|
||||
if run < 0xFFFF then
|
||||
signMod = 1
|
||||
end
|
||||
history = 0
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
return bits
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ prediction
|
||||
-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder)
|
||||
local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
|
||||
e[1] = x[1]
|
||||
if n <= 1 then
|
||||
return
|
||||
end
|
||||
local i = 2
|
||||
while i <= order + 1 and i <= n do
|
||||
e[i] = signExtend(x[i] - x[i - 1], bps)
|
||||
i += 1
|
||||
end
|
||||
local half = POW[quant]
|
||||
local qd = POW[quant + 1]
|
||||
while i <= n do
|
||||
local d = x[i - order - 1]
|
||||
local val = 0
|
||||
for j = 1, order do
|
||||
val += (x[i - j] - d) * coefs[j]
|
||||
end
|
||||
val = floor((val + half) / qd)
|
||||
local r = signExtend(x[i] - val - d, bps)
|
||||
e[i] = r
|
||||
if r ~= 0 then
|
||||
local es = if r > 0 then 1 else -1
|
||||
for j = order, 1, -1 do
|
||||
if r * es <= 0 then
|
||||
break
|
||||
end
|
||||
local v = d - x[i - j]
|
||||
local sgn = if v > 0 then es elseif v < 0 then -es else 0
|
||||
coefs[j] -= sgn
|
||||
r -= floor(v * sgn / qd) * (order - j + 1)
|
||||
end
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised
|
||||
local function lpc(x: { number }, n: number, order: number, work: { number }): { number }
|
||||
local ac = table.create(order + 1, 0)
|
||||
for i = 1, n do
|
||||
local t = (2 * (i - 1) - (n - 1)) / (n + 1)
|
||||
work[i] = x[i] * (1 - t * t)
|
||||
end
|
||||
for lag = 0, order do
|
||||
local s = 0
|
||||
for i = lag + 1, n do
|
||||
s += work[i] * work[i - lag]
|
||||
end
|
||||
ac[lag + 1] = s
|
||||
end
|
||||
local coefs = table.create(order, 0)
|
||||
if ac[1] <= 0 then
|
||||
return coefs
|
||||
end
|
||||
ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable
|
||||
local a = table.create(order + 1, 0)
|
||||
local tmp = table.create(order + 1, 0)
|
||||
local errv = ac[1]
|
||||
for i = 1, order do
|
||||
local acc = ac[i + 1]
|
||||
for j = 1, i - 1 do
|
||||
acc -= a[j] * ac[i - j + 1]
|
||||
end
|
||||
local kc = acc / errv
|
||||
for j = 1, i - 1 do
|
||||
tmp[j] = a[j] - kc * a[i - j]
|
||||
end
|
||||
for j = 1, i - 1 do
|
||||
a[j] = tmp[j]
|
||||
end
|
||||
a[i] = kc
|
||||
errv *= (1 - kc * kc)
|
||||
if errv <= 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
local scale = POW[DENSHIFT + 1]
|
||||
for j = 1, order do
|
||||
coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767)
|
||||
end
|
||||
return coefs
|
||||
end
|
||||
|
||||
-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits
|
||||
local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number)
|
||||
local mult = floor(st.pb * PB_FACTOR / 4)
|
||||
local bestOrder, bestCoefs, bestBits = 0, {}, math.huge
|
||||
for _, order in { 4, 8 } do
|
||||
if order >= n then
|
||||
continue
|
||||
end
|
||||
local coefs = lpc(x, n, order, st.work)
|
||||
local trial = table.clone(coefs)
|
||||
residuals(x, st.err, n, bps, trial, order, DENSHIFT)
|
||||
local bits = rice(st, st.err, n, bps, mult, false) + order * 16
|
||||
if bits < bestBits then
|
||||
bestOrder, bestCoefs, bestBits = order, coefs, bits
|
||||
end
|
||||
end
|
||||
if bestBits == math.huge then
|
||||
-- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction)
|
||||
for i = 1, n do
|
||||
st.err[i] = x[i]
|
||||
end
|
||||
return 0, {}, rice(st, st.err, n, bps, mult, false)
|
||||
end
|
||||
return bestOrder, bestCoefs, bestBits
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frame
|
||||
-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index
|
||||
-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts
|
||||
function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer
|
||||
local channels, depth = st.channels, st.bitDepth
|
||||
local n = frames
|
||||
local partial = n ~= st.frameLength
|
||||
local rawBits = n * channels * depth
|
||||
local need = rawBits + 64 * #elements + 64
|
||||
if st.cap < need + 8 * 32 * 2 * #elements * 16 then
|
||||
local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16
|
||||
st.out = buffer.create(bytes)
|
||||
st.cap = bytes * 8
|
||||
end
|
||||
buffer.fill(st.out, 0, 0)
|
||||
st.pos = 0
|
||||
local u, v = st.u, st.v
|
||||
local mult = floor(st.pb * PB_FACTOR / 4)
|
||||
local compressed = true
|
||||
local ch = 1
|
||||
for _, nch in elements do
|
||||
local a, b = map[ch], map[ch + 1]
|
||||
local bps = depth + nch - 1
|
||||
local mixRes = 0
|
||||
if nch == 2 then
|
||||
-- the mix with the smallest first-difference energy
|
||||
local best = math.huge
|
||||
for res = 0, 4 do
|
||||
local cost = 0
|
||||
local pu, pv = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local l = samples[first + i * channels + a - 1]
|
||||
local r = samples[first + i * channels + b - 1]
|
||||
local uu, vv
|
||||
if res == 0 then
|
||||
uu, vv = l, r
|
||||
else
|
||||
uu, vv = floor((res * l + (4 - res) * r) / 4), l - r
|
||||
end
|
||||
cost += abs(uu - pu) + abs(vv - pv)
|
||||
pu, pv = uu, vv
|
||||
end
|
||||
if cost < best then
|
||||
best, mixRes = cost, res
|
||||
end
|
||||
end
|
||||
for i = 1, n do
|
||||
local l = samples[first + (i - 1) * channels + a - 1]
|
||||
local r = samples[first + (i - 1) * channels + b - 1]
|
||||
if mixRes == 0 then
|
||||
u[i], v[i] = l, r
|
||||
else
|
||||
u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r
|
||||
end
|
||||
end
|
||||
else
|
||||
for i = 1, n do
|
||||
u[i] = samples[first + (i - 1) * channels + a - 1]
|
||||
end
|
||||
end
|
||||
-- header
|
||||
put(st, if nch == 2 then 1 else 0, 3)
|
||||
put(st, 0, 4)
|
||||
put(st, 0, 12)
|
||||
put(st, if partial then 1 else 0, 1)
|
||||
put(st, 0, 2)
|
||||
put(st, 0, 1)
|
||||
if partial then
|
||||
putBig(st, n, 32)
|
||||
end
|
||||
put(st, if mixRes == 0 then 0 else 2, 8)
|
||||
put(st, mixRes, 8)
|
||||
local orders, coefsList = {}, {}
|
||||
for c = 1, nch do
|
||||
local x = if c == 1 then u else v
|
||||
local order, coefs = analyse(st, x, n, bps)
|
||||
orders[c], coefsList[c] = order, coefs
|
||||
put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift
|
||||
put(st, PB_FACTOR * 32 + order, 8)
|
||||
for j = 1, order do
|
||||
put(st, coefs[j] % 65536, 16)
|
||||
end
|
||||
end
|
||||
for c = 1, nch do
|
||||
local x = if c == 1 then u else v
|
||||
local order = orders[c]
|
||||
if order == 0 then
|
||||
for i = 1, n do
|
||||
st.err[i] = x[i]
|
||||
end
|
||||
else
|
||||
residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT)
|
||||
end
|
||||
rice(st, st.err, n, bps, mult, true)
|
||||
end
|
||||
ch += nch
|
||||
if st.pos > rawBits + 64 * #elements then
|
||||
compressed = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if not compressed then
|
||||
-- uncompressed frame
|
||||
buffer.fill(st.out, 0, 0)
|
||||
st.pos = 0
|
||||
ch = 1
|
||||
for _, nch in elements do
|
||||
put(st, if nch == 2 then 1 else 0, 3)
|
||||
put(st, 0, 4)
|
||||
put(st, 0, 12)
|
||||
put(st, if partial then 1 else 0, 1)
|
||||
put(st, 0, 2)
|
||||
put(st, 1, 1)
|
||||
if partial then
|
||||
putBig(st, n, 32)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
for c = 0, nch - 1 do
|
||||
putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth)
|
||||
end
|
||||
end
|
||||
ch += nch
|
||||
end
|
||||
end
|
||||
put(st, 7, 3) -- END
|
||||
local bytes = (st.pos + 7) // 8
|
||||
local pkt = buffer.create(bytes)
|
||||
buffer.copy(pkt, 0, st.out, 0, bytes)
|
||||
return pkt
|
||||
end
|
||||
|
||||
function Encode.state(cfg: any): State
|
||||
local n = cfg.frameLength
|
||||
return {
|
||||
frameLength = n,
|
||||
bitDepth = cfg.bitDepth,
|
||||
pb = cfg.pb,
|
||||
mb = cfg.mb,
|
||||
kb = cfg.kb,
|
||||
channels = cfg.channels,
|
||||
out = buffer.create(16),
|
||||
pos = 0,
|
||||
cap = 0,
|
||||
u = table.create(n, 0),
|
||||
v = table.create(n, 0),
|
||||
err = table.create(n, 0),
|
||||
work = table.create(n, 0),
|
||||
}
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,251 @@
|
||||
--!strict
|
||||
-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
|
||||
-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
|
||||
-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
|
||||
-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
|
||||
--
|
||||
-- local Alac = require("@formats/codecs/Alac")
|
||||
-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
|
||||
-- local dec = Alac.decoder(cfg)
|
||||
-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
|
||||
-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })
|
||||
-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096)
|
||||
-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Decode = require("@formats/codecs/Alac/Decode")
|
||||
local Encode = require("@formats/codecs/Alac/Encode")
|
||||
|
||||
local Alac = {}
|
||||
|
||||
export type Config = {
|
||||
frameLength: number, -- samples per packet (4096)
|
||||
compatibleVersion: number,
|
||||
bitDepth: number,
|
||||
pb: number, -- 40
|
||||
mb: number, -- 10
|
||||
kb: number, -- 14
|
||||
channels: number,
|
||||
maxRun: number, -- 255
|
||||
maxFrameBytes: number,
|
||||
avgBitRate: number,
|
||||
sampleRate: number,
|
||||
}
|
||||
|
||||
-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count
|
||||
local TO_WAV: { { number } } = {
|
||||
{ 1 },
|
||||
{ 1, 2 },
|
||||
{ 3, 1, 2 },
|
||||
{ 3, 1, 2, 4 },
|
||||
{ 3, 1, 2, 4, 5 },
|
||||
{ 3, 1, 2, 5, 6, 4 },
|
||||
{ 3, 1, 2, 5, 6, 7, 4 },
|
||||
{ 3, 7, 8, 1, 2, 5, 6, 4 },
|
||||
}
|
||||
-- the element layout (channels per element) the encoder writes
|
||||
local ELEMENTS: { { number } } = {
|
||||
{ 1 },
|
||||
{ 2 },
|
||||
{ 1, 2 },
|
||||
{ 1, 2, 1 },
|
||||
{ 1, 2, 2 },
|
||||
{ 1, 2, 2, 1 },
|
||||
{ 1, 2, 2, 1, 1 },
|
||||
{ 1, 2, 2, 2, 1 },
|
||||
}
|
||||
Alac.TO_WAV = TO_WAV
|
||||
|
||||
-- config(buf, offset?, length?) -> Config | nil, Err
|
||||
function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?)
|
||||
local r = Bytes.reader(buf, offset, length)
|
||||
-- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie
|
||||
for _ = 1, 2 do
|
||||
local typ = r:peek(4, 4)
|
||||
if typ == "frma" then
|
||||
r:skip(12)
|
||||
elseif typ == "alac" then
|
||||
r:skip(12)
|
||||
end
|
||||
end
|
||||
if r:remaining() < 24 then
|
||||
return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes")
|
||||
end
|
||||
local c: Config = {
|
||||
frameLength = r:u32be(),
|
||||
compatibleVersion = r:u8(),
|
||||
bitDepth = r:u8(),
|
||||
pb = r:u8(),
|
||||
mb = r:u8(),
|
||||
kb = r:u8(),
|
||||
channels = r:u8(),
|
||||
maxRun = r:u16be(),
|
||||
maxFrameBytes = r:u32be(),
|
||||
avgBitRate = r:u32be(),
|
||||
sampleRate = r:u32be(),
|
||||
}
|
||||
if c.compatibleVersion ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion)
|
||||
end
|
||||
if c.frameLength < 1 or c.frameLength > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength)
|
||||
end
|
||||
if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth)
|
||||
end
|
||||
if c.channels < 1 or c.channels > 8 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels")
|
||||
end
|
||||
if c.kb < 1 or c.kb > 24 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb)
|
||||
end
|
||||
return c, nil
|
||||
end
|
||||
|
||||
-- cookie(cfg) -> the 24-byte ALACSpecificConfig
|
||||
function Alac.cookie(c: Config): buffer
|
||||
local w = Bytes.writer(24)
|
||||
w:u32be(c.frameLength)
|
||||
w:u8(0)
|
||||
w:u8(c.bitDepth)
|
||||
w:u8(c.pb)
|
||||
w:u8(c.mb)
|
||||
w:u8(c.kb)
|
||||
w:u8(c.channels)
|
||||
w:u16be(c.maxRun)
|
||||
w:u32be(c.maxFrameBytes)
|
||||
w:u32be(c.avgBitRate)
|
||||
w:u32be(c.sampleRate)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Decoder = {
|
||||
config: Config,
|
||||
pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits)
|
||||
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
|
||||
state: Decode.State,
|
||||
}
|
||||
|
||||
local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
|
||||
local o = offset or 0
|
||||
local n = length or (buffer.len(buf) - o)
|
||||
if o < 0 or n < 0 or o + n > buffer.len(buf) then
|
||||
return nil, Err.new(Err.ARG, "packet range out of the buffer")
|
||||
end
|
||||
local frames, msg = Decode.frame(self.state, buf, o, n)
|
||||
if not frames then
|
||||
return nil, Err.new(Err.CORRUPT, msg or "bad packet", o)
|
||||
end
|
||||
local ch = self.config.channels
|
||||
local src, dst = self.state.out, self.pcm
|
||||
if ch <= 2 then
|
||||
for i = 1, frames * ch do
|
||||
dst[i] = src[i]
|
||||
end
|
||||
else
|
||||
local map = TO_WAV[ch]
|
||||
for f = 0, frames - 1 do
|
||||
local base = f * ch
|
||||
for k = 1, ch do
|
||||
dst[base + map[k]] = src[base + k]
|
||||
end
|
||||
end
|
||||
end
|
||||
return frames, nil
|
||||
end
|
||||
|
||||
-- decoder(cfg) -> Decoder
|
||||
function Alac.decoder(cfg: Config): Decoder
|
||||
return {
|
||||
config = cfg,
|
||||
pcm = table.create(cfg.frameLength * cfg.channels, 0),
|
||||
decode = decode,
|
||||
state = Decode.state(cfg),
|
||||
}
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encoder
|
||||
export type Encoder = {
|
||||
config: Config,
|
||||
encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?),
|
||||
state: Encode.State,
|
||||
bytes: number,
|
||||
frames: number,
|
||||
}
|
||||
|
||||
local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?)
|
||||
local cfg = self.config
|
||||
if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples")
|
||||
end
|
||||
if first < 1 or first + frames * cfg.channels - 1 > #samples then
|
||||
return nil, Err.new(Err.ARG, "encode: the samples end early")
|
||||
end
|
||||
local ch = cfg.channels
|
||||
local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch])
|
||||
local n = buffer.len(pkt)
|
||||
self.bytes += n
|
||||
self.frames += frames
|
||||
if n > cfg.maxFrameBytes then
|
||||
cfg.maxFrameBytes = n
|
||||
end
|
||||
if self.frames > 0 then
|
||||
cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames)
|
||||
end
|
||||
return pkt, nil
|
||||
end
|
||||
|
||||
export type EncoderOptions = {
|
||||
sampleRate: number,
|
||||
channels: number, -- 1 .. 8
|
||||
bitDepth: number?, -- 16 (default), 20 or 24
|
||||
frameLength: number?, -- default 4096
|
||||
}
|
||||
|
||||
-- encoder(opts) -> Encoder | nil, Err
|
||||
function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?)
|
||||
if type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "encoder: expected options")
|
||||
end
|
||||
local depth = opts.bitDepth or 16
|
||||
local ch = opts.channels
|
||||
if depth ~= 16 and depth ~= 20 and depth ~= 24 then
|
||||
return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24")
|
||||
end
|
||||
if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels")
|
||||
end
|
||||
local sr = opts.sampleRate
|
||||
if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encoder: bad sampleRate")
|
||||
end
|
||||
local fl = opts.frameLength or 4096
|
||||
if fl < 16 or fl > 16384 or fl % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384")
|
||||
end
|
||||
local cfg: Config = {
|
||||
frameLength = fl,
|
||||
compatibleVersion = 0,
|
||||
bitDepth = depth,
|
||||
pb = 40,
|
||||
mb = 10,
|
||||
kb = 14,
|
||||
channels = ch,
|
||||
maxRun = 255,
|
||||
maxFrameBytes = 0,
|
||||
avgBitRate = 0,
|
||||
sampleRate = sr,
|
||||
}
|
||||
return {
|
||||
config = cfg,
|
||||
encode = encode,
|
||||
state = Encode.state(cfg),
|
||||
bytes = 0,
|
||||
frames = 0,
|
||||
}, nil
|
||||
end
|
||||
|
||||
return Alac
|
||||
Reference in new issue
Block a user