Files
rosetta/tools/fixtures/_adpcm.py
T

378 lines
16 KiB
Python

# Shared helpers for the ADPCM fixture generators (adpcm, adx, vag, brstm): small Python ADPCM encoders that build the
# game containers ffmpeg cannot write (Sony VAG, Nintendo BRSTM / BCSTM / BFSTM, Simon & Schuster KVAG); the files are
# decoded by vgmstream / ffmpeg as the references, so these encoders only need to be valid, not good.
# A = _adpcm.load()
# A.ima_encode(samples, ch, high_first=False) -> raw IMA nibble stream (state 0 / 0; channels interleaved by nibble)
# A.kvag(samples, rate, ch) -> a KVAG file (IMA, high nibble first)
# A.psx_encode(samples) -> bytes of 16-byte PS-ADPCM frames (mono); A.vag(samples, rate, name, loop=None)
# A.dsp_encode(samples, coefs) -> bytes of 8-byte DSP frames (mono); A.DSP_COEFS: the 16 coefficients used
# A.rstm(samples, rate, ch, kind="RSTM"|"CSTM"|"FSTM", loop=None, block=0x2000, le=None, codec="dsp"|"pcm16"|"pcm8")
# A.s16(floats) -> clipped ints
import math, struct, sys
IMA_STEP = [
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060,
1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484,
7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767]
IMA_INDEX = [-1, -1, -1, -1, 2, 4, 6, 8]
def load():
return sys.modules[__name__]
def s16(floats):
return [max(-32768, min(32767, int(math.floor(v * 32768 + 0.5)))) for v in floats]
def clamp16(v):
return -32768 if v < -32768 else 32767 if v > 32767 else v
def ima_step(pred, index, nib):
step = IMA_STEP[index]
d = step >> 3
if nib & 1:
d += step >> 2
if nib & 2:
d += step >> 1
if nib & 4:
d += step
pred = clamp16(pred - d if nib & 8 else pred + d)
index = max(0, min(88, index + IMA_INDEX[nib & 7]))
return pred, index
def ima_nibble(pred, index, x):
best = None
for nib in range(16):
p, _ = ima_step(pred, index, nib)
e = abs(x - p)
if best is None or e < best[0]:
best = (e, nib)
return best[1]
def ima_encode(samples, ch, high_first=False):
ints = s16(samples)
st = [[0, 0] for _ in range(ch)]
nibs = []
for i, x in enumerate(ints):
c = i % ch
n = ima_nibble(st[c][0], st[c][1], x)
st[c][0], st[c][1] = ima_step(st[c][0], st[c][1], n)
nibs.append(n)
if len(nibs) % 2:
nibs.append(0)
out = bytearray()
for k in range(0, len(nibs), 2):
a, b = nibs[k], nibs[k + 1]
out.append((a << 4 | b) if high_first else (b << 4 | a))
return bytes(out)
def kvag(samples, rate, ch):
data = ima_encode(samples, ch, high_first=True) # DVI order: the high nibble first (ffmpeg adpcm_ima_ssi, vgmstream)
return b"KVAG" + struct.pack("<IIH", len(data), rate, 1 if ch == 2 else 0) + data
# ------------------------------------------------------------------------------------------------ PS-ADPCM
PSX_COEFS = [(0, 0), (60, 0), (115, -52), (98, -55), (122, -60)]
def psx_frame(xs, h1, h2):
"""the best (filter, shift) for 28 samples: (error, header byte, nibbles, h1, h2) with vgmstream's decode"""
best = None
for f, (c1, c2) in enumerate(PSX_COEFS):
for shift in range(13):
a, b = h1, h2
err = 0
nibs = []
for x in xs:
pred = 4 * (c1 * a + c2 * b) # (c1 * a + c2 * b) / 64 * 256
# sample = (nib << (20 - shift) + pred) >> 8; pick the nibble closest to x
want = ((x << 8) - pred) / (1 << (20 - shift))
n = max(-8, min(7, int(round(want))))
s = (n * (1 << (20 - shift)) + pred) >> 8
cs = clamp16(s)
err += (x - cs) ** 2
nibs.append(n & 15)
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, f << 4 | shift, nibs, a, b)
return best
def psx_encode(samples, loop=None):
"""PS-ADPCM frames (mono ints) after the usual blank frame; loop = (start frame, end frame) sets the flags"""
out = bytearray(16)
h1 = h2 = 0
n = (len(samples) + 27) // 28
for k in range(n):
xs = samples[k * 28:(k + 1) * 28]
xs = xs + [0] * (28 - len(xs))
_, head, nibs, h1, h2 = psx_frame(xs, h1, h2)
flag = 0
if loop:
if k == loop[0]:
flag = 6
elif k == loop[1] - 1:
flag = 3
elif loop[0] < k < loop[1] - 1:
flag = 2
elif k == n - 1:
flag = 1
out += bytes([head, flag]) + bytes(nibs[i] | nibs[i + 1] << 4 for i in range(0, 28, 2))
return bytes(out)
def vag(samples, rate, name=b"rosetta", loop=None):
data = psx_encode(s16(samples), loop)
head = b"VAGp" + struct.pack(">IIII", 0x20, 0, len(data), rate) + b"\0" * 12 + name[:16].ljust(16, b"\0")
return head + data
# ------------------------------------------------------------------------------------------------ Nintendo DSP
DSP_COEFS = [0, 0, 2048, 0, 0, 2048, 4096, -2048, 3600, -1700, 3000, -1100, 1024, 0, 3900, -1950]
def dsp_frame(xs, h1, h2, coefs):
best = None
for p in range(8):
c1, c2 = coefs[2 * p], coefs[2 * p + 1]
for sc in range(12):
scale = 1 << sc
a, b = h1, h2
err = 0
nibs = []
outs = []
for x in xs:
base = 1024 + c1 * a + c2 * b
want = ((x << 11) - base) / (scale << 11)
n = max(-8, min(7, int(round(want))))
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, outs)
return best
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, 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 = 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, decs[c]) for c, x in enumerate(chans)]
spb = block // 8 * 14
elif codec == "pcm16":
big = kind == "RSTM" or (kind == "FSTM" and not le)
enc = [b"".join(struct.pack(">h" if big else "<h", v) for v in x) for x in chans]
spb = block // 2
else:
enc = [bytes((v >> 8) & 255 for v in x) for x in chans]
spb = block
nblocks = (frames + spb - 1) // spb
last_samples = frames - (nblocks - 1) * spb
last_size = len(enc[0]) - (nblocks - 1) * block
last_padded = (last_size + 31) // 32 * 32
data = bytearray()
for b in range(nblocks):
for c in range(ch):
part = enc[c][b * block:(b + 1) * block]
if b == nblocks - 1:
part = part.ljust(last_padded, b"\0")
data += part
codec_id = {"pcm8": 0, "pcm16": 1, "dsp": 2}[codec]
ls, le_ = (loop if loop else (0, frames))
if kind == "RSTM":
info = struct.pack(">BBBBHHIIIIIIIIIIII", codec_id, 1 if loop else 0, ch, 0, rate, 0, ls, frames, 0, nblocks,
block, spb, last_size, last_samples, last_padded, spb, 4, 0)
# HEAD: 3 references, the stream info, track info, channel info
def ref(off):
return struct.pack(">II", 0x01000000, off)
p_info = 0x18
p_track = p_info + len(info)
track_table = struct.pack(">BBBB", 1, 0, 0, 0) # 1 track, type 0
p_trackent = p_track + 4 + 8
track_ent = struct.pack(">BBBB", 127, 64, 0, 0) + struct.pack(">I", 0) + struct.pack(">BBBB", ch, 0, 1, 0)
track_blob = track_table + ref(p_trackent) + track_ent
p_chan = p_track + len(track_blob)
chan_head = struct.pack(">BBBB", ch, 0, 0, 0)
p_chinfo = p_chan + 4 + 8 * ch
chan_refs = b""
chan_infos = b""
for c in range(ch):
me = p_chinfo + len(chan_infos)
chan_refs += ref(me)
adp = struct.pack(">16h", *coefs) + struct.pack(">HHhhHhhH", 0, enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0)
chan_infos += ref(me + 8) + adp
body = info + track_blob + chan_head + chan_refs + chan_infos
body = ref(p_info) + ref(p_track) + ref(p_chan) + body
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(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:]
hsize = 0x40
o_head = hsize
o_adpc = o_head + len(head)
o_data = o_adpc + len(adpc)
datac = b"DATA" + struct.pack(">II", len(data) + 0x20, 0x18) + b"\0" * 0x14 + bytes(data)
start = o_data + 0x20
head = bytearray(head)
struct.pack_into(">I", head, 8 + 8 * 3 + 0x10, start) # data offset (absolute)
total = o_data + len(datac)
hdr = b"RSTM" + struct.pack(">HHIHH", 0xFEFF, 0x0100, total, hsize, 2) + struct.pack(">IIIIII", o_head, len(head), o_adpc,
len(adpc), o_data, len(datac))
hdr = hdr.ljust(hsize, b"\0")
return hdr + bytes(head) + adpc + datac
# CSTM / FSTM
E = ">" if (kind == "FSTM" and not le) else "<"
def ref(t, off):
return struct.pack(E + "HHi", t, 0, off)
# INFO: refs (stream info, track table, channel table), stream info, channel table, channel infos, dsp infos
stream_info = struct.pack(E + "BBBB", codec_id, 1 if loop else 0, ch, 0) + struct.pack(
E + "IIIIIIIIIII", rate, ls, frames, nblocks, block, spb, last_size, last_samples, last_padded, 4 * ch, spb)
stream_info += ref(0x1F00, 0x18) # sample data: DATA + 8 + 0x18
p_stream = 0x18
p_chtab = p_stream + len(stream_info)
chtab = struct.pack(E + "I", ch)
p_chinfo = p_chtab + 4 + 8 * ch
infos = b""
adps = b""
for c in range(ch):
chtab += ref(0x4102, p_chinfo + 8 * c - p_chtab)
p_adp = p_chinfo + 8 * ch
for c in range(ch):
me = p_chinfo + 8 * c
adp_at = p_adp + len(adps)
infos += ref(0x0300, adp_at - me) if codec == "dsp" else ref(0, -1)
adps += struct.pack(E + "16h", *coefs) + struct.pack(E + "HhhHhhH", enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0)
body = ref(0x4100, p_stream) + ref(0, -1) + ref(0x0101, p_chtab) + stream_info + chtab + infos + adps
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(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)
hsize = 0x40
o_info = hsize
o_seek = o_info + len(info)
o_data = o_seek + len(seek)
total = o_data + len(datac)
ver = 0x02000000 if kind == "CSTM" else 0x00040000
hdr = kind.encode() + (b"\xfe\xff" if E == ">" else b"\xff\xfe") + struct.pack(E + "HII", hsize, ver, total)
hdr += struct.pack(E + "HH", 3, 0)
hdr += struct.pack(E + "HHII", 0x4000, 0, o_info, len(info))
hdr += struct.pack(E + "HHII", 0x4001, 0, o_seek, len(seek))
hdr += struct.pack(E + "HHII", 0x4002, 0, o_data, len(datac))
hdr = hdr.ljust(hsize, b"\0")
return hdr + info + seek + datac
# ------------------------------------------------------------------------------------------------ references
def wav_pcm(data):
"""(rate, channels, s16le bytes) of a 16-bit PCM WAV (vgmstream's output)"""
p = 12
rate = ch = None
while p + 8 <= len(data):
cid, size = data[p:p + 4], struct.unpack_from("<I", data, p + 4)[0]
if cid == b"fmt ":
ch, rate = struct.unpack_from("<HI", data, p + 10)
elif cid == b"data":
return rate, ch, data[p + 8:p + 8 + size]
p += 8 + size + (size & 1)
raise ValueError("no data chunk")
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", "-i", "-o", "{out}", "{in}"], data, ext, outext="wav")
return wav_pcm(out)
def vginfo(ctx, data, ext):
A = _audio()
return A.tool(ctx, "vgmstream", ["vgmstream-cli", "-m", "{in}"], data, ext).decode(errors="replace")
def ffs16(ctx, data, ext, fmt=None):
"""ffmpeg's decode as s16le bytes"""
A = _audio()
return A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error"] + (["-f", fmt] if fmt else []) + ["-i", "{in}", "-f", "s16le",
"-acodec", "pcm_s16le", "-"], data, ext)
def ffencode(ctx, wavdata, args, ext):
"""ffmpeg encodes a WAV input with args into a file of extension ext"""
A = _audio()
return A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}"] + list(args) + ["-y", "{out}"], wavdata, "wav",
outext=ext)
_A = None
def _audio():
global _A
if _A is None:
import importlib.util, os
spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
_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