ws-audio2: audio/adx (CRI ADX read / write, loops) and audio/vag (VAGp / VAGi / KVAG read, VAGp / VAGi write)

Bit-exact with vgmstream (ADX, PS-ADPCM) and ffmpeg (KVAG IMA); ADX and PS-ADPCM encoders in codecs/audio/Adpcm.
This commit is contained in:
4DBug committed 2026-10-31 14:17:57 -05:00
1 parent 363b14932f
commit fd9175883d
10 files changed
+987 -1

No files matched your search

+24
View File
@@ -170,6 +170,18 @@ local list: { Entry } = {
return require("@formats/audio/adpcm")
end,
},
{
name = "adx",
category = "audio",
path = "audio/adx",
extensions = { "adx" },
mime = { "audio/x-adx" },
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, loops = true, channels = 8 },
load = function()
return require("@formats/audio/adx")
end,
},
{
name = "aiff",
category = "audio",
@@ -254,6 +266,18 @@ local list: { Entry } = {
return require("@formats/audio/opus")
end,
},
{
name = "vag",
category = "audio",
path = "audio/vag",
extensions = { "vag" },
mime = { "audio/x-vag" },
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, loops = true, channels = 2 },
load = function()
return require("@formats/audio/vag")
end,
},
{
name = "voc",
category = "audio",
+237
View File
@@ -0,0 +1,237 @@
--!strict
-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in
-- formats-luau; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt),
-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder
-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff),
-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and
-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels,
-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and
-- exponential (4) encoding types, AHX.
--
-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff)
-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } })
-- ------------------------------------------------------------------------------------------------ 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 Adx = {
name = "adx",
category = "audio",
extensions = { "adx" },
mime = { "audio/x-adx" },
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, loops = true, channels = 8 },
}
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
export type EncodeOptions = {
loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none
cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders)
}
-- ------------------------------------------------------------------------------------------------ constants
local FRAME = 18
-- ------------------------------------------------------------------------------------------------ sniff
function Adx.sniff(r: Bytes.Reader): number
if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then
return 0
end
local off = r:peekU8(2) * 256 + r:peekU8(3)
return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Adx.open(r)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch, rate = src.channels, src.sampleRate
if ch > 8 then
return nil, Err.new(Err.ARG, "ADX holds at most 8 channels")
end
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
end
local loop = o.loop
if loop == nil then
local v = value :: any
local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop
loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil)
end
local a, cerr = Pcm.collect(src)
if not a then
return nil, cerr
end
local n = a.frames
if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
end
local cutoff = o.cutoff or 500
if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then
return nil, Err.new(Err.ARG, "bad cutoff")
end
cutoff = math.floor(cutoff)
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
local hist = if ch > 1 then 4 * ch else 8
local start = 0x18 + hist + (if loop then 0x18 else 0) + 6
start = (start + 3) // 4 * 4
local nframes = (n + 31) // 32
local w = Bytes.writer(start + (nframes + 1) * FRAME * ch)
w:u16be(0x8000)
w:u16be(start - 4)
w:u8(3)
w:u8(FRAME)
w:u8(4)
w:u8(ch)
w:u32be(rate)
w:u32be(n)
w:u16be(cutoff)
w:u16be(0x0400)
w:u32be(0)
w:fill(0, hist)
if loop then
local bytesAt = function(f: number): number
return start + (f // 32) * FRAME * ch
end
w:u16be(0)
w:u16be(1)
w:u32be(1)
w:u32be(loop.start)
w:u32be(bytesAt(loop.start))
w:u32be(loop.stop)
w:u32be(bytesAt(loop.stop + 31))
end
w:fill(0, start - 6 - w.pos)
w:string("(c)CRI")
local at = w:reserve(nframes * FRAME * ch)
local st = buffer.create(8 * ch)
for c = 0, ch - 1 do
Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch)
end
w.pos = at + nframes * FRAME * ch
-- the end marker: scale 0x8001, then the padding size
w:u16be(0x8001)
w:u16be(FRAME - 4)
w:fill(0, FRAME - 4)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Adx.open(r: Bytes.Reader, _opts: any?): (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
if Adx.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not an ADX file")
end
local h = r:sub(0)
local copyright = (h:seek(2) and h:u16be()) or 0
local start = copyright + 4
local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8()
local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be()
if h.err then
return nil, h.err
end
if version == 0x0408 or version == 0x0409 then
return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)")
end
if enc ~= 3 then
return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else ""))
end
if fsize ~= FRAME or bits ~= 4 then
return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits))
end
if ch < 1 or ch > 8 then
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch)
end
if rate < 1 or rate >= 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
end
if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then
return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version))
end
local size = r.limit - r.base - start
if size < 0 then
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
end
-- loop points and the initial history (vgmstream's reading of the extra header fields)
local hist: { number }? = nil
local loopsAt: number? = nil
if version == 0x0300 then
if start - 6 >= 0x14 + 0x18 then
loopsAt = 0x14
end
elseif version == 0x0400 then
local hsize = if ch > 1 then 4 * ch else 8
hist = {}
for c = 0, ch - 1 do
local hh = r:sub(0x18 + c * 4, 4)
local h1, h2 = hh:i16be(), hh:i16be()
hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2
end
local ainf = 0
local ai = r:sub(0x18 + hsize + 4, 8)
if ai:string(4) == "AINF" then
ainf = ai:u32be()
end
if start - ainf - 6 >= 0x18 + hsize + 0x18 then
loopsAt = 0x18 + hsize
end
end
local loopTable: { start: number, stop: number }? = nil
if loopsAt then
local l = r:sub(loopsAt + 4, 0x14)
local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be()
if not l.err and flag ~= 0 and le > ls then
loopTable = { start = ls, stop = le }
end
end
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable }
local d, err = Decoder.interleaved(dec, {
kind = "adx",
buf = r.buf,
offset = r.base + start,
size = size,
interleave = FRAME,
frames = frames,
c1 = c1,
c2 = c2,
v3 = version == 0x0300,
hist = hist,
})
if not d then
return nil, err
end
d.bitrate = rate * FRAME * ch * 8 // 32
return d, nil
end
return Adx
+231
View File
@@ -0,0 +1,231 @@
--!strict
-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same
-- extension), over codecs/audio/Adpcm. New in formats-luau; the header variants and the PS-ADPCM decoding follow
-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono
-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and
-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono /
-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it.
-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame
-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game
-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...).
--
-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant)
-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } })
-- ------------------------------------------------------------------------------------------------ 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 Vag = {
name = "vag",
category = "audio",
extensions = { "vag" },
mime = { "audio/x-vag" },
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, loops = true, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
export type EncodeOptions = {
loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the
-- source's meta.source.loop, else none
name: string?, -- the 16-byte name field (default: tags.title)
interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16)
}
-- ------------------------------------------------------------------------------------------------ constants
local HEVAG = { [0x00020001] = true, [0x00030000] = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Vag.sniff(r: Bytes.Reader): number
local m = r:peek(4)
return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Vag.open(r)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch, rate = src.channels, src.sampleRate
if ch > 2 then
return nil, Err.new(Err.ARG, "VAG holds mono or stereo")
end
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
end
local il = o.interleave or 2048
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
local loop = o.loop
local v = value :: any
if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then
loop = v.meta.source.loop
end
local a, cerr = Pcm.collect(src)
if not a then
return nil, cerr
end
local n = a.frames
local nf = (n + 27) // 28 -- data frames (after the blank one)
local ls, le = -1, -1
if loop then
if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
end
ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1
if le <= ls then
return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames")
end
end
local chBytes = (nf + 1) * 16
local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il
local start = if ch == 1 then 0x30 else 0x800
local out = buffer.create(start + stride * ch)
local title = o.name or (a.tags and a.tags.title) or ""
buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi")
buffer.writeu32(out, 4, bit32.byteswap(0x20))
if ch == 2 then
buffer.writeu32(out, 8, il)
end
buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride))
buffer.writeu32(out, 0x10, bit32.byteswap(rate))
buffer.writestring(out, 0x20, string.sub(title, 1, 16))
local st = buffer.create(8 * ch)
local plane = buffer.create(chBytes)
for c = 0, ch - 1 do
buffer.fill(plane, 0, 0)
Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16)
for k = 0, nf - 1 do
local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0
if not loop and k == nf - 1 then
flag = 1
end
buffer.writeu8(plane, 16 + k * 16 + 1, flag)
end
if ch == 1 then
buffer.copy(out, start, plane, 0, chBytes)
else
for b = 0, stride // il - 1 do
local take = math.clamp(chBytes - b * il, 0, il)
if take > 0 then
buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take)
end
end
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end
-- flag 3), or nil
local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop?
local ls, le = -1, -1
for k = 0, frames - 1 do
local off = p + (k * 16) // il * il * ch + (k * 16) % il
local flag = bit32.band(buffer.readu8(buf, off + 1), 15)
if flag == 6 and ls < 0 then
ls = k * 28
elseif flag == 3 and le < 0 then
le = k * 28 + 28
if ls >= 0 then
break
end
end
end
return if ls >= 0 and le > ls then { start = ls, stop = le } else nil
end
function Vag.open(r: Bytes.Reader, _opts: any?): (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 h = r:sub(0)
local magic = h:string(4)
local total = r.limit - r.base
if magic == "KVAG" then
local size, rate, stereo = h:u32le(), h:u32le(), h:u16le()
if h.err then
return nil, h.err
end
if rate < 1 or stereo > 1 then
return nil, Err.new(Err.CORRUPT, "bad KVAG header")
end
local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" }
local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true })
if d then
d.bitrate = rate * 4 * (stereo + 1)
end
return d, err
end
if magic ~= "VAGp" and magic ~= "VAGi" then
return nil, Err.new(Err.CORRUPT, "not a VAG file")
end
local version, il = h:u32be(), h:u32le()
local chSize, rate = h:u32be(), h:u32be()
local name = r:sub(0x20, 16):cstring(16)
if h.err then
return nil, h.err
end
if HEVAG[version] then
return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)")
end
if rate < 1 or rate >= 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
end
local ch, start = 1, 0x30
if magic == "VAGi" then
ch, start = 2, 0x800
if il < 16 or il % 16 ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad interleave " .. il)
end
else
il = 16
end
if total < start then
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
end
local size = math.min(chSize * ch, total - start)
local p = r.base + start
local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16)
local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops
local tags = {}
if name ~= "" then
tags.title = name
end
local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop }
local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 })
if d then
d.bitrate = rate * 16 * 8 * ch // 28
end
return d, err
end
return Vag
+120
View File
@@ -565,4 +565,124 @@ function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: numbe
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
return Adpcm