ws-audio2: music/ptm (PolyTracker): it family, MOD letters with S3M fine slides, note slides, delta 8 / 16-bit samples; engine flags.panLaw = ft2 (square-root panning)

ops/MusicOps: accept modules of the other tracker formats by their engine family (Tracker.family), a one-line
backward-compatible change.
This commit is contained in:
4DBug committed 2026-10-31 14:29:01 -05:00
1 parent 48b4b4cc4e
commit 60544a3a77
9 files changed
+409 -4

No files matched your search

+1
View File
@@ -78,6 +78,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` |
| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` |
| music | mtm | .mtm | yes | - | render: true, channels: 1, 32 | `tests/music/mtm.luau` |
| music | ptm | .ptm | yes | - | render: true, channels: 1, 32 | `tests/music/ptm.luau` |
| music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` |
| music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` |
| music | stm | .stm | yes | - | render: true, channels: 4, 4 | `tests/music/stm.luau` |
+12
View File
@@ -890,6 +890,18 @@ local list: { Entry } = {
return require("@formats/music/mtm")
end,
},
{
name = "ptm",
category = "music",
path = "music/ptm",
extensions = { "ptm" },
mime = { "audio/x-ptm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/ptm")
end,
},
{
name = "s3m",
category = "music",
@@ -221,6 +221,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any
autoReset = flags.autoReset or false,
st2Tempo = flags.st2Tempo or false,
oktSlides = flags.oktSlides or false,
ft2Pan = flags.panLaw == "ft2",
ord = 0,
row = 0,
tick = 0,
@@ -1905,6 +1906,10 @@ local function updateVoice(st: any, v: any)
local g = vol * st.master
if v.surround then
v.tl, v.tr = g * 0.5, -g * 0.5
elseif st.ft2Pan then
-- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255
local p = min(pan, 255)
v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256)
else
v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256
end
+2 -1
View File
@@ -26,7 +26,8 @@
-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in
-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta),
-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows),
-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo) }
-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo),
-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels) }
-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width,
-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool }
-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels
+224
View File
@@ -0,0 +1,224 @@
--!strict
-- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD
-- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the
-- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx
-- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger,
-- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the
-- byte stream, as PolyTracker stores them), ping-pong loops.
-- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Ptm = {
name = "ptm",
category = "music",
extensions = { "ptm" },
mime = { "audio/x-ptm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
-- PolyTracker's effects past MOD's 0..F
local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" }
-- ------------------------------------------------------------------------------------------------ sniff
local function validHeader(r: Bytes.Reader): boolean
if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then
return false
end
local h = r:sub(32, 10)
local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le()
return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128
end
function Ptm.sniff(r: Bytes.Reader): number
return if validHeader(r) then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values
local function delta16(buf: buffer, off: number, frames: number, limit: number): (buffer, number)
local n = math.max(0, math.min(frames, (limit - off) // 2))
local raw = buffer.create(n * 2)
local acc = 0
for i = 0, n * 2 - 1 do
acc = (acc + buffer.readu8(buf, off + i)) % 256
buffer.writeu8(raw, i, acc)
end
return raw, n
end
function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if not validHeader(r) then
return nil, Err.new(if r:size() < 608 then Err.TRUNCATED else Err.CORRUPT, "not a PolyTracker module")
end
local title = r:fixed(28)
r:skip(1)
local vlo, vhi = r:u8(), r:u8()
r:skip(1)
local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le()
r:seek(64)
local m = Tracker.newModule("ptm", nch, "it")
m.title = title
m.linear = false
m.instrumentMode = false
m.flags.oldEffects, m.flags.compatGxx = true, true
m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels
for i = 1, 32 do
local p = r:u8()
if i <= nch then
m.channelPan[i] = (p % 16) * 16 + 4
end
end
for i = 1, 256 do
local o = r:u8()
if i <= nord then
m.order[i] = o
end
end
local patOff: { number } = {}
for i = 1, 128 do
patOff[i] = r:u16le() * 16
end
if r.err then
return nil, r.err
end
-- samples
local buf = r.buf
for i = 1, nsmp do
local h = r:slice(80)
if r.err then
return nil, r.err
end
local flags = h:u8()
h:skip(12)
local vol, c4 = h:u8(), h:u16le()
h:skip(2)
local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le()
h:skip(14)
local s = Tracker.newSample(h:fixed(28))
m.samples[i] = s
s.volume = math.min(vol, 64)
s.c5speed = math.max(1, c4 * 2)
if flags % 4 == 1 and len > 0 then
local bits = if bit32.band(flags, 0x10) ~= 0 then 16 else 8
if le > ls then
le -= 1
end
local frames = len
if bits == 16 then
frames, ls, le = frames // 2, ls // 2, le // 2
end
local at = r.base + off
if at < r.limit then
local ok, err
if bits == 16 then
local raw, n = delta16(buf, at, frames, r.limit)
ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget)
else
ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget)
end
if not ok then
return nil, err
end
end
if bit32.band(flags, 4) ~= 0 and le > ls then
s.loopStart, s.loopEnd = ls, math.min(le, s.length)
s.loopType = if bit32.band(flags, 8) ~= 0 then 2 else 1
end
end
end
-- patterns (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume)
for p = 1, npat do
local pat = Tracker.newPattern(64, nch)
m.patterns[p] = pat
local d = pat.data
if patOff[p] > 0 and patOff[p] < r:size() then
local pr = r:sub(patOff[p])
local row = 0
while row < 64 and not pr:eof() do
local b = pr:u8()
if b == 0 then
row += 1
else
local ch = b % 32
local q = (row * nch + ch) * 5
local ok = ch < nch
if bit32.band(b, 0x20) ~= 0 then
local note, ins = pr:u8(), pr:u8()
if note == 254 then
note = 254
elseif note == 0 or note > 120 then
note = 0
end
if ok then
buffer.writeu8(d, q, note)
buffer.writeu8(d, q + 1, ins)
end
end
if bit32.band(b, 0x40) ~= 0 then
local cmd, param = pr:u8(), pr:u8()
local name
if cmd < 0x10 then
name, param = Load.modCommand(cmd, param)
else
name = EXTRA[cmd - 0x10 + 1]
end
if name == "panning8" then
name, param = "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16
elseif name == "globalvol" then
param = math.min(param, 0x40) * 2
end
if ok then
if name == "volume" then
if buffer.readu8(d, q + 2) == 0 then
buffer.writeu8(d, q + 2, math.min(param, 64) + 1)
end
else
local fx, fp = Load.itEffect(name, param)
buffer.writeu8(d, q + 3, fx)
buffer.writeu8(d, q + 4, fp)
end
end
end
if bit32.band(b, 0x80) ~= 0 then
local v = pr:u8()
if ok then
buffer.writeu8(d, q + 2, math.min(v, 64) + 1)
end
end
end
end
end
end
m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Ptm.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Ptm
+4 -3
View File
@@ -27,7 +27,8 @@ local function bad(what: string): (nil, Err.Err)
end
local function isModule(m: any): boolean
return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == true and type(m.patterns) == "table"
-- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four)
return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table"
end
local function int(v: any, lo: number, hi: number): boolean
@@ -243,7 +244,7 @@ function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?)
local copy = buffer.create(length * channels * 4)
buffer.copy(copy, 0, data, 0, length * channels * 4)
s.data, s.length, s.channels = copy, length, channels
s.bits = spec.bits or (if m.format == "mod" then 8 else 16)
s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16)
if s.bits ~= 8 and s.bits ~= 16 then
return bad("addSample: bits must be 8 or 16")
end
@@ -298,7 +299,7 @@ function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err
if not isModule(m) then
return bad("addInstrument: needs a tracker Module")
end
if m.format ~= "xm" and m.format ~= "it" then
if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then
return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)")
end
if type(spec) ~= "table" then
+19
View File
@@ -0,0 +1,19 @@
-- music/ptm tests: generated PolyTracker modules (tools/fixtures/ptm.py) parsed, rendered through codecs/audio/Tracker
-- and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract,
-- and the fuzz no-throw pass.
local T = require("@tests/T")
local S = require("@tests/music/_similar")
local Ptm = require("@formats/music/ptm")
local Cases = require("@tests/gen/ptm_cases")
local t = T.suite("ptm")
t:eq(Ptm.name, "ptm", "name")
t:eq(Ptm.category, "music", "category")
t:check(Ptm.caps.decode and not Ptm.caps.encode, "caps")
local mods = S.against(t, Ptm, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "it")
t:check(mods[1] and mods[1].samples[3].bits == 16 and mods[1].samples[3].loopType == 2, "16-bit ping-pong loop")
t:fuzz("decode", S.fuzzer(Ptm), S.samples(Cases), { mutations = 30 })
t:done()
+53
View File
@@ -663,3 +663,56 @@ def write_ult(title, samples, orders, patterns, channels, version=4, pans=None,
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("<HHHHH", len(orders), len(samples), len(patterns), channels, 0) + b"\0\0PTMF" + b"\0" * 16
pp = list(pans or [(i % 2) * 15 for i in range(channels)])
head += bytes(pp + [0] * (32 - len(pp)))
head += bytes(orders) + b"\xff" * (256 - len(orders))
pat_at = len(head)
head += b"\0" * 256
smp_at = len(head)
head += b"\0" * (80 * len(samples))
body = head
for k, pat in enumerate(patterns):
while len(body) % 16:
body.append(0)
struct.pack_into("<H", body, pat_at + 2 * k, len(body) // 16)
for row in pat:
for ch, (note, ins, vol, cmd, param) in enumerate(row):
what = (0x20 if note or ins else 0) | (0x40 if cmd is not None else 0) | (0x80 if vol is not None else 0)
if what:
body.append(what | ch)
if what & 0x20:
body += bytes([note, ins])
if what & 0x40:
body += bytes([cmd, param])
if what & 0x80:
body.append(vol)
body.append(0)
for i, s in enumerate(samples):
bps = 2 if s.get("bits", 8) == 16 else 1
raw = s["data"]
enc, prev = bytearray(), 0
for b in raw:
enc.append((b - prev) & 255)
prev = b
off = len(body)
body += enc
ls, le = s.get("loop") or (0, 0)
fl = 1 | (4 if s.get("loop") else 0) | (8 if s.get("pingpong") else 0) | (16 if bps == 2 else 0)
h = bytearray(80)
h[0] = fl
h[1:13] = name(s.get("name", "")[:8] + ".smp", 12)
h[13] = s.get("volume", 64)
struct.pack_into("<HHIIII", h, 14, s.get("c4spd", 8363), 0, off, len(raw), ls * bps, (le * bps + 1) if s.get("loop") else 0)
h[48:76] = name(s.get("name", ""), 28)
h[76:80] = b"PTMS"
body[smp_at + 80 * i:smp_at + 80 * i + 80] = h
return bytes(body)
+89
View File
@@ -0,0 +1,89 @@
# PTM fixtures (tools/fixtures.py): generated PolyTracker modules exercising the effects, rendered by openmpt123.
# tests/gen/ptm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
# duration (openmpt's song length) }
import os, sys
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
T = sys.modules.get("_tracker")
if T is None:
import importlib.util
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
T = importlib.util.module_from_spec(_spec)
sys.modules["_tracker"] = T
_spec.loader.exec_module(T)
INPUTS = ["tools/fixtures/_tracker.py"]
def empty(ch):
return [[(0, 0, None, None, 0) for _ in range(ch)] for _ in range(64)]
def put(p, row, ch, note=0, ins=0, vol=None, cmd=None, param=0):
p[row][ch] = (note, ins, vol, cmd, param)
def samples():
return [
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c4spd": 8363, "loop": (0, 64)},
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c4spd": 16726, "loop": (0, 64)},
{"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 64, "c4spd": 13000, "loop": (0, 200), "pingpong": True},
{"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c4spd": 8363},
{"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c4spd": 10000, "loop": (0, 50)},
]
def song_effects(keep=None):
a, b = empty(6), empty(6)
mel = [61, 65, 68, 73, 68, 65, 63, 61]
for i in range(16):
put(a, i * 4, 0, mel[i % 8], 1, None, 0x0 if i % 4 == 1 else None, 0x37)
put(a, 0, 1, 49, 2, 48)
put(a, 4, 1, 0, 0, None, 0xA, 0x04)
put(a, 8, 1, 0, 0, None, 0xA, 0x20)
put(a, 12, 1, 0, 0, None, 0xA, 0xF2) # S3M-style fine slide
put(a, 16, 1, 51, 2, None, 0x2, 0x03)
put(a, 20, 1, 0, 0, None, 0x1, 0x06)
put(a, 24, 1, 0, 0, None, 0x1, 0xF4) # fine porta
put(a, 28, 1, 56, 2, None, 0x4, 0x46)
put(a, 36, 1, 0, 0, None, 0x6, 0x02)
put(a, 40, 1, 49, 2)
put(a, 41, 1, 61, 0, None, 0x3, 0x10)
put(a, 44, 1, 0, 0, None, 0x5, 0x01)
put(a, 48, 1, 54, 2, None, 0x7, 0x58)
put(a, 56, 1, 0, 0, None, 0xC, 0x20)
for r in range(0, 64, 8):
put(a, r, 3, 61, 4, 64 - r // 2)
put(a, 20, 3, 61, 4, None, 0x9, 0x08)
put(a, 32, 3, 61, 4, None, 0xE, 0xC3)
put(a, 40, 3, 61, 4, None, 0xE, 0xD2)
put(a, 48, 3, 61, 4, None, 0x11, 0x03) # retrigger
put(a, 4, 2, 37, 3, 50)
put(a, 2, 4, 73, 5, None, 0x8, 0x30) # panning
put(a, 18, 4, 0, 0, None, 0x8, 0xD0)
put(a, 10, 5, 56, 1, None, 0x12, 0x46) # fine vibrato
put(a, 24, 5, 0, 0, None, 0x13, 0x22) # note slide up: every 2 ticks by 2
put(a, 30, 5, 0, 0, None, 0x14, 0x31) # note slide down
put(a, 36, 5, 60, 1, None, 0x15, 0x21) # with retrigger
put(b, 0, 0, 49, 1, None, 0xF, 0x04)
put(b, 4, 0, 0, 0, None, 0xF, 0x90)
put(b, 8, 0, 61, 1, None, 0x10, 0x20) # global volume
put(b, 24, 0, 0, 0, None, 0x10, 0x40)
put(b, 0, 2, 37, 3)
put(b, 16, 2, 0, 0, None, 0xE, 0x92)
put(b, 32, 4, 68, 5, None, 0xD, 0x00)
if keep is not None:
for p in (a, b):
for row in p:
for ch in range(6):
if ch not in keep and row[ch][3] not in (0xD, 0xF, 0x10):
row[ch] = (0, 0, None, None, 0)
return T.write_ptm("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9])
def generate(ctx):
cases = []
for nm, data in (("effects", song_effects()),):
ref = T.reference(ctx, data, "ptm")
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
ctx.emit("ptm_cases", cases)