Fixture: tools/fixtures/_tracker.py write_xm gains an optional per-sample "adpcm" payload (two lines, shared with the tracker generators, backward compatible); a new xm case renders the same as openmpt123.
497 lines
21 KiB
Python
497 lines
21 KiB
Python
# Tracker fixture helpers (used by tools/fixtures/{mod,s3m,xm,it}.py): small writers for MOD, S3M, XM and IT
|
|
# (including IT 2.14 / 2.15 sample compression), synthesized samples, reference renders through openmpt123 (nix
|
|
# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 40 log-spaced band
|
|
# magnitudes of the mid signal), computed the same way in tests/music/_similar.luau. Every module is generated here
|
|
# (no third-party files), so the fixtures carry no licence.
|
|
import json, math, os, struct, subprocess, tempfile
|
|
|
|
SR = 44100
|
|
HOP = 2048
|
|
BANDS = 40
|
|
F_LO, F_HI = 150.0, 16000.0
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------- samples
|
|
def synth(kind, n, period, amp=0.9, seed=1, decay=None):
|
|
"""float samples in [-1, 1]: sine / square / saw / tri / noise / pluck"""
|
|
out = []
|
|
s = seed
|
|
for i in range(n):
|
|
ph = (i % period) / period
|
|
if kind == "sine":
|
|
v = math.sin(2 * math.pi * ph)
|
|
elif kind == "square":
|
|
v = 1.0 if ph < 0.5 else -1.0
|
|
elif kind == "saw":
|
|
v = 2 * ph - 1
|
|
elif kind == "tri":
|
|
v = 4 * ph - 1 if ph < 0.5 else 3 - 4 * ph
|
|
else: # noise
|
|
s = (s * 1103515245 + 12345) % 2147483648
|
|
v = (s / 2147483648) * 2 - 1
|
|
if decay:
|
|
v *= math.exp(-i / decay)
|
|
out.append(v * amp)
|
|
return out
|
|
|
|
|
|
def s8(xs):
|
|
return bytes((max(-128, min(127, int(round(x * 127)))) & 255) for x in xs)
|
|
|
|
|
|
def u8(xs):
|
|
return bytes(max(0, min(255, int(round(x * 127)) + 128)) for x in xs)
|
|
|
|
|
|
def s16(xs):
|
|
return b"".join(struct.pack("<h", max(-32768, min(32767, int(round(x * 32767))))) for x in xs)
|
|
|
|
|
|
def delta8(raw):
|
|
out, prev = bytearray(), 0
|
|
for b in raw:
|
|
v = b - 256 if b >= 128 else b
|
|
out.append((v - prev) & 255)
|
|
prev = v
|
|
return bytes(out)
|
|
|
|
|
|
def delta16(raw):
|
|
out, prev = bytearray(), 0
|
|
for i in range(0, len(raw), 2):
|
|
v = struct.unpack_from("<h", raw, i)[0]
|
|
out += struct.pack("<H", (v - prev) & 0xFFFF)
|
|
prev = v
|
|
return bytes(out)
|
|
|
|
|
|
def name(s, n):
|
|
b = s.encode()[:n]
|
|
return b + b"\0" * (n - len(b))
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------- MOD
|
|
PERIODS = [1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
|
|
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453,
|
|
428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226,
|
|
214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113]
|
|
|
|
|
|
def mod_period(note): # note 1 = C-0; 49 = ProTracker C-2 (428)
|
|
return PERIODS[note - 25] if note else 0
|
|
|
|
|
|
def write_mod(title, samples, orders, patterns, channels=4, restart=127):
|
|
"""samples: [{name, data (s8 bytes, even length), volume, finetune (-8..7), loop: (start, length) | None}];
|
|
patterns: [[row: [(note, ins, fx, param)] * channels] * 64]"""
|
|
out = bytearray(name(title, 20))
|
|
for i in range(31):
|
|
if i < len(samples):
|
|
s = samples[i]
|
|
ls, ll = s.get("loop") or (0, 2)
|
|
out += name(s.get("name", ""), 22) + struct.pack(">HBBHH", len(s["data"]) // 2, s.get("finetune", 0) & 15,
|
|
s.get("volume", 64), ls // 2, ll // 2)
|
|
else:
|
|
out += b"\0" * 22 + struct.pack(">HBBHH", 0, 0, 0, 0, 1)
|
|
out += bytes([len(orders), restart]) + bytes(orders) + b"\0" * (128 - len(orders))
|
|
out += b"M.K." if channels == 4 else (b"%dCHN" % channels if channels < 10 else b"%dCH" % channels)
|
|
for pat in patterns:
|
|
for row in pat:
|
|
for (note, ins, fx, param) in row:
|
|
p = mod_period(note)
|
|
out += bytes([(ins & 0xF0) | (p >> 8), p & 255, ((ins & 15) << 4) | fx, param])
|
|
for s in samples:
|
|
out += s["data"]
|
|
return bytes(out)
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------- S3M
|
|
def write_s3m(title, samples, orders, patterns, channels, speed=6, tempo=125, gvol=64, mvol=48 | 128, pans=None,
|
|
flags=0, cwt=0x1320, chanset=None):
|
|
"""samples: [{name, data (u8 bytes), volume, c2spd, loop: (start, end) | None}];
|
|
patterns: [[row: [(note, ins, vol, cmd, info)] * channels] * 64] with note 0 = none, 254 = cut, else S3M byte
|
|
(octave << 4 | semitone); vol None = none; cmd 0 = none (A = 1)."""
|
|
ordn = list(orders) + [255]
|
|
if len(ordn) % 2:
|
|
ordn.append(255)
|
|
nins, npat = len(samples), len(patterns)
|
|
head = bytearray(name(title, 28) + bytes([0x1A, 16, 0, 0]))
|
|
head += struct.pack("<HHHHHH", len(ordn), nins, npat, flags, cwt, 2) + b"SCRM"
|
|
head += bytes([gvol, speed, tempo, mvol, 16, 252 if pans else 0]) + b"\0" * 8 + struct.pack("<H", 0)
|
|
cs = chanset or [(i % 2) * 8 + i // 2 if i < channels else 255 for i in range(32)]
|
|
head += bytes(cs[:32] + [255] * (32 - len(cs)))
|
|
head += bytes(ordn)
|
|
ptr_at = len(head)
|
|
head += b"\0" * (2 * (nins + npat))
|
|
if pans:
|
|
head += bytes([(0x20 | (p & 15)) for p in pans] + [0] * (32 - len(pans)))
|
|
body = bytearray(head)
|
|
|
|
def align():
|
|
while len(body) % 16:
|
|
body.append(0)
|
|
|
|
ins_ptrs, pat_ptrs, ins_at = [], [], []
|
|
for s in samples:
|
|
align()
|
|
ins_ptrs.append(len(body) // 16)
|
|
ins_at.append(len(body))
|
|
body += b"\0" * 80
|
|
for pat in patterns:
|
|
align()
|
|
pat_ptrs.append(len(body) // 16)
|
|
pk = bytearray()
|
|
for row in pat:
|
|
for ch, (note, ins, vol, cmd, info) in enumerate(row):
|
|
what = 0
|
|
if note or ins:
|
|
what |= 0x20
|
|
if vol is not None:
|
|
what |= 0x40
|
|
if cmd:
|
|
what |= 0x80
|
|
if what:
|
|
pk.append(what | ch)
|
|
if what & 0x20:
|
|
pk += bytes([note if note else 255, ins])
|
|
if what & 0x40:
|
|
pk.append(vol)
|
|
if what & 0x80:
|
|
pk += bytes([cmd, info])
|
|
pk.append(0)
|
|
body += struct.pack("<H", len(pk) + 2) + pk
|
|
for i, s in enumerate(samples):
|
|
align()
|
|
seg = len(body) // 16
|
|
body += s["data"]
|
|
ls, le = s.get("loop") or (0, 0)
|
|
h = bytearray(80)
|
|
h[0] = 1
|
|
h[1:13] = name(s.get("name", "") + ".smp", 12)
|
|
h[13] = seg >> 16
|
|
struct.pack_into("<H", h, 14, seg & 0xFFFF)
|
|
struct.pack_into("<IIIBBBB", h, 16, len(s["data"]), ls, le, s.get("volume", 64), 0, 0, 1 if s.get("loop") else 0)
|
|
struct.pack_into("<I", h, 32, s.get("c2spd", 8363))
|
|
h[48:76] = name(s.get("name", ""), 28)
|
|
h[76:80] = b"SCRS"
|
|
body[ins_at[i]:ins_at[i] + 80] = h
|
|
for k, p in enumerate(ins_ptrs + pat_ptrs):
|
|
struct.pack_into("<H", body, ptr_at + 2 * k, p)
|
|
return bytes(body)
|
|
|
|
|
|
def s3m_note(note):
|
|
"""our note number (1 = C-0, 61 = C-5 IT = S3M C-4) -> the S3M note byte"""
|
|
n = note - 13
|
|
return (n // 12) << 4 | (n % 12)
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------- XM
|
|
def env_bytes(points):
|
|
b = bytearray()
|
|
for (x, y) in points[:12]:
|
|
b += struct.pack("<HH", x, y)
|
|
return bytes(b + b"\0" * (48 - len(b)))
|
|
|
|
|
|
def write_xm(title, instruments, orders, patterns, channels, speed=6, tempo=125, linear=True, restart=0):
|
|
"""instruments: [{name, samples: [{name, data (raw bytes, not delta), bits 8|16, volume, finetune, pan, relnote,
|
|
loop: (start, length, type 1|2) | None}], keymap: [96 sample indexes] | None, volenv: {points, sustain, loop:
|
|
(s, e)} | None, panenv: ..., fadeout, vib: (type, sweep, depth, rate)}];
|
|
patterns: [[row: [(note, ins, vol, fx, param)] * channels]] (note 97 = key off; vol = raw volume byte)"""
|
|
out = bytearray(b"Extended Module: " + name(title, 20) + b"\x1a" + name("formats-luau fixtures", 20))
|
|
out += struct.pack("<HIHHHHHHHH", 0x0104, 276, len(orders), restart, channels, len(patterns), len(instruments),
|
|
1 if linear else 0, speed, tempo)
|
|
out += bytes(orders) + b"\0" * (256 - len(orders))
|
|
for pat in patterns:
|
|
pk = bytearray()
|
|
for row in pat:
|
|
for (note, ins, vol, fx, param) in row:
|
|
flags = 0x80 | (1 if note else 0) | (2 if ins else 0) | (4 if vol else 0) | (8 if fx else 0) | (16 if param else 0)
|
|
pk.append(flags)
|
|
for bit, v in ((1, note), (2, ins), (4, vol), (8, fx), (16, param)):
|
|
if flags & bit:
|
|
pk.append(v)
|
|
out += struct.pack("<IBHH", 9, 0, len(pat), len(pk)) + pk
|
|
for ins in instruments:
|
|
smps = ins.get("samples", [])
|
|
if not smps:
|
|
out += struct.pack("<I", 29) + name(ins.get("name", ""), 22) + struct.pack("<BH", 0, 0)
|
|
continue
|
|
h = bytearray(struct.pack("<I", 263) + name(ins.get("name", ""), 22) + struct.pack("<BHI", 0, len(smps), 40))
|
|
h += bytes(ins.get("keymap") or [0] * 96)
|
|
ve, pe = ins.get("volenv"), ins.get("panenv")
|
|
h += env_bytes(ve["points"] if ve else []) + env_bytes(pe["points"] if pe else [])
|
|
h += bytes([len(ve["points"]) if ve else 0, len(pe["points"]) if pe else 0])
|
|
for e in (ve, pe):
|
|
if e:
|
|
ls, le = e.get("loop") or (0, 0)
|
|
h += bytes([e.get("sustain", 0) or 0, ls, le])
|
|
else:
|
|
h += b"\0\0\0"
|
|
for e in (ve, pe):
|
|
t = 0
|
|
if e:
|
|
t = 1 | (2 if e.get("sustain") is not None else 0) | (4 if e.get("loop") else 0)
|
|
h.append(t)
|
|
vt, vs, vd, vr = ins.get("vib", (0, 0, 0, 0))
|
|
h += bytes([vt, vs, vd, vr]) + struct.pack("<H", ins.get("fadeout", 0)) + b"\0" * 22
|
|
out += h
|
|
for s in smps:
|
|
bpsm = 2 if s.get("bits", 8) == 16 else 1
|
|
ls, ll, lt = s.get("loop") or (0, 0, 0)
|
|
t = lt | (16 if bpsm == 2 else 0)
|
|
out += struct.pack("<IIIBbBBbB", len(s["data"]), ls * bpsm, ll * bpsm, s.get("volume", 64), s.get("finetune", 0),
|
|
t, s.get("pan", 128), s.get("relnote", 0), 0xAD if s.get("adpcm") else 0) + name(s.get("name", ""), 22)
|
|
for s in smps:
|
|
# "adpcm": ModPlug ADPCM bytes (16-byte delta table + nibbles) stored instead of the delta samples
|
|
out += s["adpcm"] if s.get("adpcm") else delta16(s["data"]) if s.get("bits", 8) == 16 else delta8(s["data"])
|
|
return bytes(out)
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------- IT
|
|
def it_compress(raw, bits, it215):
|
|
"""IT 2.14 / 2.15 compression with a constant bit width (9 for 8-bit, 17 for 16-bit): valid for every decoder,
|
|
no width changes"""
|
|
width = 9 if bits == 8 else 17
|
|
block = 0x8000 if bits == 8 else 0x4000
|
|
if bits == 8:
|
|
vals = [b - 256 if b >= 128 else b for b in raw]
|
|
else:
|
|
vals = [struct.unpack_from("<h", raw, i)[0] for i in range(0, len(raw), 2)]
|
|
mask = (1 << (bits)) - 1
|
|
out = bytearray()
|
|
for start in range(0, len(vals), block):
|
|
chunk = vals[start:start + block]
|
|
acc, nbits, data = 0, 0, bytearray()
|
|
d1 = d2 = 0
|
|
for v in chunk:
|
|
if it215:
|
|
nd1 = v - d2 # second-order: the decoder does d1 += x; d2 += d1; out d2
|
|
x = nd1 - d1
|
|
d1, d2 = nd1, v
|
|
else:
|
|
x = v - d1
|
|
d1 = v
|
|
acc |= (x & mask) << nbits
|
|
nbits += width
|
|
while nbits >= 8:
|
|
data.append(acc & 255)
|
|
acc >>= 8
|
|
nbits -= 8
|
|
if nbits:
|
|
data.append(acc & 255)
|
|
out += struct.pack("<H", len(data)) + data
|
|
return bytes(out)
|
|
|
|
|
|
def it_env(e):
|
|
b = bytearray(82)
|
|
if e:
|
|
flags = 1 | (2 if e.get("loop") else 0) | (4 if e.get("sustain") else 0) | (128 if e.get("filter") else 0)
|
|
b[0] = flags
|
|
b[1] = len(e["points"])
|
|
ls, le = e.get("loop") or (0, 0)
|
|
ss, se = e.get("sustain") or (0, 0)
|
|
b[2], b[3], b[4], b[5] = ls, le, ss, se
|
|
for i, (x, y) in enumerate(e["points"][:25]):
|
|
struct.pack_into("<bH", b, 6 + i * 3, y, x)
|
|
return bytes(b)
|
|
|
|
|
|
def write_it(title, samples, instruments, orders, patterns, channels, speed=6, tempo=125, gv=128, mv=48, linear=True,
|
|
old=False, compat=False, pans=None, vols=None, msg=None):
|
|
"""samples: [{name, data (raw signed bytes), bits, stereo, volume, gv, pan (0..64) | None, c5, loop: (s, e, ping),
|
|
sus: (s, e, ping), compress: None | 214 | 215, vib: (speed, depth, rate, type)}];
|
|
instruments: None (sample mode) or [{name, nna, dct, dca, fadeout, gbv, pan | None, pps, ppc, ifc, ifr,
|
|
keymap: [(note, sample)] * 120, volenv / panenv / pitchenv: {points [(tick, value)], loop, sustain, filter}}];
|
|
patterns: [[row: [(note, ins, vol, cmd, param)] * channels]] with note 0 = none else IT note + 1 (1 = C-0) or
|
|
255 off / 254 cut / 253 fade (stored as 246, like IT); vol None or the raw volume byte; cmd 0 = none (A = 1)."""
|
|
ins_list = instruments or []
|
|
ordn = list(orders) + [255]
|
|
flags = 1 | (4 if instruments else 0) | (8 if linear else 0) | (16 if old else 0) | (32 if compat else 0)
|
|
head = bytearray(b"IMPM" + name(title, 26) + struct.pack("<H", 0x1004))
|
|
head += struct.pack("<HHHHHHHH", len(ordn), len(ins_list), len(samples), len(patterns), 0x0214, 0x0214, flags, 0)
|
|
head += bytes([gv, mv, speed, tempo, 128, 0]) + struct.pack("<HII", 0, 0, 0)
|
|
cp = [(pans[i] if pans and i < len(pans) else 32) if i < channels else 32 + 128 for i in range(64)]
|
|
head += bytes(cp) + bytes([(vols[i] if vols and i < len(vols) else 64) for i in range(64)])
|
|
head += bytes(ordn)
|
|
ptr_at = len(head)
|
|
head += b"\0" * (4 * (len(ins_list) + len(samples) + len(patterns)))
|
|
body = bytearray(head)
|
|
ptrs = []
|
|
for ins in ins_list:
|
|
ptrs.append(len(body))
|
|
b = bytearray(554)
|
|
b[0:4] = b"IMPI"
|
|
b[17], b[18], b[19] = ins.get("nna", 0), ins.get("dct", 0), ins.get("dca", 0)
|
|
struct.pack_into("<H", b, 20, ins.get("fadeout", 0))
|
|
struct.pack_into("<bB", b, 22, ins.get("pps", 0), ins.get("ppc", 60))
|
|
b[24] = ins.get("gbv", 128)
|
|
b[25] = ins["pan"] if ins.get("pan") is not None else 128 + 32
|
|
b[32:58] = name(ins.get("name", ""), 26)
|
|
b[58] = ins.get("ifc", 0)
|
|
b[59] = ins.get("ifr", 0)
|
|
km = ins["keymap"]
|
|
for n in range(120):
|
|
b[64 + 2 * n], b[65 + 2 * n] = km[n]
|
|
for k, key in enumerate(("volenv", "panenv", "pitchenv")):
|
|
b[304 + 82 * k:386 + 82 * k] = it_env(ins.get(key))
|
|
body += b
|
|
smp_at = []
|
|
for s in samples:
|
|
ptrs.append(len(body))
|
|
smp_at.append(len(body))
|
|
body += b"\0" * 80
|
|
for pat in patterns:
|
|
ptrs.append(len(body))
|
|
pk = bytearray()
|
|
for row in pat:
|
|
for ch, (note, ins, vol, cmd, param) in enumerate(row):
|
|
mask = (1 if note else 0) | (2 if ins else 0) | (4 if vol is not None else 0) | (8 if cmd else 0)
|
|
if mask:
|
|
pk += bytes([(ch + 1) | 128, mask])
|
|
if note:
|
|
pk.append(note - 1 if note < 253 else (246 if note == 253 else note))
|
|
if ins:
|
|
pk.append(ins)
|
|
if vol is not None:
|
|
pk.append(vol)
|
|
if cmd:
|
|
pk += bytes([cmd, param])
|
|
pk.append(0)
|
|
body += struct.pack("<HHI", len(pk), len(pat), 0) + pk
|
|
for i, s in enumerate(samples):
|
|
raw = s["data"]
|
|
stereo = s.get("stereo", False)
|
|
bps = 2 if s.get("bits", 8) == 16 else 1
|
|
frames = len(raw) // bps // (2 if stereo else 1)
|
|
comp = s.get("compress")
|
|
if comp:
|
|
if stereo:
|
|
half = len(raw) // 2
|
|
data = it_compress(raw[:half], s.get("bits", 8), comp == 215) + it_compress(raw[half:], s.get("bits", 8), comp == 215)
|
|
else:
|
|
data = it_compress(raw, s.get("bits", 8), comp == 215)
|
|
else:
|
|
data = raw
|
|
ptr = len(body)
|
|
body += data
|
|
h = bytearray(80)
|
|
h[0:4] = b"IMPS"
|
|
fl = 1 | (2 if bps == 2 else 0) | (4 if stereo else 0) | (8 if comp else 0)
|
|
lp, sp = s.get("loop"), s.get("sus")
|
|
if lp:
|
|
fl |= 16 | (64 if lp[2] else 0)
|
|
if sp:
|
|
fl |= 32 | (128 if sp[2] else 0)
|
|
h[17], h[18], h[19] = s.get("gv", 64), fl, s.get("volume", 64)
|
|
h[20:46] = name(s.get("name", ""), 26)
|
|
h[46] = 1 | (4 if comp == 215 else 0)
|
|
h[47] = (s["pan"] | 128) if s.get("pan") is not None else 32
|
|
struct.pack_into("<IIIIIII", h, 48, frames, lp[0] if lp else 0, lp[1] if lp else 0, s.get("c5", 8363),
|
|
sp[0] if sp else 0, sp[1] if sp else 0, ptr)
|
|
vs, vd, vr, vt = s.get("vib", (0, 0, 0, 0))
|
|
h[76], h[77], h[78], h[79] = vs, vd, vr, vt
|
|
body[smp_at[i]:smp_at[i] + 80] = h
|
|
for k, p in enumerate(ptrs):
|
|
struct.pack_into("<I", body, ptr_at + 4 * k, p)
|
|
return bytes(body)
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------- reference render
|
|
def openmpt(ctx, data, ext, extra=()):
|
|
"""the module rendered by openmpt123 (linear interpolation, no Amiga resampler): (left, right) float lists"""
|
|
with tempfile.TemporaryDirectory() as d:
|
|
p = os.path.join(d, "song." + ext)
|
|
with open(p, "wb") as f:
|
|
f.write(data)
|
|
raw = ctx.nix("libopenmpt", ["openmpt123", "--batch", "--quiet", "--stdout", "--samplerate", str(SR),
|
|
"--channels", "2", "--float", "--filter", "2", "--stereo", "100",
|
|
"--ctl", "render.resampler.emulate_amiga=0", *extra, p])
|
|
import array
|
|
a = array.array("f")
|
|
a.frombytes(raw[: len(raw) // 8 * 8])
|
|
return a[0::2], a[1::2]
|
|
|
|
|
|
def fft(re, im):
|
|
n = len(re)
|
|
j = 0
|
|
for i in range(1, n):
|
|
bit = n >> 1
|
|
while j & bit:
|
|
j ^= bit
|
|
bit >>= 1
|
|
j |= bit
|
|
if i < j:
|
|
re[i], re[j] = re[j], re[i]
|
|
im[i], im[j] = im[j], im[i]
|
|
size = 2
|
|
while size <= n:
|
|
ang = -2 * math.pi / size
|
|
wr, wi = math.cos(ang), math.sin(ang)
|
|
for start in range(0, n, size):
|
|
cr, ci = 1.0, 0.0
|
|
half = size // 2
|
|
for k in range(half):
|
|
a, b = start + k, start + k + half
|
|
tr = re[b] * cr - im[b] * ci
|
|
ti = re[b] * ci + im[b] * cr
|
|
re[b], im[b] = re[a] - tr, im[a] - ti
|
|
re[a], im[a] = re[a] + tr, im[a] + ti
|
|
cr, ci = cr * wr - ci * wi, cr * wi + ci * wr
|
|
size *= 2
|
|
|
|
|
|
EDGES = [F_LO * (F_HI / F_LO) ** (j / BANDS) for j in range(BANDS + 1)]
|
|
WINDOW = [0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) for i in range(HOP)]
|
|
|
|
|
|
def features(left, right):
|
|
"""{frames, rmsL, rmsR, rmsM, bands (frames * BANDS magnitudes)} of a stereo signal"""
|
|
n = len(left) // HOP
|
|
out = {"frames": n, "rmsL": [], "rmsR": [], "rmsM": [], "bands": []}
|
|
for k in range(n):
|
|
o = k * HOP
|
|
L, R = left[o:o + HOP], right[o:o + HOP]
|
|
M = [(a + b) / 2 for a, b in zip(L, R)]
|
|
out["rmsL"].append(math.sqrt(sum(x * x for x in L) / HOP))
|
|
out["rmsR"].append(math.sqrt(sum(x * x for x in R) / HOP))
|
|
out["rmsM"].append(math.sqrt(sum(x * x for x in M) / HOP))
|
|
re = [M[i] * WINDOW[i] for i in range(HOP)]
|
|
im = [0.0] * HOP
|
|
fft(re, im)
|
|
e = [0.0] * BANDS
|
|
for b in range(1, HOP // 2):
|
|
f = b * SR / HOP
|
|
if f < F_LO or f >= F_HI:
|
|
continue
|
|
j = min(BANDS - 1, int(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS))
|
|
e[j] += re[b] * re[b] + im[b] * im[b]
|
|
out["bands"] += [math.sqrt(x) for x in e]
|
|
return out
|
|
|
|
|
|
def duration(ctx, data, ext):
|
|
"""openmpt123 --info's song length in seconds"""
|
|
with tempfile.TemporaryDirectory() as d:
|
|
p = os.path.join(d, "song." + ext)
|
|
with open(p, "wb") as f:
|
|
f.write(data)
|
|
info = ctx.nix("libopenmpt", ["openmpt123", "--info", p]).decode(errors="replace")
|
|
for line in info.splitlines():
|
|
if line.startswith("Duration"):
|
|
secs = 0.0
|
|
for part in line.split(":", 1)[1].strip().split(":"):
|
|
secs = secs * 60 + float(part)
|
|
return secs
|
|
raise RuntimeError("openmpt123 --info: no duration")
|
|
|
|
|
|
def reference(ctx, data, ext, extra=()):
|
|
left, right = openmpt(ctx, data, ext, extra)
|
|
f = features(left, right)
|
|
f["duration"] = duration(ctx, data, ext)
|
|
return f
|