ws-audio2: codecs/audio/Adpcm (IMA / ima4 / IMA WAV / MS / ADX / PS-ADPCM / DSP decode, IMA + MS encode, Decoder layouts) and audio/adpcm (raw streams)

- codecs/audio/Adpcm: decoder kernels bit-exact with ffmpeg (IMA, ima4, MS) and vgmstream (ADX, PS-ADPCM, DSP);
  IMA nibble / IMA WAV / MS block encoders. Adpcm/Decoder: streaming Decoders over the shared layouts (channel
  interleaved frames, nibble streams, self-contained blocks) with exact seeking through state snapshots.
- audio/wav: its IMA / MS block decoders moved to codecs/audio/Adpcm (wav tests unchanged and green).
- codecs/audio/Stream (shared, small and backward compatible): pcm() may return a buffer of f32 (copied with
  buffer.copy) instead of a table.
- audio/adpcm: headerless ima / ima_wav / ms / ima_qt / psx streams by options; encode ima / ima_wav / ms.
- licenses: vgmstream (ISC).
This commit is contained in:
4DBug committed 2026-10-31 14:10:23 -05:00
1 parent de4f14a343
commit 363b14932f
14 files changed
+1931 -166

No files matched your search

+352
View File
@@ -0,0 +1,352 @@
# 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"formats-luau", 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 = []
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)
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)
return best
def dsp_encode(samples, coefs=DSP_COEFS):
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)
out.append(head)
out += bytes(nibs[i] << 4 | nibs[i + 1] for i in range(0, 14, 2))
h1, h2 = a, b
return bytes(out)
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)]
if codec == "dsp":
enc = [dsp_encode(x, coefs) for x in 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(struct.pack(">hh", 0, 0) * ch for _ 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(struct.pack(E + "hh", 0, 0) * ch for _ 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", "-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
+138
View File
@@ -0,0 +1,138 @@
# ADPCM fixtures (tools/fixtures.py): codecs/audio/Adpcm and the raw audio/adpcm format.
# tests/gen/adpcm_codec.luau raw codec streams with the reference decoder's s16le output: { name, kind, data, ch,
# frames, ref, rate?, cutoff?, v3?, coefs? }
# adx ffmpeg -f adx (version 3), the frames after the header; vgmstream decodes (scale + 1, v3 rounding)
# psx our Python PS-ADPCM encoder (tools/fixtures/_adpcm.py) in a VAG; vgmstream decodes
# dsp our Python DSP encoder in a mono BRSTM; vgmstream decodes
# ima_qt ffmpeg adpcm_ima_qt in AIFF-C (the SSND packets); ffmpeg decodes
# ima our Python IMA encoder in KVAG (high nibble first, stereo by nibble); ffmpeg (adpcm_ima_ssi) decodes
# tests/gen/adpcm_raw.luau headerless streams for audio/adpcm: { name, codec, data, rate, ch, blockAlign?, ref }
# ima / ima-stereo (KVAG data, ffmpeg), ms (ffmpeg adpcm_ms WAV data chunk, ffmpeg), ima_wav (ffmpeg
# adpcm_ima_wav), ima_qt (the AIFF-C packets), psx (VAG data), dsp (mono), adx-free
# tests/gen/adpcm_ours.luau our encoder's raw output (audio/adpcm encode, run in this step) wrapped in a container
# ffmpeg reads, ffmpeg's decode, and our own decode of the same bytes (must match)
# tests/gen/adpcm_sig.luau the encoder input (stereo)
import importlib.util, os, 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/adpcm"]
RATE = 22050
def aiff_ssnd(d):
p = 12
while p + 8 <= len(d):
cid, size = d[p:p + 4], struct.unpack_from(">I", d, p + 4)[0]
if cid == b"SSND":
off = struct.unpack_from(">I", d, p + 8)[0]
return d[p + 16 + off:p + 8 + size]
p += 8 + size + (size & 1)
raise ValueError("no SSND")
def wav_data(d):
p = 12
fmt = None
while p + 8 <= len(d):
cid, size = d[p:p + 4], struct.unpack_from("<I", d, p + 4)[0]
if cid == b"fmt ":
fmt = d[p + 8:p + 8 + size]
elif cid == b"data":
return fmt, d[p + 8:p + 8 + size]
p += 8 + size + (size & 1)
raise ValueError("no data")
def generate(ctx):
stereo = A.signal("music", RATE, 2, 5000, seed=7)
mono = A.signal("sweep", RATE, 1, 4100, seed=8)
w2, w1 = A.wav(stereo, RATE, 2), A.wav(mono, RATE, 1)
codec, raw = [], []
# ADX (ffmpeg writes version 3; vgmstream is the reference: CRI's scale + 1)
for name, w, ch in (("adx-mono", w1, 1), ("adx-stereo", w2, 2)):
f = D.ffencode(ctx, w, ["-c:a", "adpcm_adx", "-f", "adx"], "adx")
start = struct.unpack_from(">H", f, 2)[0] + 4
rate, frames, cutoff, ver = struct.unpack_from(">IIHH", f, 8)
_, rch, ref = D.vgdecode(ctx, f, "adx")
assert rch == ch and len(ref) == frames * ch * 2, (len(ref), frames)
codec.append(dict(name=name, kind="adx", data=f[start:], ch=ch, frames=frames, ref=ref, rate=rate,
cutoff=cutoff, v3=ver == 0x0300))
# PS-ADPCM in a VAG (mono)
v = D.vag(mono, RATE)
_, _, ref = D.vgdecode(ctx, v, "vag")
codec.append(dict(name="psx", kind="psx", data=v[0x30:], ch=1, frames=len(ref) // 2, ref=ref))
raw.append(dict(name="psx", codec="psx", data=v[0x30:], rate=RATE, ch=1, ref=ref))
# DSP in a mono BRSTM (one block holds everything)
ints = D.s16(mono)
dspdata = D.dsp_encode(ints)
f = D.rstm(mono, RATE, 1, "RSTM", block=(len(dspdata) + 31) // 32 * 32)
_, _, ref = D.vgdecode(ctx, f, "brstm")
assert len(ref) == len(ints) * 2
codec.append(dict(name="dsp", kind="dsp", data=dspdata, ch=1, frames=len(ints), ref=ref, coefs=D.DSP_COEFS))
# Apple ima4 (AIFF-C)
for name, w, ch in (("ima_qt-mono", w1, 1), ("ima_qt-stereo", w2, 2)):
f = D.ffencode(ctx, w, ["-c:a", "adpcm_ima_qt", "-f", "aiff"], "aiff")
data = aiff_ssnd(f)
ref = D.ffs16(ctx, f, "aiff")
codec.append(dict(name=name, kind="ima_qt", data=data, ch=ch, frames=len(ref) // (2 * ch), ref=ref))
raw.append(dict(name=name, codec="ima_qt", data=data, rate=RATE, ch=ch, ref=ref))
# IMA nibble streams (KVAG, high nibble first)
for name, sig, ch in (("ima-mono", mono, 1), ("ima-stereo", stereo, 2)):
f = D.kvag(sig, RATE, ch)
ref = D.ffs16(ctx, f, "vag", fmt="kvag")
codec.append(dict(name=name, kind="ima", data=f[14:], ch=ch, frames=len(ref) // (2 * ch), ref=ref))
raw.append(dict(name=name, codec="ima", data=f[14:], rate=RATE, ch=ch, ref=ref))
# MS ADPCM / IMA WAV blocks (ffmpeg), as raw block streams
for name, codec_, w, ch in (("ms-stereo", "adpcm_ms", w2, 2), ("ms-mono", "adpcm_ms", w1, 1),
("ima_wav-stereo", "adpcm_ima_wav", w2, 2)):
f = D.ffencode(ctx, w, ["-c:a", codec_, "-f", "wav"], "wav")
fmt, data = wav_data(f)
ba = struct.unpack_from("<H", fmt, 12)[0]
ref = D.ffs16(ctx, f, "wav")
raw.append(dict(name=name, codec="ms" if codec_ == "adpcm_ms" else "ima_wav", data=data, rate=RATE, ch=ch,
blockAlign=ba, ref=ref))
ctx.emit("adpcm_codec", codec)
ctx.emit("adpcm_raw", raw)
# our encoder (audio/adpcm) -> containers ffmpeg reads -> ffmpeg's decode; the test decodes the same bytes itself
A.emit_signal(ctx, "adpcm_sig", stereo, RATE, 2)
ours = []
for codec_, opts in (("ima", '{ codec = "ima" }'), ("ms", '{ codec = "ms", blockAlign = 512 }'),
("ima_wav", '{ codec = "ima_wav", blockAlign = 512 }')):
data = A.encode_luau(ctx, "audio/adpcm", "adpcm_sig", opts)
if codec_ == "ima":
f = b"KVAG" + struct.pack("<IIH", len(data), RATE, 1) + data
ref = D.ffs16(ctx, f, "vag", fmt="kvag")
else:
ba = 512
spb = (ba - 7 * 2) * 2 // 2 + 2 if codec_ == "ms" else (ba - 8) + 1
if codec_ == "ms":
coefs = b"".join(struct.pack("<hh", a, b) for a, b in zip([256, 512, 0, 192, 240, 460, 392], [0, -256, 0, 64, 0, -208, -232]))
ext = struct.pack("<HH", spb, 7) + coefs
fmt = struct.pack("<HHIIHHH", 2, 2, RATE, RATE * ba // spb, ba, 4, len(ext)) + ext
else:
fmt = struct.pack("<HHIIHHHH", 0x11, 2, RATE, RATE * ba // spb, ba, 4, 2, spb)
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + data
f = b"RIFF" + struct.pack("<I", len(body)) + body
ref = D.ffs16(ctx, f, "wav")
ours.append(dict(name=codec_, opts=opts, data=data, ref=ref))
ctx.emit("adpcm_ours", ours)