ws-audio2: audio/brstm (BRSTM / BCSTM / BFSTM read: DSP ADPCM, PCM16, PCM8, loops)

Bit-exact with vgmstream; forward seeks start from the ADPC / SEEK history. codecs/audio/Adpcm/Decoder.interleaved
also lays out block-interleaved PCM (s16be / s16le / s8); snapshots take precedence over a format's history table.
This commit is contained in:
4DBug committed 2026-10-31 14:22:46 -05:00
1 parent fd9175883d
commit 5dfaaf7524
6 files changed
+454 -18

No files matched your search

+12
View File
@@ -206,6 +206,18 @@ local list: { Entry } = {
return require("@formats/audio/au")
end,
},
{
name = "brstm",
category = "audio",
path = "audio/brstm",
extensions = { "brstm", "bcstm", "bfstm" },
mime = { "audio/x-brstm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" },
caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } },
load = function()
return require("@formats/audio/brstm")
end,
},
{
name = "caf",
category = "audio",
+292
View File
@@ -0,0 +1,292 @@
--!strict
-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and
-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in formats-luau; the layouts
-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP
-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16
-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop }
-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions
-- (the whole stream plays), the track table (channels are not grouped).
--
-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec)
-- ------------------------------------------------------------------------------------------------ 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 Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Brstm = {
name = "brstm",
category = "audio",
extensions = { "brstm", "bcstm", "bfstm" },
mime = { "audio/x-brstm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" },
caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" }
-- ------------------------------------------------------------------------------------------------ sniff
function Brstm.sniff(r: Bytes.Reader): number
local m = r:peek(4)
if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then
return 0
end
local bom = r:peek(2, 4)
return if bom == "\254\255" or bom == "\255\254" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Brstm.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 = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit)
end
-- ------------------------------------------------------------------------------------------------ open
-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file
-- start); a read out of range records the error in .err and returns 0
local function view(r: Bytes.Reader, be: boolean)
local v = { err = nil :: string? }
local size = r.limit - r.base
local function at(o: number, n: number): Bytes.Reader?
if o < 0 or o + n > size then
v.err = "an offset points past the end"
return nil
end
return r:sub(o, n)
end
function v.u8(o: number): number
local s = at(o, 1)
return if s then s:u8() else 0
end
function v.u16(o: number): number
local s = at(o, 2)
return if s then (if be then s:u16be() else s:u16le()) else 0
end
function v.i16(o: number): number
local s = at(o, 2)
return if s then (if be then s:i16be() else s:i16le()) else 0
end
function v.u32(o: number): number
local s = at(o, 4)
return if s then (if be then s:u32be() else s:u32le()) else 0
end
function v.i32(o: number): number
local s = at(o, 4)
return if s then (if be then s:i32be() else s:i32le()) else 0
end
return v
end
type Layout = {
codec: number,
loop: boolean,
ch: number,
rate: number,
loopStart: number,
frames: number,
blockSize: number,
lastPadded: number,
data: number, -- the first block (absolute in the file)
adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2)
hist: number?, -- the per-block history table: (yn1, yn2) per channel per block
histEntries: number,
}
local function parseRstm(v: any): (Layout?, string?)
if v.u16(0x06) ~= 0x0100 then
return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07))
end
local head = v.u32(0x10)
local adpc = v.u32(0x18)
if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian
return nil, "no HEAD chunk"
end
local base = head + 8
local info = base + v.u32(base + 4)
local chans = base + v.u32(base + 20)
local ch = v.u8(info + 2)
local L: Layout = {
codec = v.u8(info),
loop = v.u8(info + 1) ~= 0,
ch = ch,
rate = v.u16(info + 4),
loopStart = v.u32(info + 8),
frames = v.u32(info + 12),
data = v.u32(info + 16),
blockSize = v.u32(info + 24),
lastPadded = v.u32(info + 40),
adp = {},
hist = nil,
histEntries = 0,
}
for c = 0, ch - 1 do
local ci = base + v.u32(chans + 4 + c * 8 + 4)
L.adp[c + 1] = base + v.u32(ci + 4)
end
if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC"
L.hist = adpc + 8
L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch)
end
return L, nil
end
local function parseFstm(v: any): (Layout?, string?)
local info: number, seek: number, data: number = 0, 0, 0
local seekSize: number = 0
for i = 0, math.min(v.u16(0x10), 16) - 1 do
local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4)
if id == 0x4000 then
info = off
elseif id == 0x4001 then
seek = off
seekSize = v.u32(0x14 + i * 12 + 8) :: number
elseif id == 0x4002 then
data = off
end
end
if info == 0 or data == 0 then
return nil, "no INFO or DATA block"
end
local stream = info + 8 + v.i32(info + 0x0C)
local chans = info + 8 + v.i32(info + 0x1C)
local ch = v.u8(stream + 2)
local dataRef = stream + 0x30
local L: Layout = {
codec = v.u8(stream),
loop = v.u8(stream + 1) ~= 0,
ch = ch,
rate = v.u32(stream + 4),
loopStart = v.u32(stream + 8),
frames = v.u32(stream + 12),
blockSize = v.u32(stream + 20),
lastPadded = v.u32(stream + 36),
data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20,
adp = {},
hist = nil,
histEntries = 0,
}
for c = 0, ch - 1 do
local ci = chans + v.i32(chans + 4 + c * 8 + 4)
L.adp[c + 1] = ci + v.i32(ci + 4)
end
if seek > 0 and seekSize > 8 then
L.hist = seek + 8
L.histEntries = (seekSize - 8) // math.max(1, 4 * ch)
end
return L, nil
end
function Brstm.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 r.limit - r.base < 0x40 then
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
end
if Brstm.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file")
end
local magic = r:peek(4)
local be = r:peek(2, 4) == "\254\255"
local v = view(r, be)
local parsed: Layout?, msg: string?
if magic == "RSTM" then
if not be then
return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM")
end
parsed, msg = parseRstm(v)
else
parsed, msg = parseFstm(v)
end
if v.err then
return nil, Err.new(Err.TRUNCATED, v.err)
elseif not parsed then
return nil, Err.from(msg)
end
local L = parsed :: Layout
local codec = CODECS[L.codec]
if not codec then
return nil, Err.new(Err.CORRUPT, "codec " .. L.codec)
elseif codec == "ima" then
return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams")
end
local ch = L.ch
if ch < 1 or L.rate < 1 then
return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate")
end
local size = r.limit - r.base - L.data
if L.data < 0 or size < 0 then
return nil, Err.new(Err.TRUNCATED, "the data starts past the end")
end
local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le"
local coefs: buffer? = nil
local hist: { number }? = nil
if codec == "dsp" then
coefs = buffer.create(64 * ch)
hist = {}
for c = 0, ch - 1 do
local adp = L.adp[c + 1]
for k = 0, 15 do
buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2))
end
hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38)
end
if v.err then
return nil, Err.new(Err.TRUNCATED, v.err)
end
end
local histAt, entries = L.hist, L.histEntries
local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil
local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop }
local block = L.blockSize
if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then
return nil, Err.new(Err.CORRUPT, "bad block size " .. block)
end
local d, err = Decoder.interleaved(dec, {
kind = kind :: any,
buf = r.buf,
offset = r.base + L.data,
size = size,
interleave = block,
lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block,
frames = L.frames,
coefs = coefs,
hist = hist,
restore = if codec == "dsp" and histAt
then function(row: number, st: buffer): boolean
if row >= entries then
return false
end
for c = 0, ch - 1 do
local p = (histAt :: number) + (row * ch + c) * 4
buffer.writei32(st, c * 8, v.i16(p))
buffer.writei32(st, c * 8 + 4, v.i16(p + 2))
end
return v.err == nil
end
else nil,
})
if d then
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
end
return d, err
end
return Brstm
+31 -11
View File
@@ -2,8 +2,8 @@
-- 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.
-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else
-- decodes forward from the nearest earlier snapshot. New in formats-luau.
--
-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...)
-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter)
@@ -14,8 +14,8 @@
-- })
--
-- 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.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every
-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM)
-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG)
-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes
-- per channel), raw or inside AIFF-C / CAF
@@ -55,10 +55,10 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?)
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
if snaps[i] then
buffer.copy(st, 0, snaps[i])
elseif restore and restore(i) then
-- the format set the state (BRSTM's seek table)
else
local j = i - 1
while j > 1 and not snaps[j] do
@@ -96,11 +96,29 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?)
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
local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame
local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame
-- PCM samples of one channel into every ds-th float of dst from float d
local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number)
if kind == "s8" then
for k = 0, n - 1 do
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128)
end
elseif kind == "s16le" then
for k = 0, n - 1 do
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768)
end
else
for k = 0, n - 1 do
local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1)
buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768)
end
end
end
export type InterleavedSpec = {
kind: "psx" | "adx" | "dsp",
kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way
buf: buffer,
offset: number, -- the first row
size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames)
@@ -177,8 +195,10 @@ function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?)
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
elseif kind == "dsp" then
Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch)
else
pcm(kind, buf, p, n, out, d, ch)
end
end
got += n