ws-audio2: codecs/audio/Adpcm (IMA / ima4 / IMA WAV / MS / ADX / PS-ADPCM / DSP decode, IMA + MS encode, Decoder layouts) and audio/adpcm (raw streams)
- codecs/audio/Adpcm: decoder kernels bit-exact with ffmpeg (IMA, ima4, MS) and vgmstream (ADX, PS-ADPCM, DSP); IMA nibble / IMA WAV / MS block encoders. Adpcm/Decoder: streaming Decoders over the shared layouts (channel interleaved frames, nibble streams, self-contained blocks) with exact seeking through state snapshots. - audio/wav: its IMA / MS block decoders moved to codecs/audio/Adpcm (wav tests unchanged and green). - codecs/audio/Stream (shared, small and backward compatible): pcm() may return a buffer of f32 (copied with buffer.copy) instead of a table. - audio/adpcm: headerless ima / ima_wav / ms / ima_qt / psx streams by options; encode ima / ima_wav / ms. - licenses: vgmstream (ISC).
This commit is contained in:
1 parent
de4f14a343
commit
363b14932f
14 files changed
+1931
-166
No files matched your search
@@ -158,6 +158,18 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/aac")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "adpcm",
|
||||
category = "audio",
|
||||
path = "audio/adpcm",
|
||||
extensions = { "adpcm", "ima" },
|
||||
mime = { "audio/x-adpcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
|
||||
load = function()
|
||||
return require("@formats/audio/adpcm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "aiff",
|
||||
category = "audio",
|
||||
@@ -272,7 +284,7 @@ local list: { Entry } = {
|
||||
path = "audio/wav",
|
||||
extensions = { "wav", "wave", "rf64", "bw64" },
|
||||
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
|
||||
load = function()
|
||||
return require("@formats/audio/wav")
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
--!strict
|
||||
-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in
|
||||
-- formats-luau. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by
|
||||
-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such
|
||||
-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs
|
||||
-- here are the layouts those containers use:
|
||||
-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first
|
||||
-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order
|
||||
-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024)
|
||||
-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024)
|
||||
-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime
|
||||
-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16)
|
||||
-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients
|
||||
-- live in a header: see audio/brstm and audio/adx).
|
||||
--
|
||||
-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 })
|
||||
-- local raw = Adpcm.encode(a, { codec = "ima" })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Raw = {
|
||||
name = "adpcm",
|
||||
category = "audio",
|
||||
extensions = { "adpcm", "ima" },
|
||||
mime = { "audio/x-adpcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx"
|
||||
export type Options = {
|
||||
codec: Codec?, -- default "ima"
|
||||
sampleRate: number?, -- default 22050 (decode)
|
||||
channels: number?, -- default 1 (decode)
|
||||
blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding)
|
||||
lowFirst: boolean?, -- ima: the low nibble first
|
||||
interleave: number?, -- psx: bytes per channel before the next channel (default 16)
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Raw.sniff(_r: Bytes.Reader): number
|
||||
return 0 -- no header: found by extension or opts.format only
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Raw.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames))
|
||||
end
|
||||
return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?)
|
||||
local o: Options = opts or {}
|
||||
local codec = o.codec or "ima"
|
||||
if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then
|
||||
return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms")
|
||||
end
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local a, cerr = Pcm.collect(src)
|
||||
if not a then
|
||||
return nil, cerr
|
||||
end
|
||||
local ch, n, x = a.channels, a.frames, a.samples
|
||||
if codec == "ima" then
|
||||
local out = buffer.create((n * ch + 1) // 2)
|
||||
local st = buffer.create(8 * ch)
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local ba = o.blockAlign or 256 * ch
|
||||
local spb = Decoder.blockFrames(codec, ba, ch)
|
||||
if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then
|
||||
return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba))
|
||||
end
|
||||
if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then
|
||||
return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels")
|
||||
end
|
||||
local blocks = (n + spb - 1) // spb
|
||||
local out = buffer.create(blocks * ba)
|
||||
local st = buffer.create(8 * ch)
|
||||
for b = 0, blocks - 1 do
|
||||
local f0 = b * spb
|
||||
if codec == "ms" then
|
||||
Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba)
|
||||
else
|
||||
Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
local o: Options = opts or {}
|
||||
local codec = o.codec or "ima"
|
||||
local rate, ch = o.sampleRate or 22050, o.channels or 1
|
||||
if not CODECS[codec] then
|
||||
return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec))
|
||||
end
|
||||
if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then
|
||||
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 }
|
||||
local d, err
|
||||
if codec == "ima" then
|
||||
d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst })
|
||||
elseif codec == "psx" then
|
||||
local il = o.interleave or 16
|
||||
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
|
||||
end
|
||||
d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il })
|
||||
else
|
||||
local ba = o.blockAlign or 1024
|
||||
if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then
|
||||
return nil, Err.new(Err.ARG, "bad blockAlign")
|
||||
end
|
||||
d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba })
|
||||
end
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
|
||||
return d, nil
|
||||
end
|
||||
|
||||
return Raw
|
||||
@@ -1,7 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers).
|
||||
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The
|
||||
-- ADPCM block decoders moved to codecs/audio/Adpcm.
|
||||
-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau)
|
||||
-- only calls them with ranges it has checked against the source length and the output size.
|
||||
local readu8, readi8, readu16, readi16, readu32, readi32 =
|
||||
@@ -102,160 +103,6 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num
|
||||
end
|
||||
end
|
||||
|
||||
local IMA_STEP = buffer.create(89 * 4)
|
||||
do
|
||||
local steps = {
|
||||
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,
|
||||
}
|
||||
for i, s in steps do
|
||||
buffer.writei32(IMA_STEP, (i - 1) * 4, s)
|
||||
end
|
||||
end
|
||||
local IMA_INDEX = buffer.create(16 * 4)
|
||||
do
|
||||
local t = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
|
||||
for i, v in t do
|
||||
buffer.writei32(IMA_INDEX, (i - 1) * 4, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- IMA ADPCM (Microsoft / WAV layout), one block at src[off] of blockAlign bytes with `avail` bytes present (a
|
||||
-- truncated last block decodes the whole 8-sample groups it has). Writes interleaved f32 to dst from frame 0 and
|
||||
-- returns the frame count.
|
||||
function Codecs.imaBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer): number
|
||||
if avail < 4 * ch then
|
||||
return 0
|
||||
end
|
||||
-- groups of 8 samples per channel (4 bytes each) after the per-channel headers
|
||||
local groups = (avail - 4 * ch) // (4 * ch)
|
||||
local frames = math.min(spb, 1 + groups * 8)
|
||||
for c = 0, ch - 1 do
|
||||
local pred = readi16(src, off + c * 4)
|
||||
local index = readu8(src, off + c * 4 + 2)
|
||||
if index > 88 then
|
||||
index = 88
|
||||
end
|
||||
writef32(dst, c * 4, pred / 32768)
|
||||
local f = 1
|
||||
local g = 0
|
||||
while f < frames do
|
||||
local p = off + 4 * ch + (g * ch + c) * 4
|
||||
for k = 0, 7 do
|
||||
if f >= frames then
|
||||
break
|
||||
end
|
||||
local b = readu8(src, p + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
local step = buffer.readi32(IMA_STEP, index * 4)
|
||||
local diff = rshift(step, 3)
|
||||
if band(nib, 1) ~= 0 then
|
||||
diff += rshift(step, 2)
|
||||
end
|
||||
if band(nib, 2) ~= 0 then
|
||||
diff += rshift(step, 1)
|
||||
end
|
||||
if band(nib, 4) ~= 0 then
|
||||
diff += step
|
||||
end
|
||||
if band(nib, 8) ~= 0 then
|
||||
pred -= diff
|
||||
else
|
||||
pred += diff
|
||||
end
|
||||
if pred > 32767 then
|
||||
pred = 32767
|
||||
elseif pred < -32768 then
|
||||
pred = -32768
|
||||
end
|
||||
index += buffer.readi32(IMA_INDEX, nib * 4)
|
||||
if index < 0 then
|
||||
index = 0
|
||||
elseif index > 88 then
|
||||
index = 88
|
||||
end
|
||||
writef32(dst, (f * ch + c) * 4, pred / 32768)
|
||||
f += 1
|
||||
end
|
||||
g += 1
|
||||
end
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
local MS_ADAPT = buffer.create(16 * 4)
|
||||
do
|
||||
local t = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
|
||||
for i, v in t do
|
||||
buffer.writei32(MS_ADAPT, (i - 1) * 4, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- MS ADPCM, one block. coefs: i32 pairs (coef1, coef2) x ncoef (256 = 1.0). state: 5 * ch i32 scratch.
|
||||
-- Returns the frame count (a truncated last block decodes the whole bytes it has).
|
||||
function Codecs.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer,
|
||||
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)
|
||||
-- state per channel: c1, c2, idelta, s1, s2 (5 i32)
|
||||
for c = 0, ch - 1 do
|
||||
local pi = readu8(src, off + c)
|
||||
if pi >= ncoef then
|
||||
pi = ncoef - 1
|
||||
end
|
||||
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
|
||||
buffer.writei32(state, so, buffer.readi32(coefs, pi * 8))
|
||||
buffer.writei32(state, so + 4, buffer.readi32(coefs, pi * 8 + 4))
|
||||
buffer.writei32(state, so + 8, idelta)
|
||||
buffer.writei32(state, so + 12, s1)
|
||||
buffer.writei32(state, so + 16, s2)
|
||||
writef32(dst, c * 4, s2 / 32768)
|
||||
if frames > 1 then
|
||||
writef32(dst, (ch + c) * 4, s1 / 32768)
|
||||
end
|
||||
end
|
||||
-- nibbles, high first, channels interleaved per nibble
|
||||
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 c = k % ch
|
||||
local so = c * 20
|
||||
local c1, c2 = buffer.readi32(state, so), buffer.readi32(state, so + 4)
|
||||
local idelta = buffer.readi32(state, so + 8)
|
||||
local s1, s2 = buffer.readi32(state, so + 12), buffer.readi32(state, so + 16)
|
||||
local p = s1 * c1 + s2 * c2
|
||||
p = if p >= 0 then p // 256 else -((-p) // 256)
|
||||
local sn = if nib >= 8 then nib - 16 else nib
|
||||
p += sn * idelta
|
||||
if p > 32767 then
|
||||
p = 32767
|
||||
elseif p < -32768 then
|
||||
p = -32768
|
||||
end
|
||||
idelta = (buffer.readi32(MS_ADAPT, nib * 4) * idelta) // 256
|
||||
if idelta < 16 then
|
||||
idelta = 16
|
||||
elseif idelta > 2796202 then -- INT_MAX / 768, as ffmpeg
|
||||
idelta = 2796202
|
||||
end
|
||||
buffer.writei32(state, so + 8, idelta)
|
||||
buffer.writei32(state, so + 12, p)
|
||||
buffer.writei32(state, so + 16, s1)
|
||||
writef32(dst, (2 * ch + k) * 4, p / 32768)
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
-- copy frames from a block cache into the output: count f32 values
|
||||
function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number)
|
||||
buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4)
|
||||
|
||||
@@ -21,6 +21,7 @@ local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Riff = require("@formats/containers/Riff")
|
||||
local Codecs = require("@formats/audio/wav/Codecs")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Wav = {
|
||||
@@ -28,7 +29,7 @@ local Wav = {
|
||||
category = "audio",
|
||||
extensions = { "wav", "wave", "rf64", "bw64" },
|
||||
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
|
||||
}
|
||||
|
||||
@@ -488,8 +489,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
|
||||
spb = computed
|
||||
end
|
||||
-- coefficients from the fmt extension, else the 7 standard pairs
|
||||
local c1 = { 256, 512, 0, 192, 240, 460, 392 }
|
||||
local c2 = { 0, -256, 0, 64, 0, -208, -232 }
|
||||
local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
|
||||
local ncoef = 7
|
||||
if fmt.avail >= 22 then
|
||||
local k = u16(fmt.body + 20)
|
||||
@@ -592,9 +592,9 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
|
||||
local avail = math.min(ba, self.dataOffset + self.dataSize - off)
|
||||
local got
|
||||
if kind == "ima_adpcm" then
|
||||
got = Codecs.imaBlock(self._buf, off, avail, ch, spb, cache)
|
||||
got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0)
|
||||
else
|
||||
got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef,
|
||||
got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef,
|
||||
self._state :: buffer)
|
||||
end
|
||||
self._cacheBlock = block
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
--!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, or the format's own state for that packet (BRSTM's ADPC history), or 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, 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 restore and restore(i) then
|
||||
-- the format set the state
|
||||
elseif snaps[i] then
|
||||
buffer.copy(st, 0, snaps[i])
|
||||
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 } -- bytes per frame
|
||||
local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14 } -- samples per frame
|
||||
|
||||
export type InterleavedSpec = {
|
||||
kind: "psx" | "adx" | "dsp",
|
||||
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)
|
||||
else
|
||||
Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, 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
|
||||
@@ -0,0 +1,568 @@
|
||||
--!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
|
||||
-- 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
|
||||
|
||||
return Adpcm
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user