# 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("= 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("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("> 16 struct.pack_into(" 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("= 128 else b for b in raw] else: vals = [struct.unpack_from("= 8: data.append(acc & 255) acc >>= 8 nbits -= 8 if nbits: data.append(acc & 255) out += struct.pack("> 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 # ---------------------------------------------------------------------------------------------- other trackers # (ws-audio2: MTM, 669, STM, ULT, OKT, MED, PTM, FAR, UMX writers for tools/fixtures/{mtm,669,...}.py) def write_mtm(title, samples, orders, patterns, channels, pans=None, rows=64, comment=b""): """samples: [{name, data (raw unsigned bytes; 16-bit: little-endian unsigned), bits 8|16, volume 0..64, finetune -8..7, loop: (start, end) in bytes | None}]; patterns: [[row: [(note, ins, fx, param)] * channels] * rows] with note 0 = none else our note (1 = C-0; 49 = C-4 plays at 8363 Hz; >= 25)""" tracks, index = [], {} table = [] for pat in patterns: ids = [] for ch in range(32): if ch >= channels: ids.append(0) continue tb = bytearray() for r in range(rows): note, ins, fx, param = pat[r][ch] if r < len(pat) else (0, 0, 0, 0) n = note - 25 if note else 0 tb += bytes([(n << 2) | (ins >> 4), ((ins & 15) << 4) | fx, param]) tb = bytes(tb) + b"\0" * (192 - len(tb)) if not any(tb): ids.append(0) continue if tb not in index: tracks.append(tb) index[tb] = len(tracks) ids.append(index[tb]) table.append(ids) out = bytearray(b"MTM\x10" + name(title, 20)) out += struct.pack("= 37), ins 1-based, vol 0..15 or None, effect byte (cmd << 4 | param) or None; tempos / breaks: per pattern""" out = bytearray(b"JN" if extended else b"if") msg = message.encode()[:108] out += msg + b" " * (108 - len(msg)) out += bytes([len(samples), len(patterns), restart]) out += bytes(orders) + b"\xff" * (128 - len(orders)) out += bytes(tempos) + b"\x04" * (128 - len(tempos)) out += bytes(breaks) + b"\x3f" * (128 - len(breaks)) for s in samples: ls, le = s.get("loop") or (0, 0xFFFFF) out += name(s.get("name", ""), 13) + struct.pack("> 4), ((i & 15) << 4) | (vol if vol is not None else 0)]) elif vol is not None: out += bytes([0xFE, vol]) else: out += b"\xff\x00" out.append(0xFF if eff is None else eff) for s in samples: out += s["data"] return bytes(out) def write_stm(title, samples, orders, patterns, tempo=0x60, gvol=64, minor=21): """samples: [{name, data (signed bytes), volume, c2spd, loop: (start, end) | None}] (up to 31); patterns: [[row: [(note, ins, vol, cmd, info)] * 4] * 64] with note 0 = none, 254 = cut, else our note (>= 37); vol None = none; cmd 0 = none (A = 1, letters as in S3M)""" head = bytearray(name(title, 20) + b"!Scream!" + bytes([0x1A, 2, 2, minor, tempo, len(patterns), gvol]) + b"\0" * 13) smp_at = len(head) head += b"\0" * (31 * 32) head += bytes(orders) + bytes([99] * ((64 if minor == 0 else 128) - len(orders))) for pat in patterns: for row in pat: for (note, ins, vol, cmd, info) in row: if note in ("skip", "fb"): head.append(0xFC if note == "skip" else 0xFB) # nothing / a C-0 at volume 0 continue if note == 254: nb = 0xFE elif note: n = note - 37 nb = (n // 12) << 4 | (n % 12) else: nb = 0xFF v = 65 if vol is None else vol head += bytes([nb, (ins << 3) | (v & 7), ((v >> 3) << 4) | cmd, info]) body = head for i in range(31): h = bytearray(32) if i < len(samples): s = samples[i] while len(body) % 16: body.append(0) off = len(body) // 16 body += s["data"] ls, le = s.get("loop") or (0, 0xFFFF) h[0:12] = name(s.get("name", ""), 12) struct.pack_into("= 4: out += struct.pack("= 3: out += bytes(pans or [(i % 2) * 15 for i in range(channels)]) for ch in range(channels): for pat in patterns: evs = [] for row in pat: note, ins, e1, p1, e2, p2 = row[ch] evs.append(bytes([note - 24 if note else 0, ins, (e2 << 4) | e1, p1, p2])) i = 0 while i < len(evs): j = i while j + 1 < len(evs) and evs[j + 1] == evs[i] and j - i < 250: j += 1 if j > i: out += bytes([0xFC, j - i + 1]) + evs[i] else: out += evs[i] i = j + 1 for s in samples: out += s["data"] return bytes(out) def write_ptm(title, samples, orders, patterns, channels, pans=None): """samples: [{name, data (signed bytes; 16-bit little-endian), bits 8|16, volume, c4spd, loop: (start, end) in frames | None, pingpong}] (stored delta coded: 8-bit deltas of the byte stream, also for 16-bit); patterns: [[row: [(note, ins, vol, cmd, param)] * channels] * 64] with note 0 = none, 254 = cut, else our note (1..120); vol None = none; cmd None = none, else 0..0x16 (MOD effects 0..F, then PolyTracker's G..)""" head = bytearray(name(title, 28) + bytes([26, 3, 2, 0])) head += struct.pack("> 3] |= 1 << (i & 7) body += smap for s in samples: bps = 2 if s.get("bits", 8) == 16 else 1 ls, le = s.get("loop") or (0, 0) body += name(s.get("name", ""), 32) + struct.pack("I", len(data)) + data out = bytearray(b"OKTASONG") out += chunk(b"CMOD", b"".join(struct.pack(">H", c) for c in cmod)) sh = bytearray() for i in range(36): if i < len(samples): s = samples[i] ls, ll = s.get("loop") or (0, 0) sh += name(s.get("name", ""), 20) + struct.pack(">IHHHH", len(s["data"]), ls // 2, ll // 2, s.get("volume", 64), s.get("type", 2)) else: sh += b"\0" * 32 out += chunk(b"SAMP", bytes(sh)) out += chunk(b"SPEE", struct.pack(">H", speed)) out += chunk(b"SLEN", struct.pack(">H", len(patterns))) out += chunk(b"PLEN", struct.pack(">H", len(orders))) out += chunk(b"PATT", bytes(orders) + b"\0" * (128 - len(orders))) for pat in patterns: pb = bytearray(struct.pack(">H", len(pat))) for row in pat: for (note, ins, fx, param) in row: pb += bytes([note, max(0, ins - 1), fx, param]) out += chunk(b"PBOD", bytes(pb)) for s in samples: out += chunk(b"SBOD", s["data"]) return bytes(out) def write_med(version, samples, blocks, sequence, tempo=125, tempo2=6, flags=0, flags2=0, trackvols=None, pans=None, master=64, play_transpose=0, sections=None, title=None): """an MMD0 .. MMD3 module. samples: [{data (signed 8-bit bytes, or big-endian 16-bit with bits 16), bits, volume, transpose, loop: (start, length) in bytes (even) | None, hold, decay, finetune, octaves (IFF multi-octave count: data holds the octaves from the lowest, each twice as long)}]; blocks: [[row: [(note, ins, cmd, param)] * tracks] * rows] with note 0 = none else the MED note (1 = C-1; MMD1+: 0x80 = note off); sequence: block numbers (MMD0 / 1) or the play sequence (MMD2 / 3; sections: [[playseq numbers]] and playseqs = [sequence])""" out = bytearray(52) song_at = 52 out += b"\0" * (63 * 8 + 284) need_ext = any(s.get("hold") or s.get("finetune") for s in samples) or title is not None def align(): while len(out) % 4: out.append(0) # blocks block_ptrs = [] for blk in blocks: align() block_ptrs.append(len(out)) ntr = len(blk[0]) if version == 0: out += bytes([ntr, len(blk) - 1]) else: out += struct.pack(">HHI", ntr, len(blk) - 1, 0) for row in blk: for (note, ins, cmd, param) in row: if version == 0: out += bytes([(note & 0x3F) | ((ins & 0x10) << 3) | ((ins & 0x20) << 1), ((ins & 15) << 4) | (cmd & 15), param]) else: out += bytes([note, ins & 0x3F, cmd, param]) align() block_arr = len(out) for p in block_ptrs: out += struct.pack(">I", p) # instruments inst_ptrs = [] for s in samples: align() inst_ptrs.append(len(out)) oct_ = s.get("octaves", 1) typ = {1: 0, 5: 1, 3: 2, 2: 3, 4: 4, 6: 5, 7: 6}[oct_] | (0x10 if s.get("bits", 8) == 16 else 0) out += struct.pack(">Ih", len(s["data"]), typ) + s["data"] align() smp_arr = len(out) for p in inst_ptrs: out += struct.pack(">I", p) # play sequences (MMD2 / 3) seq_info = None if version >= 2: align() psq = [] for sq in [sequence]: psq.append(len(out)) out += name("seq", 32) + struct.pack(">IIH", 0, 0, len(sq)) + b"".join(struct.pack(">H", b) for b in sq) align() ps_table = len(out) for p in psq: out += struct.pack(">I", p) sec_table = len(out) secs = sections or [0] for sc in secs: out += struct.pack(">H", sc) align() tv = len(out) out += bytes(trackvols or [64] * len(blocks[0][0])) tp = 0 if pans: tp = len(out) out += bytes([p & 255 for p in pans]) seq_info = (ps_table, sec_table, tv, tp, len(secs)) # expansion: instrument extras + song name exp = 0 if need_ext: align() ie = len(out) for s in samples: ls, ll = s.get("loop") or (0, 0) out += struct.pack(">BBBbBBHBBIIBBH", s.get("hold", 0), s.get("decay", 0), 0, s.get("finetune", 0), 0, 1 if s.get("loop") else 0, 0, 0, 0, ls, ll, 127, 0, 0) nm = (title or "").encode() + b"\0" na = len(out) out += nm align() exp = len(out) e = bytearray(80) struct.pack_into(">IIHH", e, 0, 0, ie, len(samples), 22) struct.pack_into(">II", e, 44, na, len(nm)) out += e # the song header for i, s in enumerate(samples): ls, ll = s.get("loop") or (0, 0) struct.pack_into(">HHBBBb", out, song_at + 8 * i, ls // 2, ll // 2, 0, 0, s.get("volume", 64), s.get("transpose", 0)) sh = song_at + 63 * 8 if version < 2: struct.pack_into(">HH", out, sh, len(blocks), len(sequence)) out[sh + 4:sh + 4 + len(sequence)] = bytes(sequence) else: ps_table, sec_table, tv, tp, nsec = seq_info struct.pack_into(">HH", out, sh, len(blocks), nsec) struct.pack_into(">IIIHHIIHH", out, sh + 4, ps_table, sec_table, tv, len(blocks[0][0]), 1, tp, 0, 100, 0) struct.pack_into(">HbBBB", out, sh + 260, tempo, play_transpose, flags, flags2, tempo2) out[sh + 266:sh + 282] = bytes((trackvols or [64] * 16)[:16]) + bytes(max(0, 16 - len(trackvols or [0] * 16))) out[sh + 282] = master out[sh + 283] = len(samples) hdr = bytearray(b"MMD" + bytes([0x30 + version])) hdr += struct.pack(">IIHHIB3sIIII11sB", len(out), song_at, 0, 0, block_arr, 0, b"\0\0\0", smp_arr, 0, exp, 0, b"\0" * 11, 0) out[0:52] = hdr return bytes(out) def umx_index(v): """an Unreal compact index""" neg, v = v < 0, abs(v) out = bytearray([(0x80 if neg else 0) | (v & 0x3F) | (0x40 if v > 0x3F else 0)]) v >>= 6 while v: out.append((v & 0x7F) | (0x80 if v > 0x7F else 0)) v >>= 7 return bytes(out) def write_umx(modules, version=69): """an Unreal package (UT99-era, package version 61..99) whose exports are Music objects: modules = [(object name, module bytes)]""" names = ["None", "Music", "Core", "Class"] + [n for n, _ in modules] out = bytearray(36) name_at = len(out) for n in names: b = n.encode() + b"\0" out += (umx_index(len(b)) if version >= 64 else b"") + b + struct.pack("