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
+59
View File
@@ -0,0 +1,59 @@
-- tests/audio/_adpcm: shared checks of the ADPCM game-audio formats (adx, vag, brstm): a file against the reference
-- decoder's s16le output, bit-exact, through decode() and through open() with seeks (forward into unvisited packets,
-- back, the end), loop points; the SNR of an encoder's round trip.
local Bytes = require("@formats/core/Bytes")
local H = {}
-- same(f32 buffer, s16le reference buffer, first reference sample, count) -> true when every sample is equal
function H.same(out: buffer, ref: buffer, from: number, count: number): boolean
for i = 0, count - 1 do
if buffer.readf32(out, i * 4) * 32768 ~= buffer.readi16(ref, (from + i) * 2) then
return false
end
end
return true
end
function H.snr(x: buffer, y: buffer, count: number): number
local sig, err = 0, 0
for i = 0, count - 1 do
local a = buffer.readf32(x, i * 4)
local e = a - buffer.readf32(y, i * 4)
sig += a * a
err += e * e
end
return if err == 0 then 200 else 10 * math.log10(sig / err)
end
-- check(t, Fmt, c, opts?): c = { name, data, rate, ch, frames?, ref, loopStart?, loopEnd? }
function H.check(t: any, Fmt: any, c: any, opts: any?)
local ref = buffer.fromstring(c.ref)
local frames = buffer.len(ref) // (2 * c.ch)
local a, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts)
t:check(a, c.name .. ": decode: " .. tostring(err))
if not a then
return
end
t:eq(a.frames, frames, c.name .. ": frames")
t:eq(a.channels, c.ch, c.name .. ": channels")
t:eq(a.sampleRate, c.rate, c.name .. ": rate")
t:check(H.same(a.samples, ref, 0, frames * c.ch), c.name .. ": bit-exact with the reference")
t:eq(a.meta.source.format, Fmt.name, c.name .. ": meta.source.format")
if c.loopStart then
local l = a.meta.source.loop
t:check(l and l.start == c.loopStart and l.stop == c.loopEnd, c.name .. ": loop " .. tostring(l and l.start) .. " " .. tostring(l and l.stop))
else
t:eq(a.meta.source.loop, nil, c.name .. ": no loop")
end
-- open: seek forward first (unvisited packets), then back, then the end
local dec = Fmt.open(Bytes.reader(buffer.fromstring(c.data)), opts) :: any
for _, f in { frames * 3 // 4, 5, frames // 2 + 13, frames - 2, 0, 4097 } do
f = math.min(f, frames)
dec:seek(f / c.rate)
local b, n = dec:read(50)
t:check(n == math.min(50, frames - f) and H.same(b, ref, f * c.ch, n * c.ch), c.name .. ": seek to " .. f)
end
end
return H
+90
View File
@@ -0,0 +1,90 @@
-- audio/adx tests: ffmpeg's ADX files (version 3) and a version 4 file with history and loop points, bit-exact with
-- vgmstream (tools/fixtures/adx.py) through decode and open with seeks; our encoder's files as vgmstream decodes them
-- (equal to our decode, loops reported) and their quality; header errors; the api; the fuzz pass.
local T = require("@tests/T")
local Adx = require("@formats/audio/adx")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local F = require("@formats")
local H = require("@tests/audio/_adpcm")
local Cases = require("@tests/gen/adx_cases")
local Ours = require("@tests/gen/adx_ours")
local Sig = require("@tests/gen/adx_sig")
local t = T.suite("adx")
t:eq(Adx.name, "adx", "name")
t:check(Adx.caps.decode and Adx.caps.encode, "caps")
local samples = {}
for _, c in Cases do
table.insert(samples, c.data)
t:eq(Adx.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
H.check(t, Adx, c)
end
t:note("%d files bit-exact with vgmstream", #Cases)
-- ------------------------------------------------------------------------------------------------ encoder
local audio = Types.Audio.new(Sig.rate, Sig.channels, Sig.frames)
buffer.writestring(audio.samples, 0, Sig.data)
for _, c in Ours do
H.check(t, Adx, c)
local a = Adx.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
local s = H.snr(audio.samples, a.samples, Sig.frames * Sig.channels)
t:check(s > 22, string.format("ours %s: %.1f dB", c.name, s))
t:note("encode %s: %.1f dB", c.name, s)
-- deterministic, and the same from a streaming Decoder; the loop is kept through a re-encode
local again = Adx.encode(a)
local back = Adx.decode(Bytes.reader(again :: buffer)) :: any
t:check(back and (c.loopStart == nil or (back.meta.source.loop.start == c.loopStart)), c.name .. ": loop kept on re-encode")
end
do
local out = Adx.encode(audio, { loop = { start = 1000, stop = 8000 } })
t:check(out and buffer.tostring(out) == Ours[2].data, "encode is deterministic")
local _, e1 = Adx.encode(audio, { loop = { start = 10, stop = 5 } })
t:check(e1 and e1.code == Err.ARG, "bad loop")
local _, e2 = Adx.encode(Types.Audio.new(8000, 9, 10))
t:check(e2 and e2.code == Err.ARG, "9 channels")
local _, e3 = Adx.encode(audio, { cutoff = 1e6 })
t:check(e3 and e3.code == Err.ARG, "bad cutoff")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local base = Cases[1].data
local function patch(at: number, bytes: string): buffer
local b = buffer.fromstring(base)
buffer.writestring(b, at, bytes)
return b
end
local function fails(b: buffer, code: string, label: string)
local d, e = Adx.open(Bytes.reader(b))
t:check(d == nil and e and e.code == code, label .. ": " .. tostring(e))
end
fails(patch(0x12, "\4\9"), Err.UNSUPPORTED, "encrypted")
fails(patch(0x04, "\4"), Err.UNSUPPORTED, "exponential type")
fails(patch(0x04, "\17"), Err.UNSUPPORTED, "AHX")
fails(patch(0x07, "\0"), Err.CORRUPT, "0 channels")
fails(patch(0x12, "\6\0"), Err.UNSUPPORTED, "version 6")
fails(buffer.fromstring("not adx at all"), Err.CORRUPT, "not adx")
t:eq(F.detect(base), "adx", "F.detect")
local a = F.audio.load(base)
t:check(a and a.frames == Cases[1].frames, "F.audio.load")
local out = F.save(a, nil, { format = "adx" })
t:check(out and F.detect(out) == "adx", "F.save adx")
end
t:fuzz("open + read + seek", function(b: buffer)
local dec = Adx.open(Bytes.reader(b))
if dec then
dec:read(100000)
dec:seek(dec.duration / 2)
dec:read(33)
end
return dec
end, samples, { mutations = 10 })
t:fuzz("header", function(b: buffer)
return Adx.decode(Bytes.reader(b))
end, samples, { mutations = 10, keepHeader = 0, garbage = 50 })
t:done()
+89
View File
@@ -0,0 +1,89 @@
-- audio/vag tests: VAGp (with and without loop flags), VAGi and KVAG files from our Python encoders, bit-exact with
-- vgmstream / ffmpeg (tools/fixtures/vag.py) through decode and open with seeks; our encoder's files as vgmstream
-- decodes them (loops reported where vgmstream reads them), their quality; errors; the api; the fuzz pass.
local T = require("@tests/T")
local Vag = require("@formats/audio/vag")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local F = require("@formats")
local H = require("@tests/audio/_adpcm")
local Cases = require("@tests/gen/vag_cases")
local Ours = require("@tests/gen/vag_ours")
local Sig = require("@tests/gen/vag_sig")
local Sig1 = require("@tests/gen/vag_sig1")
local t = T.suite("vag")
t:eq(Vag.name, "vag", "name")
local samples = {}
for _, c in Cases do
table.insert(samples, c.data)
t:eq(Vag.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
H.check(t, Vag, c)
if c.title then
t:eq(Vag.decode(Bytes.reader(buffer.fromstring(c.data))).tags.title, c.title, c.name .. ": title")
end
end
t:note("%d files bit-exact with vgmstream / ffmpeg", #Cases)
-- ------------------------------------------------------------------------------------------------ encoder
local function audioOf(S: any): any
local a = Types.Audio.new(S.rate, S.channels, S.frames)
buffer.writestring(a.samples, 0, S.data)
return a
end
for _, c in Ours do
H.check(t, Vag, c)
local src = audioOf(if c.ch == 1 then Sig1 else Sig)
local a = Vag.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
-- the output starts with the blank frame: 28 samples later
local s = H.snr(src.samples, buffer.fromstring(buffer.readstring(a.samples, 28 * c.ch * 4, src.frames * c.ch * 4)), src.frames * c.ch)
t:check(s > 25, string.format("ours %s: %.1f dB", c.name, s))
t:note("encode %s: %.1f dB", c.name, s)
end
do
local mono = audioOf(Sig1)
local out = Vag.encode(mono, { loop = { start = 600, stop = 5000 } })
t:check(out and buffer.tostring(out) == Ours[2].data, "encode is deterministic")
mono.tags = { title = "A Title That Is Long" }
local named = Vag.decode(Bytes.reader(Vag.encode(mono) :: buffer)) :: any
t:eq(named.tags.title, "A Title That Is ", "the name field holds 16 bytes")
local _, e1 = Vag.encode(Types.Audio.new(8000, 3, 10))
t:check(e1 and e1.code == Err.ARG, "3 channels")
local _, e2 = Vag.encode(mono, { loop = { start = 0, stop = 10 } })
t:check(e2 and e2.code == Err.ARG, "a loop inside one frame")
local _, e3 = Vag.encode(audioOf(Sig), { interleave = 100 })
t:check(e3 and e3.code == Err.ARG, "bad interleave")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local base = Cases[1].data
local hevag = buffer.fromstring(base)
buffer.writeu32(hevag, 4, bit32.byteswap(0x00030000))
local _, e1 = Vag.open(Bytes.reader(hevag))
t:check(e1 and e1.code == Err.UNSUPPORTED, "HEVAG: " .. tostring(e1))
local _, e2 = Vag.open(Bytes.reader(buffer.fromstring("VAGp\0\0")))
t:check(e2 and e2.code == Err.TRUNCATED, "short header: " .. tostring(e2))
local _, e3 = Vag.open(Bytes.reader(buffer.fromstring("RIFF0000WAVE")))
t:check(e3 and e3.code == Err.CORRUPT, "not vag")
t:eq(F.detect(base), "vag", "F.detect")
local a = F.audio.load(Cases[4].data)
t:check(a and a.channels == 1 and a.meta.source.codec == "ima", "F.audio.load KVAG")
end
t:fuzz("open + read + seek", function(b: buffer)
local dec = Vag.open(Bytes.reader(b))
if dec then
dec:read(100000)
dec:seek(dec.duration / 2)
dec:read(33)
end
return dec
end, samples, { mutations = 10 })
t:fuzz("header", function(b: buffer)
return Vag.decode(Bytes.reader(b))
end, samples, { mutations = 10, keepHeader = 0, garbage = 50 })
t:done()
+13 -1
View File
@@ -316,7 +316,7 @@ def wav_pcm(data):
def vgdecode(ctx, data, ext):
"""vgmstream's decode of a file: (rate, channels, s16le bytes); loop facts come from vgminfo"""
A = _audio()
out = A.tool(ctx, "vgmstream", ["vgmstream-cli", "-o", "{out}", "{in}"], data, ext, outext="wav")
out = A.tool(ctx, "vgmstream", ["vgmstream-cli", "-i", "-o", "{out}", "{in}"], data, ext, outext="wav")
return wav_pcm(out)
@@ -350,3 +350,15 @@ def _audio():
_A = importlib.util.module_from_spec(spec)
spec.loader.exec_module(_A)
return _A
def vagi(samples, rate, ch=2, interleave=0x400):
"""a VAGi file (stereo PS-ADPCM, channels interleaved every `interleave` bytes, data at 0x800)"""
ints = s16(samples)
chans = [psx_encode(ints[c::ch]) for c in range(ch)]
size = max(len(x) for x in chans)
size = (size + interleave - 1) // interleave * interleave
chans = [x.ljust(size, b"\0") for x in chans]
data = b"".join(chans[c][k:k + interleave] for k in range(0, size, interleave) for c in range(ch))
head = b"VAGi" + struct.pack(">I", 0x20) + struct.pack("<I", interleave) + struct.pack(">II", size, rate)
return head.ljust(0x800, b"\0") + data
+69
View File
@@ -0,0 +1,69 @@
# CRI ADX fixtures (tools/fixtures.py): audio/adx. vgmstream is the reference decoder (CRI's scale + 1 and version 3
# rounding; ffmpeg's ADX decoder differs a little on both).
# tests/gen/adx_cases.luau { name, data, rate, ch, frames, ref (vgmstream s16le), loopStart?, loopEnd? }
# ffmpeg -f adx files (version 3, mono / stereo), and a version 4 file rebuilt around ffmpeg's frames with an
# initial history and loop points (vgmstream -m reports the loop)
# tests/gen/adx_ours.luau our encoder's files (run in this step) with vgmstream's decode and loop report
# tests/gen/adx_sig.luau the encoder input
import importlib.util, os, re, struct
_dir = os.path.dirname(os.path.abspath(__file__))
def _load(name):
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
A = _load("_audio")
D = _load("_adpcm")
INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/adx"]
def loops(info):
m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", info, re.S)
return (int(m.group(1)), int(m.group(2))) if m else None
def case(ctx, name, data):
rate, ch, ref = D.vgdecode(ctx, data, "adx")
e = dict(name=name, data=data, rate=rate, ch=ch, frames=len(ref) // (2 * ch), ref=ref)
lp = loops(D.vginfo(ctx, data, "adx"))
if lp:
e["loopStart"], e["loopEnd"] = lp
return e
def generate(ctx):
cases = []
for name, rate, ch, kind in (("ffmpeg-mono-22k", 22050, 1, "sweep"), ("ffmpeg-stereo-44k", 44100, 2, "music"),
("ffmpeg-stereo-32k", 32000, 2, "sine")):
sig = A.signal(kind, rate, ch, 7000, seed=ch)
f = D.ffencode(ctx, A.wav(sig, rate, ch), ["-c:a", "adpcm_adx", "-f", "adx"], "adx")
cases.append(case(ctx, name, f))
# version 4 with history and loops, around the stereo frames
f = cases[1]["data"]
start = struct.unpack_from(">H", f, 2)[0] + 4
frames_ = f[start:]
rate, n = struct.unpack_from(">II", f, 8)
head = bytearray(f[:0x14])
struct.pack_into(">H", head, 0x12, 0x0400)
head += b"\0" * 4 + struct.pack(">hhhh", 300, -200, -150, 90) # 0x14 flags, 0x18 history (2 channels)
head += struct.pack(">HHIIIII", 0, 1, 1, 1024, 0, 6000, 0)
newstart = len(head) + 6
struct.pack_into(">H", head, 2, newstart - 4)
cases.append(case(ctx, "v4-hist-loop", bytes(head) + b"(c)CRI" + frames_))
ctx.emit("adx_cases", cases)
sig = A.signal("music", 32000, 2, 9000, seed=11)
A.emit_signal(ctx, "adx_sig", sig, 32000, 2)
ours = []
for name, opts in (("plain", "nil"), ("loop", "{ loop = { start = 1000, stop = 8000 } }")):
data = A.encode_luau(ctx, "audio/adx", "adx_sig", opts)
e = case(ctx, name, data)
e["opts"] = opts
ours.append(e)
ctx.emit("adx_ours", ours)
+55
View File
@@ -0,0 +1,55 @@
# Sony VAG / KVAG fixtures (tools/fixtures.py): audio/vag. Our Python PS-ADPCM / IMA encoders (tools/fixtures/_adpcm.py)
# write the files; vgmstream decodes VAGp / VAGi (and reports the loops), ffmpeg decodes KVAG (adpcm_ima_ssi).
# tests/gen/vag_cases.luau { name, data, rate, ch, ref (s16le), loopStart?, loopEnd?, title? }
# tests/gen/vag_ours.luau our encoder's files (run in this step) as vgmstream decodes them
# tests/gen/vag_sig.luau / vag_sig1.luau the encoder inputs (stereo / mono)
import importlib.util, os, re
_dir = os.path.dirname(os.path.abspath(__file__))
def _load(name):
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
A = _load("_audio")
D = _load("_adpcm")
INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/vag"]
def vgcase(ctx, name, data, **extra):
rate, ch, ref = D.vgdecode(ctx, data, "vag")
e = dict(name=name, data=data, rate=rate, ch=ch, ref=ref, **extra)
m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", D.vginfo(ctx, data, "vag"), re.S)
if m:
e["loopStart"], e["loopEnd"] = int(m.group(1)), int(m.group(2))
return e
def generate(ctx):
mono = A.signal("music", 22050, 1, 6000, seed=21)
stereo = A.signal("sine", 32000, 2, 5000, seed=22)
cases = [
vgcase(ctx, "vagp-mono", D.vag(mono, 22050, b"Mono Song"), title="Mono Song"),
vgcase(ctx, "vagp-loop", D.vag(mono, 22050, loop=(20, 150))),
vgcase(ctx, "vagi-stereo", D.vagi(stereo, 32000)),
]
for name, sig, ch, rate in (("kvag-mono", mono, 1, 22050), ("kvag-stereo", stereo, 2, 32000)):
f = D.kvag(sig, rate, ch)
cases.append(dict(name=name, data=f, rate=rate, ch=ch, ref=D.ffs16(ctx, f, "vag", fmt="kvag")))
ctx.emit("vag_cases", cases)
A.emit_signal(ctx, "vag_sig", stereo, 32000, 2)
A.emit_signal(ctx, "vag_sig1", mono, 22050, 1)
ours = []
for name, sigmod, opts in (("mono", "vag_sig1", "nil"), ("mono-loop", "vag_sig1", "{ loop = { start = 600, stop = 5000 } }"),
("stereo", "vag_sig", "nil")):
data = A.encode_luau(ctx, "audio/vag", sigmod, opts)
e = vgcase(ctx, name, data)
e["opts"] = opts
ours.append(e)
ctx.emit("vag_ours", ours)