ws-audio2: merge ws/audio2-adpcm (codecs/audio/Adpcm, Qoa; adx, vag, brstm/bcstm/bfstm, raw adpcm, qoa; wav/aiff/caf/xm ADPCM)

This commit is contained in:
4DBug committed 2026-10-31 15:10:09 -05:00
commit 703af4cc71
43 files changed
+5121 -197

No files matched your search

+328
View File
@@ -0,0 +1,328 @@
--!strict
-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the
-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus
-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it
-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else
-- decodes forward from the nearest earlier snapshot. New in formats-luau.
--
-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...)
-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter)
-- frames = total, -- output frames
-- state = st, -- the codec state buffer decode advances
-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0
-- restore = function(i) return false end, -- optional: set st for packet i, true if it could
-- })
--
-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err:
-- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every
-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM)
-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG)
-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes
-- per channel), raw or inside AIFF-C / CAF
--
-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream).
local Err = require("@formats/core/Err")
local Stream = require("@formats/codecs/audio/Stream")
local Adpcm = require("@formats/codecs/audio/Adpcm")
local Decoder = {}
export type Spec = {
count: number,
packetFrames: number,
frames: number,
state: buffer,
decode: (i: number, out: buffer) -> (number?, Err.Err?),
restore: ((i: number) -> boolean)?,
}
function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?)
local ch = dec.channels
local pf = spec.packetFrames
local st = spec.state
local out = buffer.create(pf * ch * 4)
local decodeP = spec.decode
local restore = spec.restore
local snaps: { [number]: buffer } = {}
local nextPacket = 1
local function snap(i: number)
if not snaps[i] then
local b = buffer.create(buffer.len(st))
buffer.copy(b, 0, st)
snaps[i] = b
end
end
snap(1)
local function decode(i: number): (number?, Err.Err?)
if i ~= nextPacket then
if snaps[i] then
buffer.copy(st, 0, snaps[i])
elseif restore and restore(i) then
-- the format set the state (BRSTM's seek table)
else
local j = i - 1
while j > 1 and not snaps[j] do
j -= 1
end
buffer.copy(st, 0, snaps[j])
for k = j, i - 1 do
local n, e = decodeP(k, out)
if not n then
return nil, e
end
snap(k + 1)
end
end
end
local n, e = decodeP(i, out)
if n then
nextPacket = i + 1
snap(i + 1)
end
return n, e
end
return Stream.packets(dec, {
count = spec.count,
start = function(i: number): number
return (i - 1) * pf
end,
decode = decode,
pcm = function(): buffer
return out
end,
reset = function() end,
stop = spec.frames,
})
end
-- ------------------------------------------------------------------------------------------------ layouts
local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame
local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame
-- PCM samples of one channel into every ds-th float of dst from float d
local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number)
if kind == "s8" then
for k = 0, n - 1 do
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128)
end
elseif kind == "s16le" then
for k = 0, n - 1 do
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768)
end
else
for k = 0, n - 1 do
local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1)
buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768)
end
end
end
export type InterleavedSpec = {
kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way
buf: buffer,
offset: number, -- the first row
size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames)
interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple)
lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave
frames: number?, -- frames to output (default: what the data holds)
c1: number?, -- adx: the predictor (Adpcm.adxCoefs)
c2: number?,
v3: boolean?, -- adx: version 3 rounding
coefs: buffer?, -- dsp: 16 i32 per channel
hist: { number }?, -- initial history, h1 / h2 per channel (default 0)
restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC)
}
-- interleaved(dec, spec) -> Decoder | nil, Err
function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?)
local ch = dec.channels
local kind = spec.kind
local fsize, spf = FRAME[kind], SPF[kind]
local il = spec.interleave
local last = spec.lastInterleave or il
if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then
return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il))
end
local buf, base, size = spec.buf, spec.offset, spec.size
local rowBytes = il * ch
-- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file)
local rows = math.max(1, math.ceil(size / rowBytes))
local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel
local width = if r == rows - 1 then last else il
-- channel c sits at c * width in the row: the last channel is the one a cut file shortens
local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width)
return (per // fsize) * spf
end
local fullFrames = (il // fsize) * spf
local total = (rows - 1) * fullFrames + rowFrames(rows - 1)
local frames = math.min(spec.frames or total, total)
local st = buffer.create(8 * ch)
if spec.hist then
for c = 0, ch - 1 do
buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0)
buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0)
end
end
local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames)
local pf = rowsPer * fullFrames
local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs
local restore = spec.restore
dec.frames = frames
dec.duration = frames / dec.sampleRate
return Decoder.packets(dec, {
count = math.max(1, math.ceil(frames / pf)),
packetFrames = pf,
frames = frames,
state = st,
restore = if restore
then function(i: number): boolean
return restore(i - 1, st)
end
else nil,
decode = function(i: number, out: buffer): (number?, Err.Err?)
local got = 0
for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do
local n = math.min(rowFrames(r), frames - r * fullFrames)
if n <= 0 then
break
end
local nf = math.ceil(n / spf)
local width = if r == rows - 1 then last else il
for c = 0, ch - 1 do
local p = base + r * rowBytes + c * width
local d = got * ch + c
if kind == "psx" then
Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch)
elseif kind == "adx" then
Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch)
elseif kind == "dsp" then
Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch)
else
pcm(kind, buf, p, n, out, d, ch)
end
end
got += n
end
return got, nil
end,
})
end
export type NibbleSpec = {
buf: buffer,
offset: number,
size: number, -- bytes
hi: boolean?, -- the high nibble first (DVI / KVAG); default low first
frames: number?, -- default: every whole frame of nibbles
}
-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ...
function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?)
local ch = dec.channels
local buf, base = spec.buf, spec.offset
local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch)
local st = buffer.create(8 * ch)
local hi = spec.hi == true
dec.frames = frames
dec.duration = frames / dec.sampleRate
return Decoder.packets(dec, {
count = math.max(1, math.ceil(frames / 4096)),
packetFrames = 4096,
frames = frames,
state = st,
decode = function(i: number, out: buffer): (number?, Err.Err?)
local f0 = (i - 1) * 4096
local n = math.min(4096, frames - f0)
for c = 0, ch - 1 do
Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch)
end
return n, nil
end,
})
end
export type BlockSpec = {
kind: "ms" | "ima_wav" | "ima_qt",
buf: buffer,
offset: number,
size: number,
blockAlign: number?, -- ms / ima_wav: bytes per block
frames: number?, -- default: what the blocks hold
coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs)
}
-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers
function Decoder.blockFrames(kind: string, ba: number, ch: number): number?
if kind == "ima_qt" then
return 64
elseif kind == "ms" then
return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil
end
return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil
end
-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has
function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?)
local ch = dec.channels
local kind = spec.kind
local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0
local spb = Decoder.blockFrames(kind, ba, ch)
if not spb then
return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small")
end
if spb * ch > 2 ^ 20 then
return nil, Err.new(Err.LIMIT, "ADPCM block too large")
end
local buf, base, size = spec.buf, spec.offset, spec.size
local full = size // ba
local rest = size - full * ba
local total = full * spb
if kind ~= "ima_qt" and rest > 0 then
-- a partial last block: the frames it holds whole
if kind == "ms" then
total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0
elseif rest >= 4 * ch then
total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8)
end
end
local frames = math.min(spec.frames or total, total)
local ncoef = 7
local cf = spec.coefs
if cf and #cf >= 2 then
ncoef = math.min(256, #cf // 2)
end
local coefs = buffer.create(ncoef * 8)
for k = 0, ncoef - 1 do
buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1])
buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1])
end
local scratch = buffer.create(20 * ch)
dec.frames = frames
dec.duration = frames / dec.sampleRate
dec.blockAlign = ba
dec.samplesPerBlock = spb
return Decoder.packets(dec, {
count = math.max(1, math.ceil(frames / spb)),
packetFrames = spb,
frames = frames,
state = scratch,
decode = function(i: number, out: buffer): (number?, Err.Err?)
local off = base + (i - 1) * ba
local avail = math.min(ba, base + size - off)
if kind == "ms" then
return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil
elseif kind == "ima_wav" then
return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil
end
if avail < ba then
return 0, nil
end
for c = 0, ch - 1 do
Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch)
end
return 64, nil
end,
})
end
return Decoder
+707
View File
@@ -0,0 +1,707 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in formats-luau; the IMA and
-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo
-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it:
-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024
-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts.
--
-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running
-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2),
-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder).
--
-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ...
-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples
-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI)
-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block
-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples
-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2
-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples
-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples
-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples)
-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each)
--
-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are
-- documented on each). Never throws.
local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32
local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16
local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift
local floor = math.floor
local Adpcm = {}
-- ------------------------------------------------------------------------------------------------ IMA
local IMA_STEP = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060,
1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484,
7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767,
}
local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as
-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently)
local IMA_DIFF = table.create(89 * 8, 0)
-- IMA_NEXT[index * 16 + nibble + 1]: the next step index
local IMA_NEXT = table.create(89 * 16, 0)
for i = 0, 88 do
local step = IMA_STEP[i + 1]
for n = 0, 7 do
local d = rshift(step, 3)
if band(n, 1) ~= 0 then
d += rshift(step, 2)
end
if band(n, 2) ~= 0 then
d += rshift(step, 1)
end
if band(n, 4) ~= 0 then
d += step
end
IMA_DIFF[i * 8 + n + 1] = d
end
for n = 0, 15 do
IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88)
end
end
Adpcm.IMA_STEP = IMA_STEP
-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is
-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes
-- p .. p + (q0 + (count - 1) * qs) // 2.
function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number,
dst: buffer, d: number, ds: number)
local pred = readi32(st, so)
local index = math.clamp(readi32(st, so + 4), 0, 88)
local q = q0
local o = d * 4
local os = ds * 4
for _ = 1, count do
local b = readu8(src, p + rshift(q, 1))
local nib
if (band(q, 1) == 0) == hi then
nib = rshift(b, 4)
else
nib = band(b, 15)
end
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
if nib >= 8 then
pred -= diff
if pred < -32768 then
pred = -32768
end
else
pred += diff
if pred > 32767 then
pred = 32767
end
end
index = IMA_NEXT[index * 16 + nib + 1]
writef32(dst, o, pred / 32768)
o += os
q += qs
end
writei32(st, so, pred)
writei32(st, so + 4, index)
end
-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step
-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while
-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet
-- (zeros before the first).
function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number)
local h = readu8(src, p) * 256 + readu8(src, p + 1)
local pred = band(h, 0xFF80)
if pred >= 32768 then
pred -= 65536
end
local index = band(h, 0x7F)
if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then
writei32(st, so, pred)
writei32(st, so + 4, index)
end
Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds)
end
-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the
-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the
-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float
-- index d; returns the frame count (<= spb).
function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number
if avail < 4 * ch then
return 0
end
local groups = (avail - 4 * ch) // (4 * ch)
local frames = math.min(spb, 1 + groups * 8)
local o = d * 4
for c = 0, ch - 1 do
local pred = readi16(src, off + c * 4)
local index = math.min(readu8(src, off + c * 4 + 2), 88)
writef32(dst, o + c * 4, pred / 32768)
local f = 1
local g = 0
while f < frames do
local p = off + 4 * ch + (g * ch + c) * 4
local k = 0
while k < 8 and f < frames do
local b = readu8(src, p + rshift(k, 1))
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
if nib >= 8 then
pred -= diff
if pred < -32768 then
pred = -32768
end
else
pred += diff
if pred > 32767 then
pred = 32767
end
end
index = IMA_NEXT[index * 16 + nib + 1]
writef32(dst, o + (f * ch + c) * 4, pred / 32768)
f += 1
k += 1
end
g += 1
end
end
return frames
end
-- ------------------------------------------------------------------------------------------------ MS ADPCM
local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 }
Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 }
-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for
-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x
-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from
-- float index d; returns the frame count (<= spb).
function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number,
coefs: buffer, ncoef: number, state: buffer): number
local hdr = 7 * ch
if avail < hdr or ncoef < 1 then
return 0
end
local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch)
local o = d * 4
for c = 0, ch - 1 do
local pi = math.min(readu8(src, off + c), ncoef - 1)
local idelta = readi16(src, off + ch + c * 2)
local s1 = readi16(src, off + 3 * ch + c * 2)
local s2 = readi16(src, off + 5 * ch + c * 2)
local so = c * 20
writei32(state, so, readi32(coefs, pi * 8))
writei32(state, so + 4, readi32(coefs, pi * 8 + 4))
writei32(state, so + 8, idelta)
writei32(state, so + 12, s1)
writei32(state, so + 16, s2)
writef32(dst, o + c * 4, s2 / 32768)
if frames > 1 then
writef32(dst, o + (ch + c) * 4, s1 / 32768)
end
end
local total = (frames - 2) * ch
for k = 0, total - 1 do
local b = readu8(src, off + hdr + rshift(k, 1))
local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
local so = (k % ch) * 20
local c1, c2 = readi32(state, so), readi32(state, so + 4)
local idelta = readi32(state, so + 8)
local s1, s2 = readi32(state, so + 12), readi32(state, so + 16)
local p = s1 * c1 + s2 * c2
p = if p >= 0 then p // 256 else -((-p) // 256)
p += (if nib >= 8 then nib - 16 else nib) * idelta
if p > 32767 then
p = 32767
elseif p < -32768 then
p = -32768
end
idelta = (MS_ADAPT[nib + 1] * idelta) // 256
if idelta < 16 then
idelta = 16
elseif idelta > 2796202 then -- INT_MAX / 768
idelta = 2796202
end
writei32(state, so + 8, idelta)
writei32(state, so + 12, p)
writei32(state, so + 16, s1)
writef32(dst, o + (2 * ch + k) * 4, p / 32768)
end
return frames
end
-- ------------------------------------------------------------------------------------------------ CRI ADX
local F32 = buffer.create(4)
local function f32(x: number): number
writef32(F32, 0, x)
return readf32(F32, 0)
end
-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the
-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it
function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number)
if rate <= 0 then
return 0, 0
end
local z = f32(math.cos(f32(2 * math.pi * cutoff / rate)))
local a = f32(math.sqrt(2) - z)
local b = f32(math.sqrt(2) - 1)
local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b)
local c1 = c * 8192
local c2 = f32(c * c) * -4096
c1 = if c1 >= 0 then floor(c1) else -floor(-c1)
c2 = if c2 >= 0 then floor(c2) else -floor(-c2)
return c1, c2
end
-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from
-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as
-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples.
function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean,
st: buffer, so: number, dst: buffer, d: number, ds: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
local o = d * 4
local os = ds * 4
for f = 0, nframes - 1 do
local fp = p + f * pstride
local scale = readu8(src, fp) * 256 + readu8(src, fp + 1)
if scale == 0x8001 then
scale = 0
elseif scale >= 32768 then
scale -= 65535 -- the signed value + 1
else
scale += 1
end
for k = 0, 31 do
local b = readu8(src, fp + 2 + rshift(k, 1))
local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
if n >= 8 then
n -= 16
end
local s
if v3 then
s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096
else
s = n * scale + (c1 * h1 + c2 * h2) // 4096
end
if s > 32767 then
s = 32767
elseif s < -32768 then
s = -32768
end
h2 = h1
h1 = s
writef32(dst, o, s / 32768)
o += os
end
end
writei32(st, so, h1)
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ PS-ADPCM
local PSX1 = { 0, 60, 115, 98, 122 }
local PSX2 = { 0, 0, -52, -55, -60 }
-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it:
-- exact in integers while the products fit a float's 24 bits
local function psxPred(f: number, h1: number, h2: number): number
local x = PSX1[f] * h1 + PSX2[f] * h2
if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then
return 4 * x
end
local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256
return if v >= 0 then floor(v) else -floor(-v)
end
-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart
-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The
-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples.
function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer,
d: number, ds: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
local o = d * 4
local os = ds * 4
for f = 0, nframes - 1 do
local fp = p + f * pstride
local head = readu8(src, fp)
local filter = rshift(head, 4)
local shift = band(head, 15)
if filter > 4 then
filter = 0
end
if shift > 12 then
shift = 9
end
local mul = 2 ^ (20 - shift)
local fi = filter + 1
local silent = band(readu8(src, fp + 1), 15) == 7
for k = 0, 27 do
local s = 0
if not silent then
local b = readu8(src, fp + 2 + rshift(k, 1))
local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
if n >= 8 then
n -= 16
end
s = (n * mul + psxPred(fi, h1, h2)) // 256
end
h2 = h1
h1 = s
if s > 32767 then
s = 32767
elseif s < -32768 then
s = -32768
end
writef32(dst, o, s / 32768)
o += os
end
end
writei32(st, so, h1)
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ Nintendo DSP
-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first).
-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p ..
-- p + ceil(count / 14) * 8 - 1.
function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number,
dst: buffer, d: number, ds: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
local o = d * 4
local os = ds * 4
local done = 0
local fp = p
while done < count do
local head = readu8(src, fp)
local pi = math.min(rshift(head, 4), 7)
local scale = 2 ^ band(head, 15) * 2048
local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4)
local n14 = math.min(14, count - done)
for k = 0, n14 - 1 do
local b = readu8(src, fp + 1 + rshift(k, 1))
local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
if n >= 8 then
n -= 16
end
local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048
if s > 32767 then
s = 32767
elseif s < -32768 then
s = -32768
end
h2 = h1
h1 = s
writef32(dst, o, s / 32768)
o += os
end
done += n14
fp += 8
end
writei32(st, so, h1)
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ encoders
-- the nearest s16 to x * 32768 (NaN -> 0)
local function toS16(x: number): number
local v = floor(x * 32768 + 0.5)
if v ~= v then
return 0
elseif v > 32767 then
return 32767
elseif v < -32768 then
return -32768
end
return v
end
Adpcm.toS16 = toS16
-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried)
local function imaNibble(x: number, pred: number, index: number): number
local base = index * 8 + 1
local best, bestErr = 0, math.huge
for m = 0, 7 do
local diff = IMA_DIFF[base + m]
local up = math.min(pred + diff, 32767)
local e = math.abs(x - up)
if e < bestErr then
best, bestErr = m, e
end
local down = math.max(pred - diff, -32768)
e = math.abs(x - down)
if e < bestErr then
best, bestErr = m + 8, e
end
end
return best
end
-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ...
-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p ..
-- p + (q0 + (count - 1) * qs) // 2.
function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
p: number, q0: number, qs: number, hi: boolean)
local pred = readi32(st, so)
local index = math.clamp(readi32(st, so + 4), 0, 88)
local q = q0
for i = 0, count - 1 do
local v = toS16(readf32(x, (xi + i * xs) * 4))
local nib = imaNibble(v, pred, index)
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767)
index = IMA_NEXT[index * 16 + nib + 1]
local bp = p + rshift(q, 1)
local b = readu8(out, bp)
if (band(q, 1) == 0) == hi then
b = bor(band(b, 0x0F), lshift(nib, 4))
else
b = bor(band(b, 0xF0), nib)
end
writeu8(out, bp, b)
q += qs
end
writei32(st, so, pred)
writei32(st, so + 4, index)
end
-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames
-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch
-- bytes carrying the step index from block to block.
function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number)
local groups = (spb - 1) // 8
for c = 0, ch - 1 do
local so = c * 8
local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0
writei32(st, so, first)
local index = math.clamp(readi32(st, so + 4), 0, 88)
writei32(st, so + 4, index)
buffer.writei16(out, off + c * 4, first)
writeu8(out, off + c * 4 + 2, index)
writeu8(out, off + c * 4 + 3, 0)
local pred = first
for g = 0, groups - 1 do
local gp = off + 4 * ch + (g * ch + c) * 4
for k = 0, 7 do
local f = 1 + g * 8 + k
local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred
local nib = imaNibble(v, pred, index)
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767)
index = IMA_NEXT[index * 16 + nib + 1]
local bp = gp + rshift(k, 1)
if band(k, 1) == 0 then
writeu8(out, bp, nib)
else
writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4)))
end
end
end
writei32(st, so + 4, index)
end
end
-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first
-- delta; returns the squared error and the nibbles in nibs (when given)
local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number
local s1, s2 = xs[2], xs[1]
local idelta = delta0
local err = 0
for i = 3, n do
local p = s1 * c1 + s2 * c2
p = if p >= 0 then p // 256 else -((-p) // 256)
local e = xs[i] - p
local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta)
nib = math.clamp(nib, -8, 7)
local v = math.clamp(p + nib * idelta, -32768, 32767)
err += (xs[i] - v) * (xs[i] - v)
if nibs then
nibs[i] = band(nib, 15)
end
idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202)
s2 = s1
s1 = v
end
return err
end
-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf
-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel
-- takes the predictor with the least error.
function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number)
local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
local xs = table.create(spb, 0)
local nibs = table.create(spb, 0)
local all = table.create(spb * ch, 0)
for c = 0, ch - 1 do
for i = 1, spb do
xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0
end
-- the first delta from the first steps
local sum = 0
for i = 3, math.min(spb, 10) do
sum += math.abs(xs[i] - xs[i - 1])
end
local delta0 = math.clamp(sum // 16, 16, 32767)
local best, bestErr = 1, math.huge
for k = 1, 7 do
local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil)
if e < bestErr then
best, bestErr = k, e
end
end
msTrial(xs, spb, C1[best], C2[best], delta0, nibs)
writeu8(out, off + c, best - 1)
writeu16(out, off + ch + c * 2, delta0)
buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0)
buffer.writei16(out, off + 5 * ch + c * 2, xs[1])
for i = 3, spb do
all[(i - 3) * ch + c + 1] = nibs[i]
end
end
local total = (spb - 2) * ch
for k = 0, total - 1, 2 do
writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0))
end
end
-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and
-- the nibbles in nibs when given; returns the error and the new history
local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number)
local err = 0
for k = 1, 32 do
local pred = (c1 * h1 + c2 * h2) // 4096
local e = xs[k] - pred
local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale)
n = math.clamp(n, -8, 7)
local s = math.clamp(n * scale + pred, -32768, 32767)
err += (xs[k] - s) * (xs[k] - s)
if nibs then
nibs[k] = band(n, 15)
end
h2 = h1
h1 = s
end
return err, h1, h2
end
-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames
-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame
-- past count is padded with silence. State as Adpcm.adx.
function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number,
out: buffer, p: number, pstride: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
local v = table.create(32, 0)
local nibs = table.create(32, 0)
for f = 0, (count + 31) // 32 - 1 do
local peak = 0
local a, b = h1, h2
for k = 1, 32 do
local i = f * 32 + k - 1
local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0
v[k] = s
peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096))
b = a
a = s
end
-- the scale that covers the open-loop residual peak, and a few around it, closed loop
local base = math.max(1, (peak + 6) // 7)
local best, bestErr = base, math.huge
for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do
local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF)
local e = adxTrial(v, sc, c1, c2, h1, h2, nil)
if e < bestErr then
best, bestErr = sc, e
end
end
local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs)
h1, h2 = n1, n2
local fp = p + f * pstride
writeu8(out, fp, rshift(best - 1, 8))
writeu8(out, fp + 1, band(best - 1, 255))
for k = 0, 15 do
writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2])
end
end
writei32(st, so, h1)
writei32(st, so + 4, h2)
end
-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM
-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is
-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx.
function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
p: number, pstride: number)
local h1, h2 = readi32(st, so), readi32(st, so + 4)
local v = table.create(28, 0)
local nibs = table.create(28, 0)
for f = 0, (count + 27) // 28 - 1 do
for k = 1, 28 do
local i = f * 28 + k - 1
v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0
end
local bestErr, bestHead = math.huge, 0
for fi = 1, 5 do
for shift = 0, 12 do
local mul = 2 ^ (20 - shift)
local a, b = h1, h2
local err = 0
for k = 1, 28 do
local pred = psxPred(fi, a, b)
local n = floor((v[k] * 256 - pred) / mul + 0.5)
n = if n > 7 then 7 elseif n < -8 then -8 else n
local s = (n * mul + pred) // 256
local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s
err += (v[k] - c) * (v[k] - c)
if err >= bestErr then
break
end
b = a
a = s
end
if err < bestErr then
bestErr, bestHead = err, (fi - 1) * 16 + shift
end
end
end
-- the winner again, for its nibbles and history
local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15)
local mul = 2 ^ (20 - shift)
for k = 1, 28 do
local pred = psxPred(fi, h1, h2)
local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7)
nibs[k] = band(n, 15)
h2 = h1
h1 = (n * mul + pred) // 256
end
local fp = p + f * pstride
writeu8(out, fp, bestHead)
writeu8(out, fp + 1, 0)
for k = 0, 13 do
writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16)
end
end
writei32(st, so, h1)
writei32(st, so + 4, h2)
end
-- ------------------------------------------------------------------------------------------------ ModPlug
-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at
-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping).
-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1.
function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number)
local tab = table.create(16, 0)
for k = 0, 15 do
tab[k + 1] = buffer.readi8(src, p + k)
end
local v = 0
for i = 0, count - 1 do
local b = readu8(src, p + 16 + rshift(i, 1))
local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4)
v = (v + tab[nib + 1] + 128) % 256 - 128
writef32(dst, (d + i) * 4, v / 128)
end
end
return Adpcm
+297
View File
@@ -0,0 +1,297 @@
--!strict
--!native
--!optimize 2
-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale
-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic
-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force
-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division).
-- The 64-bit slices are handled as two 32-bit halves.
--
-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message
-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d
-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p]
-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2)
--
-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes.
local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32
local readi32, writei32 = buffer.readi32, buffer.writei32
local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap
local floor = math.floor
local Qoa = {}
Qoa.SLICE_LEN = 20
Qoa.SLICES_PER_FRAME = 256
Qoa.FRAME_LEN = 256 * 20
Qoa.MAX_CHANNELS = 255
local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code
local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 }
-- DEQ[sf * 8 + q + 1]
local DEQ = {
1, -1, 3, -3, 5, -5, 7, -7,
5, -5, 18, -18, 32, -32, 49, -49,
16, -16, 53, -53, 95, -95, 147, -147,
34, -34, 113, -113, 203, -203, 315, -315,
63, -63, 210, -210, 378, -378, 588, -588,
104, -104, 345, -345, 621, -621, 966, -966,
158, -158, 528, -528, 950, -950, 1477, -1477,
228, -228, 760, -760, 1368, -1368, 2128, -2128,
316, -316, 1053, -1053, 1895, -1895, 2947, -2947,
422, -422, 1405, -1405, 2529, -2529, 3934, -3934,
548, -548, 1828, -1828, 3290, -3290, 5117, -5117,
696, -696, 2320, -2320, 4176, -4176, 6496, -6496,
868, -868, 2893, -2893, 5207, -5207, 8099, -8099,
1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933,
1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005,
1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336,
}
local function be32(b: buffer, p: number): number
return byteswap(readu32(b, p))
end
local function s16(v: number): number
return if v >= 32768 then v - 65536 else v
end
-- frameSize(channels, slices) -> bytes
function Qoa.frameSize(ch: number, slices: number): number
return 8 + 16 * ch + 8 * slices * ch
end
export type FrameInfo = { channels: number, rate: number, samples: number, size: number }
-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message
function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?)
if avail < 8 then
return nil, "truncated frame header"
end
local hi, lo = be32(b, p), be32(b, p + 4)
local ch = rshift(hi, 24)
local rate = band(hi, 0xFFFFFF)
local samples = rshift(lo, 16)
local size = band(lo, 0xFFFF)
if ch == 0 or rate == 0 or samples == 0 then
return nil, "bad frame header"
end
local slices = (samples + 19) // 20
local head = 8 + 16 * ch
if slices > 256 or size < head or slices * ch > (size - head) // 8 then
return nil, "bad frame size"
end
if size > avail then
return nil, "truncated frame"
end
return { channels = ch, rate = rate, samples = samples, size = size }, nil
end
-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state
-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there)
function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string)
local info, msg = Qoa.frameInfo(b, p, avail)
if not info then
return nil, msg :: string
end
local ch, samples = info.channels, info.samples
for c = 0, ch - 1 do
local lp = p + 8 + c * 16
local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12)
local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF))
local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF))
local sp = p + 8 + 16 * ch + c * 8
local o = (d + c) * 4
local os = ch * 4
local s0 = 0
while s0 < samples do
local hi, lo = be32(b, sp), be32(b, sp + 4)
local base = rshift(hi, 28) * 8 + 1
local n = math.min(20, samples - s0)
for k = 0, n - 1 do
local q
if k < 9 then
q = band(rshift(hi, 25 - 3 * k), 7)
elseif k == 9 then
q = band(hi, 1) * 4 + rshift(lo, 30)
else
q = band(rshift(lo, 57 - 3 * k), 7)
end
local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192
local dq = DEQ[base + q]
local r = pred + dq
if r > 32767 then
r = 32767
elseif r < -32768 then
r = -32768
end
writef32(dst, o, r / 32768)
o += os
local delta = dq // 16
w0 += if h0 < 0 then -delta else delta
w1 += if h1 < 0 then -delta else delta
w2 += if h2 < 0 then -delta else delta
w3 += if h3 < 0 then -delta else delta
h0, h1, h2, h3 = h1, h2, h3, r
end
s0 += 20
sp += 8 * ch
end
end
return samples, info.size
end
-- ------------------------------------------------------------------------------------------------ encoder
-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13)
function Qoa.newLms(ch: number): buffer
local st = buffer.create(32 * ch)
for c = 0, ch - 1 do
writei32(st, c * 32 + 24, -8192)
writei32(st, c * 32 + 28, 16384)
end
return st
end
-- the nearest s16 to x * 32768 (NaN -> 0)
local function toS16(x: number): number
local v = floor(x * 32768 + 0.5)
if v ~= v then
return 0
elseif v > 32767 then
return 32767
elseif v < -32768 then
return -32768
end
return v
end
-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which
-- wraps for big residuals at scale factor 0), rounding away from zero
local function qdiv(v: number, sf: number): number
local x = v * RECIP[sf + 1] + 32768
if x >= 2147483648 or x < -2147483648 then
x = (x + 2147483648) % 4294967296 - 2147483648
end
local n = x // 65536
local sv = if v > 0 then 1 elseif v < 0 then -1 else 0
local sn = if n > 0 then 1 elseif n < 0 then -1 else 0
return n + sv - sn
end
-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x
-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames
function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number
local slices = (n + 19) // 20
local size = Qoa.frameSize(ch, slices)
writeu32(out, p, byteswap(bor(lshift(ch, 24), rate)))
writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size)))
for c = 0, ch - 1 do
local so = c * 32
-- the history and weights as big-endian i16 x 4
for i = 0, 3 do
local hv = band(readi32(lms, so + i * 4), 0xFFFF)
local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF)
buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8))
buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255))
buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8))
buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255))
end
end
local xs = table.create(20, 0)
local codes = table.create(20, 0)
local best = table.create(20, 0)
local prevSf = table.create(ch, 0)
local sp = p + 8 + 16 * ch
for s = 0, slices - 1 do
local len = math.min(20, n - s * 20)
for c = 0, ch - 1 do
for k = 1, len do
xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4))
end
local so = c * 32
local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12)
local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28)
local bestRank, bestSf = math.huge, 0
local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3
for sfi = 0, 15 do
local sf = (sfi + prevSf[c + 1]) % 16
local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3
local rank = 0
local base = sf * 8 + 1
for k = 1, len do
local v = xs[k]
local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192
local res = v - pred
local sc = qdiv(res, sf)
if sc > 8 then
sc = 8
elseif sc < -8 then
sc = -8
end
local q = QUANT[sc + 9]
local dq = DEQ[base + q]
local r = pred + dq
if r > 32767 then
r = 32767
elseif r < -32768 then
r = -32768
end
local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3
if sq >= 2147483648 then -- C int arithmetic
sq = (sq + 2147483648) % 4294967296 - 2147483648
end
local pen = sq // 262144 - 0x8ff
if pen < 0 then
pen = 0
end
local e = v - r
rank += e * e + pen * pen
if rank > bestRank then
break
end
local delta = dq // 16
w0 += if h0 < 0 then -delta else delta
w1 += if h1 < 0 then -delta else delta
w2 += if h2 < 0 then -delta else delta
w3 += if h3 < 0 then -delta else delta
h0, h1, h2, h3 = h1, h2, h3, r
codes[k] = q
end
if rank < bestRank then
bestRank, bestSf = rank, sf
b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3
for k = 1, len do
best[k] = codes[k]
end
end
end
prevSf[c + 1] = bestSf
writei32(lms, so, b0)
writei32(lms, so + 4, b1)
writei32(lms, so + 8, b2)
writei32(lms, so + 12, b3)
writei32(lms, so + 16, bw0)
writei32(lms, so + 20, bw1)
writei32(lms, so + 24, bw2)
writei32(lms, so + 28, bw3)
-- the slice: sf in the top 4 bits, then the codes, unused codes 0
local hi, lo = bestSf * 268435456, 0
for k = 0, 19 do
local q = if k < len then best[k + 1] else 0
if k < 9 then
hi += q * 2 ^ (25 - 3 * k)
elseif k == 9 then
hi += rshift(q, 2)
lo += band(q, 3) * 1073741824
else
lo += q * 2 ^ (57 - 3 * k)
end
end
writeu32(out, sp, byteswap(hi))
writeu32(out, sp + 4, byteswap(lo))
sp += 8
end
end
return size
end
return Qoa
+9 -5
View File
@@ -10,7 +10,7 @@
-- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position
-- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before
-- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm()
-- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode
-- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode
-- reset = function() end, -- forget codec state (before a seek)
-- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop)
-- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1)
@@ -26,7 +26,7 @@ export type Spec = {
count: number,
start: (i: number) -> number,
decode: (i: number) -> (number?, Err.Err?),
pcm: () -> { number },
pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0
reset: () -> (),
skip: number?, -- default 0
stop: number?, -- default start(count + 1)
@@ -91,9 +91,13 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
local src = pcmOf()
local q = got * ch * 4
local s = pendPos * ch
for k = 1, take * ch do
writef32(ob, q, src[s + k])
q += 4
if type(src) == "buffer" then
buffer.copy(ob, q, src, s * 4, take * ch * 4)
else
for k = 1, take * ch do
writef32(ob, q, src[s + k])
q += 4
end
end
pendPos += take
got += take