--!strict --!optimize 2 -- codecs/audio/Adpcm/Decoder: the streaming Types.Decoder over packetised ADPCM (ADX, VAG, BRSTM, raw IMA) with exact seeking. -- New in rosetta. local Err = require("@rosetta/core/Err") local Stream = require("@rosetta/codecs/audio/Stream") local Adpcm = require("@rosetta/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 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 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 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", buf: buffer, offset: number, size: number, interleave: number, lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave frames: number?, c1: number?, c2: number?, v3: boolean?, coefs: buffer?, -- dsp: 16 i32 per channel hist: { number }?, restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) } 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 local rows = math.max(1, math.ceil(size / rowBytes)) local function rowFrames(r: number): number 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, hi: boolean?, -- the high nibble first (DVI / KVAG); default low first frames: number?, } -- IMA 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?, frames: number?, coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) } 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 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 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