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:
1 parent
fd9175883d
commit
5dfaaf7524
6 files changed
+454
-18
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
-- audio/brstm tests: BRSTM / BCSTM / BFSTM files (DSP ADPCM, PCM16, PCM8; big- and little-endian; loops) from our
|
||||
-- Python writer, bit-exact with vgmstream (tools/fixtures/brstm.py) through decode and open with seeks (forward seeks
|
||||
-- start from the ADPC / SEEK history table); errors; the api; the fuzz pass.
|
||||
local T = require("@tests/T")
|
||||
local Brstm = require("@formats/audio/brstm")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local F = require("@formats")
|
||||
local H = require("@tests/audio/_adpcm")
|
||||
local Cases = require("@tests/gen/brstm_cases")
|
||||
|
||||
local t = T.suite("brstm")
|
||||
t:eq(Brstm.name, "brstm", "name")
|
||||
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
t:eq(Brstm.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
|
||||
H.check(t, Brstm, c)
|
||||
t:eq(F.detect(c.data), "brstm", c.name .. ": F.detect")
|
||||
end
|
||||
t:note("%d files bit-exact with vgmstream", #Cases)
|
||||
|
||||
do
|
||||
local base = Cases[1].data
|
||||
local function fails(b: buffer, code: string, label: string)
|
||||
local d, e = Brstm.open(Bytes.reader(b))
|
||||
t:check(d == nil and e and e.code == code, label .. ": " .. tostring(e))
|
||||
end
|
||||
local beta = buffer.fromstring(base)
|
||||
buffer.writeu16(beta, 6, 0x0100) -- bytes 01 00 read big-endian: version 0.1
|
||||
fails(beta, Err.UNSUPPORTED, "version 0.1")
|
||||
fails(buffer.fromstring(string.sub(base, 1, 0x30)), Err.TRUNCATED, "short")
|
||||
fails(buffer.fromstring("RSTM\254\255\1\0" .. string.rep("\0", 100)), Err.CORRUPT, "no HEAD")
|
||||
local a = F.audio.load(Cases[2].data)
|
||||
t:check(a and a.meta.source.loop and a.meta.source.loop.start == Cases[2].loopStart, "F.audio.load keeps the loop")
|
||||
end
|
||||
|
||||
t:fuzz("open + read + seek", function(b: buffer)
|
||||
local dec = Brstm.open(Bytes.reader(b))
|
||||
if dec then
|
||||
dec:read(100000)
|
||||
dec:seek(dec.duration / 2)
|
||||
dec:read(33)
|
||||
end
|
||||
return dec
|
||||
end, samples, { mutations = 8 })
|
||||
t:fuzz("header", function(b: buffer)
|
||||
return Brstm.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 12, keepHeader = 0, garbage = 50 })
|
||||
|
||||
t:done()
|
||||
@@ -149,6 +149,7 @@ def dsp_frame(xs, h1, h2, coefs):
|
||||
a, b = h1, h2
|
||||
err = 0
|
||||
nibs = []
|
||||
outs = []
|
||||
for x in xs:
|
||||
base = 1024 + c1 * a + c2 * b
|
||||
want = ((x << 11) - base) / (scale << 11)
|
||||
@@ -156,36 +157,48 @@ def dsp_frame(xs, h1, h2, coefs):
|
||||
s = clamp16(((n * scale) << 11) + base >> 11)
|
||||
err += (x - s) ** 2
|
||||
nibs.append(n & 15)
|
||||
outs.append(s)
|
||||
a, b = s, a
|
||||
if best is not None and err >= best[0]:
|
||||
break
|
||||
else:
|
||||
if best is None or err < best[0]:
|
||||
best = (err, p << 4 | sc, nibs, a, b)
|
||||
best = (err, p << 4 | sc, nibs, outs)
|
||||
return best
|
||||
|
||||
|
||||
def dsp_encode(samples, coefs=DSP_COEFS):
|
||||
def dsp_encode(samples, coefs=DSP_COEFS, decoded=None):
|
||||
"""DSP frames; decoded (a list) receives the decoded samples (the history a seek table stores)"""
|
||||
out = bytearray()
|
||||
h1 = h2 = 0
|
||||
for k in range(0, len(samples), 14):
|
||||
xs = samples[k:k + 14]
|
||||
n = len(xs)
|
||||
xs = xs + [0] * (14 - n)
|
||||
_, head, nibs, a, b = dsp_frame(xs, h1, h2, coefs)
|
||||
_, head, nibs, outs = dsp_frame(xs, h1, h2, coefs)
|
||||
out.append(head)
|
||||
out += bytes(nibs[i] << 4 | nibs[i + 1] for i in range(0, 14, 2))
|
||||
h1, h2 = a, b
|
||||
h1, h2 = outs[-1], outs[-2]
|
||||
if decoded is not None:
|
||||
decoded += outs[:n]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def hist(dec, b, spb):
|
||||
"""(yn1, yn2) before block b: the last two decoded samples of the previous block"""
|
||||
if b == 0 or not dec:
|
||||
return (0, 0)
|
||||
return (dec[b * spb - 1], dec[b * spb - 2])
|
||||
|
||||
|
||||
def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec="dsp", coefs=DSP_COEFS):
|
||||
"""a BRSTM (kind RSTM, big-endian), BCSTM (CSTM, little-endian) or BFSTM (FSTM, big-endian unless le) file"""
|
||||
ints = s16(samples)
|
||||
frames = len(ints) // ch
|
||||
chans = [ints[c::ch] for c in range(ch)]
|
||||
decs = [[] for _ in range(ch)]
|
||||
if codec == "dsp":
|
||||
enc = [dsp_encode(x, coefs) for x in chans]
|
||||
enc = [dsp_encode(x, coefs, decs[c]) for c, x in enumerate(chans)]
|
||||
spb = block // 8 * 14
|
||||
elif codec == "pcm16":
|
||||
big = kind == "RSTM" or (kind == "FSTM" and not le)
|
||||
@@ -235,7 +248,7 @@ def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec
|
||||
head = b"HEAD" + struct.pack(">I", 0) + body
|
||||
head = head.ljust((len(head) + 31) // 32 * 32, b"\0")
|
||||
head = head[:4] + struct.pack(">I", len(head)) + head[8:]
|
||||
adpc_body = b"".join(struct.pack(">hh", 0, 0) * ch for _ in range(nblocks))
|
||||
adpc_body = b"".join(b"".join(struct.pack(">hh", *hist(decs[c], b, spb)) for c in range(ch)) for b in range(nblocks))
|
||||
adpc = b"ADPC" + struct.pack(">I", 0) + adpc_body
|
||||
adpc = adpc.ljust((len(adpc) + 31) // 32 * 32, b"\0")
|
||||
adpc = adpc[:4] + struct.pack(">I", len(adpc)) + adpc[8:]
|
||||
@@ -279,7 +292,7 @@ def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec
|
||||
info = b"INFO" + struct.pack(E + "I", 0) + body
|
||||
info = info.ljust((len(info) + 31) // 32 * 32, b"\0")
|
||||
info = info[:4] + struct.pack(E + "I", len(info)) + info[8:]
|
||||
seek = b"SEEK" + struct.pack(E + "I", 0) + b"".join(struct.pack(E + "hh", 0, 0) * ch for _ in range(nblocks))
|
||||
seek = b"SEEK" + struct.pack(E + "I", 0) + b"".join(b"".join(struct.pack(E + "hh", *hist(decs[c], b, spb)) for c in range(ch)) for b in range(nblocks))
|
||||
seek = seek.ljust((len(seek) + 31) // 32 * 32, b"\0")
|
||||
seek = seek[:4] + struct.pack(E + "I", len(seek)) + seek[8:]
|
||||
datac = b"DATA" + struct.pack(E + "I", len(data) + 0x20) + b"\0" * 0x18 + bytes(data)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Nintendo stream fixtures (tools/fixtures.py): audio/brstm. Our Python writer and DSP encoder (tools/fixtures/_adpcm.py)
|
||||
# build BRSTM / BCSTM / BFSTM files (DSP ADPCM with a filled ADPC / SEEK history table, PCM16, PCM8; several blocks
|
||||
# with a short padded last block; loops); vgmstream decodes them and reports the loops.
|
||||
# tests/gen/brstm_cases.luau { name, data, rate, ch, ref (s16le), loopStart?, loopEnd? }
|
||||
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/brstm"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
stereo = A.signal("music", 32000, 2, 9000, seed=31)
|
||||
mono = A.signal("sweep", 22050, 1, 8000, seed=32)
|
||||
made = [
|
||||
("rstm-dsp-stereo", "RSTM", stereo, 32000, 2, dict(block=0x800)),
|
||||
("rstm-dsp-mono-loop", "RSTM", mono, 22050, 1, dict(block=0x400, loop=(1000, 8000))),
|
||||
("rstm-pcm16-stereo", "RSTM", stereo, 32000, 2, dict(block=0x2000, codec="pcm16")),
|
||||
("cstm-dsp-stereo-loop", "CSTM", stereo, 32000, 2, dict(block=0x800, loop=(4000, 9000))),
|
||||
("cstm-pcm8-mono", "CSTM", mono, 22050, 1, dict(block=0x1000, codec="pcm8")),
|
||||
("fstm-be-dsp-stereo", "FSTM", stereo, 32000, 2, dict(block=0x1000)),
|
||||
("fstm-le-dsp-mono", "FSTM", mono, 22050, 1, dict(block=0x800, le=True)),
|
||||
("fstm-le-pcm16-stereo", "FSTM", stereo, 32000, 2, dict(block=0x1000, le=True, codec="pcm16")),
|
||||
]
|
||||
cases = []
|
||||
for name, kind, sig, rate, ch, kw in made:
|
||||
data = D.rstm(sig, rate, ch, kind, **kw)
|
||||
ext = {"RSTM": "brstm", "CSTM": "bcstm", "FSTM": "bfstm"}[kind]
|
||||
r, c, ref = D.vgdecode(ctx, data, ext)
|
||||
assert (r, c) == (rate, ch) and len(ref) == len(sig) * 2, (name, r, c, len(ref))
|
||||
e = dict(name=name, data=data, rate=rate, ch=ch, ref=ref)
|
||||
m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", D.vginfo(ctx, data, ext), re.S)
|
||||
if m:
|
||||
e["loopStart"], e["loopEnd"] = int(m.group(1)), int(m.group(2))
|
||||
cases.append(e)
|
||||
ctx.emit("brstm_cases", cases)
|
||||
Reference in new issue
Block a user