From 4c1f5a9987312ea43bbe9ab2e16f57ff402ede6f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:47:40 -0500 Subject: [PATCH] ws-music: codecs/Tracker engine (player, mixer, pcm, tables) + music/mod read/write/render, tested against openmpt123 --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/codecs/Tracker/Mixer.luau | 173 +++ src/Formats/codecs/Tracker/Pcm.luau | 132 ++ src/Formats/codecs/Tracker/Player.luau | 1837 ++++++++++++++++++++++++ src/Formats/codecs/Tracker/Tables.luau | 113 ++ src/Formats/codecs/Tracker/init.luau | 513 +++++++ src/Formats/music/mod/init.luau | 361 +++++ tests/music/_similar.luau | 201 +++ tests/music/mod.luau | 77 + tools/fixtures/_tracker.py | 495 +++++++ tools/fixtures/mod.py | 104 ++ 12 files changed, 4020 insertions(+) create mode 100644 src/Formats/codecs/Tracker/Mixer.luau create mode 100644 src/Formats/codecs/Tracker/Pcm.luau create mode 100644 src/Formats/codecs/Tracker/Player.luau create mode 100644 src/Formats/codecs/Tracker/Tables.luau create mode 100644 src/Formats/codecs/Tracker/init.luau create mode 100644 src/Formats/music/mod/init.luau create mode 100644 tests/music/_similar.luau create mode 100644 tests/music/mod.luau create mode 100644 tools/fixtures/_tracker.py create mode 100644 tools/fixtures/mod.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..e815f98 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,7 +6,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..d245f17 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "mod", + category = "music", + path = "music/mod", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/mod") + end, + }, } return list diff --git a/src/Formats/codecs/Tracker/Mixer.luau b/src/Formats/codecs/Tracker/Mixer.luau new file mode 100644 index 0000000..193a034 --- /dev/null +++ b/src/Formats/codecs/Tracker/Mixer.luau @@ -0,0 +1,173 @@ +--!strict +--!native +-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample +-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole +-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code). +-- +-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker) +-- validates the sample buffers' sizes. +local floor, ceil, min = math.floor, math.ceil, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local Mixer = {} + +-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) +local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) + local data: buffer = v.data + local nch = v.nch + local inc = v.inc + if not (inc > 0 and inc < 1e6) then + return + end + local len = v.len + local hi = len - 1 + local i = 0 + local guard = 0 + while i < n do + guard += 1 + if guard > n + 64 then + return + end + local s, e, t + if v.keyOn and v.susT > 0 then + s, e, t = v.susS, v.susE, v.susT + elseif v.loopT > 0 then + s, e, t = v.loopS, v.loopE, v.loopT + else + s, e, t = 0, len, 0 + end + local p = v.p + local dir = v.dir + local count + if dir > 0 then + local lim = if t == 2 then e - 1 else e + if p >= lim then + if t == 0 then + v.active = false + return + elseif t == 1 then + p = s + (p - e) % (e - s) + else + p = 2 * (e - 1) - p + if p < s then + p = s + end + v.dir = -1 + end + v.p = p + continue + end + count = ceil((lim - p) / inc) + else + if p < s then + p = 2 * s - p + if p > e - 1 then + p = e - 1 + end + v.p = p + v.dir = 1 + continue + end + count = floor((p - s) / inc) + 1 + end + if count < 1 then + count = 1 + end + local m = min(n - i, count) + local step = inc * dir + if out == nil then + v.p = p + step * m + i += m + continue + end + local wrapJ = if t == 1 then s else e - 1 + local gl, gr = v.gl, v.gr + local rl = v.rampN + local dl, dr = 0, 0 + local tl, tr = v.tl, v.tr + if rl > 0 then + dl, dr = (tl - gl) / rl, (tr - gr) / rl + end + local fOn = v.fOn + local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 + local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r + local o = (off + i) * 8 + for _ = 1, m do + local idx = floor(p) + if idx > hi then + idx = hi + elseif idx < 0 then + idx = 0 + end + local j = idx + 1 + if j >= e then + j = wrapJ + end + if j > hi then + j = hi + end + local xl, xr + if nch == 1 then + local a = readf32(data, idx * 4) + if linear then + local b = readf32(data, j * 4) + xl = a + (b - a) * (p - idx) + else + xl = a + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + end + xr = xl + else + local al = readf32(data, idx * 8) + local ar = readf32(data, idx * 8 + 4) + if linear then + local f = p - idx + xl = al + (readf32(data, j * 8) - al) * f + xr = ar + (readf32(data, j * 8 + 4) - ar) * f + else + xl, xr = al, ar + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + y = xr * fa + y1r * fb0 + y2r * fb1 + y2r, y1r = y1r, y + xr = y + end + end + if rl > 0 then + gl += dl + gr += dr + rl -= 1 + if rl == 0 then + gl, gr = tl, tr + end + end + writef32(out, o, readf32(out, o) + xl * gl) + writef32(out, o + 4, readf32(out, o + 4) + xr * gr) + o += 8 + p += step + end + v.p = p + v.gl, v.gr, v.rampN = gl, gr, rl + v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r + i += m + end + local _ = ramp +end + +-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions +function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) + for _, v in st.voices do + if v.active and v.data then + mixVoice(v, out, off, n, linear, 0) + end + end +end + +return Mixer diff --git a/src/Formats/codecs/Tracker/Pcm.luau b/src/Formats/codecs/Tracker/Pcm.luau new file mode 100644 index 0000000..30c59c8 --- /dev/null +++ b/src/Formats/codecs/Tracker/Pcm.luau @@ -0,0 +1,132 @@ +--!strict +--!native +-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, +-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back. +-- +-- Never throws: reads past the source are refused up front (decode returns nil). +local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 +local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 +local floor = math.floor + +local Pcm = {} + +export type Spec = { + bits: number, -- 8 | 16 + signed: boolean, + delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) + channels: number?, -- 1 (default) | 2 + planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved + bigEndian: boolean?, +} + +-- bytes(frames, spec) -> the size of the raw data +function Pcm.bytes(frames: number, spec: Spec): number + return frames * (spec.channels or 1) * (spec.bits // 8) +end + +-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short +function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local total = frames * nch + if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then + return nil + end + local out = buffer.create(total * 4) + local planar = spec.planar and nch == 2 + for c = 0, nch - 1 do + local acc = 0 + for i = 0, frames - 1 do + local k = if planar then c * frames + i else i * nch + c + local v + if bps == 1 then + if spec.signed then + v = readi8(buf, off + k) + else + v = readu8(buf, off + k) - 128 + end + if spec.delta then + acc = (acc + v + 128) % 256 - 128 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 128) + else + local p = off + k * 2 + if spec.bigEndian then + v = readu8(buf, p) * 256 + readu8(buf, p + 1) + if spec.signed and v >= 32768 then + v -= 65536 + end + elseif spec.signed then + v = readi16(buf, p) + else + v = readu16(buf, p) + end + if not spec.signed then + v -= 32768 + end + if spec.delta then + acc = (acc + v + 32768) % 65536 - 32768 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 32768) + end + end + end + return out +end + +-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) +function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local out = buffer.create(frames * nch * bps) + local planar = spec.planar and nch == 2 + local avail = buffer.len(samples) // 4 + for c = 0, nch - 1 do + local prev = 0 + for i = 0, frames - 1 do + local si = i * nch + c + local x = if si < avail then readf32(samples, si * 4) else 0 + local k = if planar then c * frames + i else i * nch + c + if bps == 1 then + local v = math.clamp(floor(x * 128 + 0.5), -128, 127) + local w = v + if spec.delta then + w = (v - prev) % 256 + prev = v + else + w = if spec.signed then v % 256 else v + 128 + end + writeu8(out, k, w) + else + local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) + local w = v + if spec.delta then + w = (v - prev + 32768) % 65536 - 32768 + prev = v + elseif not spec.signed then + w = v + 32768 + if w >= 32768 then + w -= 65536 + end + end + writei16(out, k * 2, w) + end + end + end + return out +end + +-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 +function Pcm.bitsNeeded(samples: buffer): number + for i = 0, buffer.len(samples) // 4 - 1 do + local x = readf32(samples, i * 4) * 128 + if x ~= floor(x) then + return 16 + end + end + return 8 +end + +return Pcm diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau new file mode 100644 index 0000000..df4350b --- /dev/null +++ b/src/Formats/codecs/Tracker/Player.luau @@ -0,0 +1,1837 @@ +--!strict +--!native +-- codecs/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, +-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric +-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes, +-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song +-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, +-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/Tracker/Mixer. +-- +-- Never throws: the module is validated by codecs/Tracker before a player is made, and every table lookup here is +-- guarded. +local Tables = require("@formats/codecs/Tracker/Tables") + +local wave64, autoWave = Tables.wave64, Tables.autoWave +local AMIGA = Tables.AMIGA +local AMIGA_PAL = Tables.AMIGA_PAL +local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs +local readu8 = buffer.readu8 + +local Player = {} + +local MOD, S3M, XM, IT = 1, 2, 3, 4 +Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT +local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } + +local MAX_VOICES = 96 -- channels + IT background voices + +-- ------------------------------------------------------------------------------------------------ state +local function newVoice(): any + return { + active = false, + chan = 0, + bg = false, + data = nil :: buffer?, + nch = 1, + len = 0, + loopS = 0, + loopE = 0, + loopT = 0, + susS = 0, + susE = 0, + susT = 0, + p = 0, + dir = 1, + inc = 0, + smp = nil :: any, + smpIdx = 0, + ins = nil :: any, + insIdx = 0, + note = 0, + vol = 0, + pan = 128, + chanVol = 64, + period = 0, + periodOut = 0, + base = 8363, + keyOn = true, + fading = false, + fade = 65536, + volEnvPos = 0, + panEnvPos = 0, + pitchEnvPos = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + envVol = 64, + envPan = 0, + envPitch = 0, + avPos = 0, + avAmp = 0, + gl = 0, + gr = 0, + tl = 0, + tr = 0, + started = false, + cutoff = 127, + reso = 0, + fOn = false, + fa = 1, + fb0 = 0, + fb1 = 0, + y1l = 0, + y2l = 0, + y1r = 0, + y2r = 0, + tremorMute = false, + surround = false, + rampN = 0, + order = 0, -- allocation age + } +end + +local function newChannel(i: number, pan: number, vol: number): any + return { + idx = i, + voice = nil :: any, + note = 0, + realNote = 0, + insIdx = 0, + smpIdx = 0, + smp = nil :: any, + vol = 0, + pan = pan, + chanVol = vol, + period = 0, + target = 0, + portaSpeed = 0, + base = 8363, + finetune = nil :: number?, + fx = 0, + param = 0, + vcmd = 0, + -- memories + mPortaUp = 0, + mPortaDn = 0, + mFineUp = 0, + mFineDn = 0, + mXFineUp = 0, + mXFineDn = 0, + mVolSlide = 0, + mFineVolUp = 0, + mFineVolDn = 0, + mOffset = 0, + mHighOffset = 0, + mPanSlide = 0, + mGVolSlide = 0, + mRetrig = 0, + mTremor = 0, + mArp = 0, + mS3M = 0, + mEF = 0, + mChanVolSlide = 0, + mTempo = 0, + mVolCol = 0, + mS = 0, + vibSpeed = 0, + vibDepth = 0, + vibPos = 0, + vibWave = 0, + tremSpeed = 0, + tremDepth = 0, + tremPos = 0, + tremWave = 0, + panbSpeed = 0, + panbDepth = 0, + panbPos = 0, + panbWave = 0, + vibDelta = 0, + tremDelta = 0, + panbDelta = 0, + arp = 0, + loopRow = 0, + loopCount = 0, + retrigCount = 0, + tremorCount = 0, + tremorOn = true, + delayTick = -1, + dNote = 0, + dIns = 0, + dVol = 0, + cutTick = -1, + keyOffTick = -1, + nna = -1, + surround = false, + cutoff = 127, + reso = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + muted = false, + triggered = false, + } +end + +-- new(module, opts) -> player state (module validated by the caller) +function Player.new(m: any, sampleRate: number, opts: any): any + local fmt = FAMILY[m.format] or MOD + local st: any = { + m = m, + fmt = fmt, + sr = sampleRate, + nch = m.channels, + speed = m.speed, + tempo = m.tempo, + gvol = m.globalVolume, + linear = m.linear, + insMode = m.instrumentMode and #m.instruments > 0, + oldFx = m.flags.oldEffects or false, + compatG = m.flags.compatGxx or false, + fastSlides = m.flags.fastSlides or false, + amigaLimits = m.flags.amigaLimits or false, + ord = 0, + row = 0, + tick = 0, + pat = nil :: any, + patIdx = -1, + patDelay = 0, + patDelayRep = 0, + fineDelay = 0, + jumpOrd = -1, + breakRow = -1, + loopJump = -1, + ended = false, + visited = {} :: { [number]: boolean }, + chans = {}, + voices = {}, + age = 0, + tickFrames = 0, + frac = 0, + separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), + master = 1, + rows = 0, + ramp = 64, + amiga = if fmt == MOD then AMIGA_PAL else AMIGA, + loopAllowed = opts and opts.loop or false, + } + for i = 1, m.channels do + local pan = m.channelPan[i] or 128 + local cv = m.channelVolume[i] or 64 + local c = newChannel(i, pan, cv) + c.muted = m.channelMute[i] or false + if pan == 512 then -- surround marker + c.pan = 128 + c.surround = true + end + st.chans[i] = c + end + for i = 1, MAX_VOICES do + st.voices[i] = newVoice() + end + st.master = Player.masterGain(m, fmt) + Player.startOrder(st, 0, 0) + return st +end + +-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at +-- volume 64 on one centred channel) +function Player.masterGain(m: any, fmt: number): number + if fmt == IT then + return 0.5 * (m.mixVolume or 48) / 48 + elseif fmt == S3M then + return 0.5 * (m.mixVolume or 48) / 48 + end + -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) + return 2 / clamp(m.channels, 2, 8) +end + +-- ------------------------------------------------------------------------------------------------ orders and rows +-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended +function Player.startOrder(st: any, ord: number, row: number) + local m = st.m + local order = m.order + local n = #order + local guard = 0 + local o = ord + while true do + guard += 1 + if guard > n + 2 then + st.ended = true + return + end + if o >= n then + o = m.restart or 0 + if o >= n or o < 0 then + o = 0 + end + if n == 0 then + st.ended = true + return + end + end + local p = order[o + 1] + if p == 255 then + o = n -- the end marker: wrap to the restart position + elseif p == 254 or m.patterns[p + 1] == nil then + o += 1 + else + st.ord = o + st.patIdx = p + st.pat = m.patterns[p + 1] + st.row = if row < st.pat.rows then row else 0 + return + end + end +end + +local function advanceRow(st: any) + if st.stopAfterRow then + st.ended = true + return + end + local loopRow = st.loopJump + if st.jumpOrd >= 0 or st.breakRow >= 0 then + local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 + local r = if st.breakRow >= 0 then st.breakRow else 0 + st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + Player.startOrder(st, o, r) + return + end + if loopRow >= 0 then + st.loopJump = -1 + -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check + for r = loopRow, st.row do + st.visited[st.ord * 1024 + r] = nil + end + st.row = loopRow + return + end + st.row += 1 + if st.row >= st.pat.rows then + Player.startOrder(st, st.ord + 1, 0) + end +end + +-- ------------------------------------------------------------------------------------------------ pitch +-- the period of a note for a sample (see codecs/Tracker for the two period spaces) +local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number) + local base, ref, tr + if st.fmt == MOD or st.fmt == XM then + base, ref = 8363, 49 + tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 + else + base, ref, tr = smp.c5speed or 8363, 61, 0 + if base <= 0 then + base = 8363 + end + end + local plin = (ref - note) * 64 - tr + if st.fmt == MOD then + -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) + local ftp = (ft or smp.finetune or 0) / 16 + return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base + end + if st.linear then + return plin, base + end + return 1712 * 8363 / base * 2 ^ (plin / 768), base +end + +local function arpPeriod(st: any, period: number, semis: number): number + if semis == 0 then + return period + end + if st.linear then + return period - semis * 64 + end + return period * 2 ^ (-semis / 12) +end + +local function clampPeriod(st: any, c: any) + if st.linear then + c.period = clamp(c.period, -6000, 6000) + elseif st.amigaLimits then + c.period = clamp(c.period, 113 * 4, 856 * 4) + else + c.period = clamp(c.period, 1, 1e6) + end +end + +-- ------------------------------------------------------------------------------------------------ voices +local function allocVoice(st: any): any + local best, bestScore = nil, math.huge + for _, v in st.voices do + if not v.active then + return v + end + if v.bg then + local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 + if s < bestScore then + best, bestScore = v, s + end + end + end + if best then + best.active = false + return best + end + return st.voices[1] -- unreachable while MAX_VOICES > channels: every channel holds one foreground voice +end + +local function keyOff(st: any, v: any) + if not v or not v.active then + return + end + v.keyOn = false + local ins = v.ins + if st.fmt == XM then + if not (ins and ins.volEnv and ins.volEnv.enabled) then + v.vol = 0 + local c = st.chans[v.chan] + if c and c.voice == v then + c.vol = 0 + end + else + v.fading = true + end + elseif st.fmt == IT then + if ins then + local env = ins.volEnv + if not (env and env.enabled and v.volEnvOn) or env.loop then + v.fading = true + end + end + end +end + +local function noteFade(v: any) + if v and v.active then + v.fading = true + end +end + +local function cutVoice(v: any) + if v then + v.active = false + end +end + +-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c +local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: boolean) + local v = c.voice + if v == nil or v.bg then + v = allocVoice(st) + c.voice = v + end + local wasActive = v.active + v.active = smp.length > 0 and smp.data ~= nil + v.chan = c.idx + v.bg = false + v.smp = smp + v.smpIdx = smpIdx + v.data = smp.data + v.nch = smp.channels or 1 + v.len = smp.length + v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType + v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 + v.p = 0 + v.dir = 1 + v.ins = ins + v.insIdx = insIdx + v.note = note + v.period = period + v.periodOut = period + v.base = base + st.age += 1 + v.order = st.age + if not keepEnv then + v.keyOn = true + v.fading = false + v.fade = 65536 + v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 + v.avPos, v.avAmp = 0, 0 + v.envVol, v.envPan, v.envPitch = 64, 0, 0 + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 + end + if not wasActive then + v.gl, v.gr = 0, 0 + end + return v +end + +-- IT new note actions on the channel's current voice (and duplicate checks on all its voices) +local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) + -- duplicate check: voices of this channel playing the same instrument + if ins and ins.dct and ins.dct > 0 then + for _, u in st.voices do + if u.active and u.chan == c.idx and u.insIdx == insIdx then + local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 + if dup then + local a = ins.dca or 0 + if a == 0 then + cutVoice(u) + elseif a == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + end + end + local v = c.voice + if v == nil or not v.active then + return + end + local nna = c.nna + if nna < 0 then + nna = if v.ins then (v.ins.nna or 0) else 0 + end + if nna == 0 then + -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) + v.active = false + return + end + v.bg = true + c.voice = nil + if nna == 2 then + keyOff(st, v) + elseif nna == 3 then + noteFade(v) + end +end + +-- ------------------------------------------------------------------------------------------------ triggering +local function isPorta(st: any, fx: number, vcmd: number): boolean + local f = st.fmt + if f == MOD then + return fx == 3 or fx == 5 + elseif f == XM then + return fx == 3 or fx == 5 or (vcmd >= 0xF0) + end + -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) + return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) +end + +-- the sample and real note for an instrument number + note +local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) + local m = st.m + if st.insMode then + local ins = m.instruments[insIdx] + if not ins or note < 1 or note > 120 then + return nil, 0, ins, note + end + local si = ins.sampleMap[note] or 0 + local rn = ins.noteMap[note] or note + local smp = m.samples[si] + return smp, si, ins, rn + end + local smp = m.samples[insIdx] + return smp, insIdx, nil, note +end + +local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) + if smp then + c.vol = smp.volume + if smp.pan then + c.pan = smp.pan + c.surround = false + end + end + if ins and st.fmt == IT then + if ins.pan and not (smp and smp.pan) then + c.pan = ins.pan + c.surround = false + end + if ins.cutoff then + c.cutoff = ins.cutoff + end + if ins.resonance then + c.reso = ins.resonance + end + end +end + +local function sampleOffset(st: any, c: any, v: any) + local f = st.fmt + local fx, param = c.fx, c.param + local off = -1 + if (f == MOD or f == XM) and fx == 9 then + if param > 0 then + c.mOffset = param + end + off = (if f == XM then c.mOffset else param) * 256 + elseif (f == S3M or f == IT) and fx == 15 then + if param > 0 then + c.mOffset = param + end + off = c.mOffset * 256 + (if f == IT then c.mHighOffset * 65536 else 0) + end + if off > 0 and v and v.active then + if off >= v.len then + if v.loopT > 0 and f ~= MOD then + off = v.loopS + elseif f == MOD and v.loopT > 0 then + off = v.loopS + else + v.active = false + return + end + end + v.p = off + end +end + +-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell +local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) + local f = st.fmt + local m = st.m + local porta = isPorta(st, c.fx, vcmd) + local hasNote = note >= 1 and note <= 120 + if insIdx > 0 then + local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil + if valid then + local prev = c.insIdx + c.insIdx = insIdx + local n = if hasNote then note else c.note + local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) + setInstrumentDefaults(st, c, smp, ins) + if not hasNote then + local v = c.voice + if f == XM and v and v.active and (prev == insIdx) then + -- an instrument number alone restarts the envelopes (FT2) + v.keyOn, v.fading, v.fade = true, false, 65536 + v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 + elseif (f == MOD or f == S3M) and smp then + c.smp, c.smpIdx = smp, insIdx + end + end + elseif f == XM and hasNote then + -- an empty instrument: the note stops the channel + c.insIdx = insIdx + if c.voice then + c.voice.active = false + end + hasNote = false + end + end + if hasNote then + local useIns = c.insIdx + local smp, smpIdx, ins, realNote = resolve(st, useIns, note) + if smp == nil then + if (f == MOD or f == S3M) and c.smp then + smp, smpIdx = c.smp, c.smpIdx + end + end + if smp then + local ft = c.finetune + local period, base = notePeriod(st, realNote, smp, ft) + local v = c.voice + if porta and v and v.active then + c.target = period + if st.fmt == IT or st.fmt == S3M then + c.note = note + end + else + if f == IT and st.insMode then + newNoteAction(st, c, ins, useIns, realNote, smpIdx) + end + local keep = f == XM and insIdx == 0 and c.voice ~= nil + c.triggered = true + c.retrigCount = 0 + v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + c.period, c.target, c.base = period, period, base + c.note, c.realNote = note, realNote + c.smp, c.smpIdx = smp, smpIdx + if insIdx > 0 or f == MOD or f == S3M then + -- volume was set by the instrument; MOD / S3M keep the channel volume + end + if c.vibWave < 4 then + c.vibPos = 0 + end + if c.tremWave < 4 then + c.tremPos = 0 + end + v.cutoff, v.reso = c.cutoff, c.reso + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + c.nna = -1 + sampleOffset(st, c, v) + end + elseif f == IT or f == XM then + -- a note mapped to no sample cuts + if c.voice and not porta then + if f == IT and st.insMode then + newNoteAction(st, c, nil, 0, note, 0) + end + if c.voice then + c.voice.active = false + end + end + end + elseif note == 255 then + if f == S3M or f == MOD then + cutVoice(c.voice) + elseif c.voice then + keyOff(st, c.voice) + end + elseif note == 254 then + cutVoice(c.voice) + if f ~= IT then + c.vol = 0 + end + elseif note == 253 then + noteFade(c.voice) + end + -- the volume column's set-volume / set-panning parts (the rest runs with the effects) + if vcmd > 0 then + if f == S3M then + c.vol = min(vcmd - 1, 64) + elseif f == XM then + if vcmd >= 0x10 and vcmd <= 0x50 then + c.vol = vcmd - 0x10 + elseif vcmd >= 0xC0 and vcmd <= 0xCF then + c.pan = (vcmd - 0xC0) * 16 + end + elseif f == IT then + local v = vcmd - 1 + if v <= 64 then + c.vol = v + elseif v >= 128 and v <= 192 then + c.pan = (v - 128) * 4 + c.surround = false + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ effect helpers +local function volSlideMod(c: any, param: number) + local x, y = param // 16, param % 16 + if x > 0 then + c.vol = min(64, c.vol + x) + else + c.vol = max(0, c.vol - y) + end +end + +local function tonePorta(st: any, c: any, speed: number) + if c.target == 0 or c.period == c.target then + return + end + if c.period < c.target then + c.period = min(c.period + speed, c.target) + else + c.period = max(c.period - speed, c.target) + end +end + +local function vibrato(st: any, c: any, scale: number) + c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale + c.vibPos = (c.vibPos + c.vibSpeed) % 64 +end + +local function tremolo(c: any, scale: number) + c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) + c.tremPos = (c.tremPos + c.tremSpeed) % 64 +end + +local function retrigVoice(st: any, c: any) + local v = c.voice + if v and v.smp then + v.active = v.smp.length > 0 + v.p = 0 + v.dir = 1 + end +end + +local function retrigVolume(c: any, x: number) + if x == 0 or x == 8 then + return + end + local mul = Tables.RETRIG_MUL[x + 1] + if mul ~= 1 then + c.vol = floor(c.vol * mul) + else + c.vol += Tables.RETRIG_ADD[x + 1] + end + c.vol = clamp(c.vol, 0, 64) +end + +-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; +-- fast: normal parts on tick 0 too) +local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number + local x, y = param // 16, param % 16 + if y == 0xF and x > 0 then + if tick == 0 then + return min(hi, value + x) + end + return value + elseif x == 0xF and y > 0 then + if tick == 0 then + return max(0, value - y) + end + return value + end + if tick == 0 and not fast then + return value + end + if y == 0 then + return min(hi, value + x) + elseif x == 0 then + return max(0, value - y) + end + return value +end + +-- ------------------------------------------------------------------------------------------------ MOD / XM effects +local function fxModXm(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local xm = st.fmt == XM + local x, y = param // 16, param % 16 + if fx == 0 then + if param ~= 0 then + local k = tick % 3 + c.arp = if k == 1 then x elseif k == 2 then y else 0 + end + elseif fx == 1 then + if xm and param > 0 then + c.mPortaUp = param + end + if tick > 0 then + c.period -= (if xm then c.mPortaUp else param) * 4 + clampPeriod(st, c) + end + elseif fx == 2 then + if xm and param > 0 then + c.mPortaDn = param + end + if tick > 0 then + c.period += (if xm then c.mPortaDn else param) * 4 + clampPeriod(st, c) + end + elseif fx == 3 or fx == 5 then + if fx == 3 and param > 0 then + c.portaSpeed = param + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif fx == 4 or fx == 6 then + if fx == 4 then + if x > 0 then + c.vibSpeed = x + end + if y > 0 then + c.vibDepth = y + end + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif fx == 7 then + if x > 0 then + c.tremSpeed = x + end + if y > 0 then + c.tremDepth = y + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 8 then + if tick == 0 then + c.pan = param + c.surround = false + end + elseif fx == 0xB then + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 0xC then + if tick == 0 then + c.vol = min(param, 64) + end + elseif fx == 0xD then + if tick == 0 then + local r = x * 10 + y + if r > 63 then + r = 0 + end + st.breakRow = r + end + elseif fx == 0xE then + if x == 1 then + if xm and y > 0 then + c.mFineUp = y + end + if tick == 0 then + c.period -= (if xm then c.mFineUp else y) * 4 + clampPeriod(st, c) + end + elseif x == 2 then + if xm and y > 0 then + c.mFineDn = y + end + if tick == 0 then + c.period += (if xm then c.mFineDn else y) * 4 + clampPeriod(st, c) + end + elseif x == 4 then + c.vibWave = y % 8 + elseif x == 6 then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + end + end + end + elseif x == 7 then + c.tremWave = y % 8 + elseif x == 8 then + if tick == 0 and not xm then + c.pan = y * 17 + c.surround = false + end + elseif x == 9 then + if y > 0 and tick > 0 and tick % y == 0 then + retrigVoice(st, c) + end + elseif x == 0xA then + if xm and y > 0 then + c.mFineVolUp = y + end + if tick == 0 then + c.vol = min(64, c.vol + (if xm then c.mFineVolUp else y)) + end + elseif x == 0xB then + if xm and y > 0 then + c.mFineVolDn = y + end + if tick == 0 then + c.vol = max(0, c.vol - (if xm then c.mFineVolDn else y)) + end + elseif x == 0xC then + if tick == y then + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 0xF then + if tick == 0 then + if param == 0 then + if not xm then + st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) + end + elseif param < 32 then + st.speed = param + else + st.tempo = param + end + end + elseif fx == 16 then -- G + if tick == 0 then + st.gvol = min(param, 64) * 2 + end + elseif fx == 17 then -- H + if param > 0 then + c.mGVolSlide = param + end + if tick > 0 then + local p = c.mGVolSlide + local px, py = p // 16, p % 16 + if px > 0 then + st.gvol = min(128, st.gvol + px * 2) + else + st.gvol = max(0, st.gvol - py * 2) + end + end + elseif fx == 20 then -- K + if tick == param then + keyOff(st, c.voice) + end + elseif fx == 21 then -- L + if tick == 0 and c.voice then + c.voice.volEnvPos = param + c.voice.panEnvPos = param + end + elseif fx == 25 then -- P + if param > 0 then + c.mPanSlide = param + end + if tick > 0 then + local p = c.mPanSlide + local px, py = p // 16, p % 16 + if px > 0 then + c.pan = min(255, c.pan + px) + else + c.pan = max(0, c.pan - py) + end + end + elseif fx == 27 then -- R + if x > 0 then + c.mRetrig = c.mRetrig % 16 + x * 16 + end + if y > 0 then + c.mRetrig = (c.mRetrig // 16) * 16 + y + end + local interval = c.mRetrig % 16 + if tick == 0 and c.triggered then + c.retrigCount = 0 + else + c.retrigCount += 1 + end + if interval > 0 and c.retrigCount >= interval then + c.retrigCount = 0 + retrigVolume(c, c.mRetrig // 16) + retrigVoice(st, c) + end + elseif fx == 29 then -- T + if param > 0 then + c.mTremor = param + end + elseif fx == 33 then -- X + if x == 1 then + if y > 0 then + c.mXFineUp = y + end + if tick == 0 then + c.period -= c.mXFineUp + clampPeriod(st, c) + end + elseif x == 2 then + if y > 0 then + c.mXFineDn = y + end + if tick == 0 then + c.period += c.mXFineDn + clampPeriod(st, c) + end + end + end + -- the volume slide half of 5xy / 6xy and Axy + if fx == 0xA or fx == 5 or fx == 6 then + if xm then + if param > 0 then + c.mVolSlide = param + end + if tick > 0 then + volSlideMod(c, c.mVolSlide) + end + elseif tick > 0 then + volSlideMod(c, param) + end + end + -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks + if fx == 29 and tick > 0 then + local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 + c.tremorCount = (c.tremorCount + 1) % (on + off) + c.tremorOn = c.tremorCount < on + end +end + +-- the XM volume column (everything but set volume / set panning, done by trigger) +local function volColXm(st: any, c: any, tick: number) + local v = c.vcmd + if v < 0x60 then + return + end + local hi, lo = v // 16, v % 16 + if hi == 6 then + if tick > 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 7 then + if tick > 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 8 then + if tick == 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 9 then + if tick == 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 0xA then + if lo > 0 then + c.vibSpeed = lo + end + elseif hi == 0xB then + if lo > 0 then + c.vibDepth = lo + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif hi == 0xD then + if tick > 0 then + c.pan = max(0, c.pan - lo) + end + elseif hi == 0xE then + if tick > 0 then + c.pan = min(255, c.pan + lo) + end + elseif hi == 0xF then + if lo > 0 then + c.portaSpeed = lo * 16 + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ S3M / IT effects +-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects +local function mem(st: any, c: any, field: string, param: number): number + if st.fmt == S3M then + if param > 0 then + c.mS3M = param + end + return c.mS3M + end + if param > 0 then + c[field] = param + end + return c[field] +end + +local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) + if p >= 0xF0 then + if tick == 0 then + c.period += sign * (p % 16) * 4 + end + elseif p >= 0xE0 then + if tick == 0 then + c.period += sign * (p % 16) + end + elseif tick > 0 then + c.period += sign * p * 4 + end + clampPeriod(st, c) +end + +local function fxS3mIt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local it = st.fmt == IT + if fx == 1 then -- A speed + if tick == 0 and param > 0 then + st.speed = param + end + elseif fx == 2 then -- B jump + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 3 then -- C break + if tick == 0 then + st.breakRow = if it then param else (param // 16) * 10 + param % 16 + end + elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) + local p = mem(st, c, "mVolSlide", param) + c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) + elseif fx == 5 then -- E porta down + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, 1) + elseif fx == 6 then -- F porta up + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, -1) + elseif fx == 9 then -- I tremor + local p = mem(st, c, "mTremor", param) + if tick > 0 or not it then + local on, off = p // 16, p % 16 + if it and st.oldFx or not it then + on, off = on + 1, off + 1 + end + on, off = max(on, 1), max(off, 1) + c.tremorCount = (c.tremorCount + 1) % (on + off) + c.tremorOn = c.tremorCount < on + end + elseif fx == 10 then -- J arpeggio + local p = mem(st, c, "mArp", param) + local k = tick % 3 + c.arp = if k == 1 then p // 16 elseif k == 2 then p % 16 else 0 + elseif fx == 13 then -- M channel volume + if tick == 0 and param <= 64 then + c.chanVol = param + end + elseif fx == 14 then -- N channel volume slide + local p = mem(st, c, "mChanVolSlide", param) + c.chanVol = dSlide(c.chanVol, p, tick, false, 64) + elseif fx == 16 then -- P panning slide (0..64 scale x 4) + local p = mem(st, c, "mPanSlide", param) + local pan64 = c.pan / 4 + local x, y = p // 16, p % 16 + if y == 0xF and x > 0 then + if tick == 0 then + pan64 = max(0, pan64 - x) + end + elseif x == 0xF and y > 0 then + if tick == 0 then + pan64 = min(64, pan64 + y) + end + elseif tick > 0 then + if y == 0 then + pan64 = max(0, pan64 - x) + elseif x == 0 then + pan64 = min(64, pan64 + y) + end + end + c.pan = pan64 * 4 + c.surround = false + elseif fx == 17 then -- Q retrigger + volume change + local p = mem(st, c, "mRetrig", param) + local interval = p % 16 + if interval > 0 then + if tick == 0 and c.retrigCount <= 0 then + c.retrigCount = interval + end + if tick > 0 then + c.retrigCount -= 1 + if c.retrigCount <= 0 then + c.retrigCount = interval + retrigVolume(c, p // 16) + retrigVoice(st, c) + end + end + end + elseif fx == 18 then -- R tremolo + if param // 16 > 0 then + c.tremSpeed = param // 16 + end + if param % 16 > 0 then + c.tremDepth = param % 16 + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 19 then -- S extended + local p = if it then mem(st, c, "mS", param) else mem(st, c, "mS", param) + local x, y = p // 16, p % 16 + if x == 3 then + c.vibWave = y % 8 + elseif x == 4 then + c.tremWave = y % 8 + elseif x == 5 then + c.panbWave = y % 8 + elseif x == 6 then + if tick == 0 then + st.fineDelay += y + end + elseif x == 7 then + if tick == 0 then + if y <= 2 then + for _, u in st.voices do + if u.active and u.bg and u.chan == c.idx then + if y == 0 then + cutVoice(u) + elseif y == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + elseif y <= 6 then + c.nna = y - 3 + else + local v = c.voice + if v then + if y == 7 then + v.volEnvOn = false + elseif y == 8 then + v.volEnvOn = true + elseif y == 9 then + v.panEnvOn = false + elseif y == 10 then + v.panEnvOn = true + elseif y == 11 then + v.pitchEnvOn = false + elseif y == 12 then + v.pitchEnvOn = true + end + end + end + end + elseif x == 8 then + if tick == 0 then + c.pan = y * 17 + c.surround = false + end + elseif x == 9 then + if tick == 0 and y == 1 then + c.surround = true + end + elseif x == 0xA then + if tick == 0 then + c.mHighOffset = y + end + elseif x == 0xB then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + elseif it then + c.loopRow = st.row + 1 + end + end + end + elseif x == 0xC then + local at = if y == 0 and it then 1 else y + if tick == at and (y > 0 or it) then + if it then + cutVoice(c.voice) + end + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 20 then -- T tempo + if param >= 0x20 then + if tick == 0 then + st.tempo = param + end + elseif it then + if param > 0 then + c.mTempo = param + end + local p = c.mTempo + if tick > 0 then + if p >= 0x10 then + st.tempo = min(255, st.tempo + (p - 0x10)) + else + st.tempo = max(32, st.tempo - p) + end + end + end + elseif fx == 22 then -- V global volume + if tick == 0 then + if it then + if param <= 128 then + st.gvol = param + end + else + st.gvol = min(param, 64) * 2 + end + end + elseif fx == 23 then -- W global volume slide + local p = mem(st, c, "mGVolSlide", param) + st.gvol = dSlide(st.gvol, p, tick, false, 128) + elseif fx == 24 then -- X panning + if tick == 0 then + if it then + c.pan = param + c.surround = false + elseif param <= 0x80 then + c.pan = param * 2 + c.surround = false + elseif param == 0xA4 then + c.surround = true + end + end + elseif fx == 25 then -- Y panbrello + if param // 16 > 0 then + c.panbSpeed = param // 16 + end + if param % 16 > 0 then + c.panbDepth = param % 16 + end + c.panbDelta = wave64(c.panbWave % 4, c.panbPos // 4) * c.panbDepth / 16 + c.panbPos = (c.panbPos + c.panbSpeed) % 256 + elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) + if tick == 0 then + if param < 0x80 then + c.cutoff = param + elseif param < 0x90 then + c.reso = (param - 0x80) * 8 + end + if c.voice then + c.voice.cutoff, c.voice.reso = c.cutoff, c.reso + end + end + end + -- tone portamento (G, L) + if fx == 7 or fx == 12 then + if fx == 7 then + if st.fmt == S3M then + if param > 0 then + c.portaSpeed = param + end + elseif st.compatG then + if param > 0 then + c.portaSpeed = param + end + else + if param > 0 then + c.mEF = param + end + c.portaSpeed = c.mEF + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end + -- vibrato (H, U, K) + if fx == 8 or fx == 21 or fx == 11 then + if fx ~= 11 then + if param // 16 > 0 then + c.vibSpeed = param // 16 + end + if param % 16 > 0 then + c.vibDepth = param % 16 + end + end + local scale = if fx == 21 then 2 / 255 else 8 / 255 + if it and not st.oldFx then + scale /= 2 + end + if tick > 0 or (it and not st.oldFx) then + vibrato(st, c, scale) + end + end +end + +-- the IT volume column (value stored + 1): slides, portamento, vibrato +local function volColIt(st: any, c: any, tick: number) + local v = c.vcmd - 1 + if v < 65 then + return + end + if v <= 74 then + local p = v - 65 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 84 then + local p = v - 75 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 94 then + local p = v - 85 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 104 then + local p = v - 95 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 114 then + local p = (v - 105) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period += c.mEF * 4 + clampPeriod(st, c) + end + elseif v <= 124 then + local p = (v - 115) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period -= c.mEF * 4 + clampPeriod(st, c) + end + elseif v >= 193 and v <= 202 then + local p = Tables.IT_VOLPORTA[v - 192] or 0 + if p > 0 then + if st.compatG then + c.portaSpeed = p + else + c.mEF = p + c.portaSpeed = p + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif v >= 203 and v <= 212 then + local d = v - 203 + if d > 0 then + c.vibDepth = d + end + if tick > 0 or not st.oldFx then + vibrato(st, c, if st.oldFx then 8 / 255 else 4 / 255) + end + end +end + +-- ------------------------------------------------------------------------------------------------ rows and ticks +local function noteDelayOf(st: any, fx: number, param: number): number + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then + return param % 16 + elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then + return param % 16 + end + return 0 +end + +local function finetuneOf(st: any, fx: number, param: number): number? + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then + local y = param % 16 + if st.fmt == MOD then + return (if y >= 8 then y - 16 else y) * 16 + end + return (y - 8) * 16 + end + return nil +end + +local function runEffects(st: any, c: any, tick: number) + c.vibDelta, c.arp = 0, 0 + if st.fmt == MOD or st.fmt == XM then + fxModXm(st, c, tick) + if st.fmt == XM then + volColXm(st, c, tick) + end + else + if st.fmt == IT then + volColIt(st, c, tick) + end + fxS3mIt(st, c, tick) + end + -- keep the tremolo / panbrello offsets only while their effect runs + local fx = c.fx + if st.fmt == MOD or st.fmt == XM then + if fx ~= 7 then + c.tremDelta = 0 + end + if fx ~= 29 then + c.tremorOn = true + end + else + if fx ~= 18 then + c.tremDelta = 0 + end + if fx ~= 9 then + c.tremorOn = true + end + if fx ~= 25 then + c.panbDelta = 0 + end + end +end + +local function processRow(st: any) + local m = st.m + local pat = st.pat + local nch = st.nch + local data = pat.data + local base = st.row * nch * 5 + st.visited[st.ord * 1024 + st.row] = true + st.rows += 1 + for i = 1, nch do + local c = st.chans[i] + local o = base + (i - 1) * 5 + local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) + if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then + fx = 255 + end + c.fx, c.param, c.vcmd = fx, param, vcmd + c.cutTick, c.keyOffTick = -1, -1 + c.triggered = false + if fx ~= 29 and fx ~= 9 then + c.tremorCount = 0 + end + local delay = noteDelayOf(st, fx, param) + c.finetune = finetuneOf(st, fx, param) + if delay > 0 then + c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd + else + c.delayTick = -1 + trigger(st, c, note, ins, vcmd) + end + runEffects(st, c, 0) + end + local _ = m +end + +local function updateEnvelope(env: any, pos: number, keyOn: boolean): (number, number, boolean) + -- returns value, next position, ended + local ticks, values = env.ticks, env.values + local n = #ticks + if n == 0 then + return 0, pos, true + end + local value + if pos <= ticks[1] then + value = values[1] + elseif pos >= ticks[n] then + value = values[n] + else + local i = 1 + while i < n and ticks[i + 1] <= pos do + i += 1 + end + local t0, t1 = ticks[i], ticks[i + 1] + if t1 > t0 then + value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) + else + value = values[i + 1] + end + end + local nextPos = pos + 1 + local ended = false + if keyOn and env.sustain and ticks[env.susEnd] and nextPos > ticks[env.susEnd] then + nextPos = ticks[env.susStart] or nextPos + elseif env.loop and ticks[env.loopEnd] and nextPos > ticks[env.loopEnd] then + nextPos = ticks[env.loopStart] or nextPos + elseif nextPos > ticks[n] then + nextPos = ticks[n] + ended = true + end + return value, nextPos, ended +end + +-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter +local function updateVoice(st: any, v: any) + local ins = v.ins + local it = st.fmt == IT + local envVol, envPan, envPitch = 64, 0, 0 + local filterEnv = nil + if ins then + local e = ins.volEnv + if e and e.enabled and v.volEnvOn then + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn) + envVol, v.volEnvPos = val, np + if ended and it then + if val <= 0 then + v.active = false + return + end + v.fading = true + end + end + e = ins.panEnv + if e and e.enabled and v.panEnvOn then + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn) + envPan, v.panEnvPos = val, np + end + e = ins.pitchEnv + if e and e.enabled and v.pitchEnvOn then + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn) + v.pitchEnvPos = np + if e.filter then + filterEnv = val + else + envPitch = val + end + end + if v.fading then + local fo = ins.fadeout or 0 + v.fade -= if it then fo * 64 else fo * 2 + if v.fade <= 0 then + v.fade = 0 + v.active = false + return + end + end + end + v.envVol = envVol + -- auto-vibrato: XM per instrument, IT per sample + local avSrc = if it then v.smp else ins + local avDelta = 0 + if avSrc and (avSrc.vibDepth or 0) > 0 then + local depth = avSrc.vibDepth + local sweep = avSrc.vibSweep or 0 + if it then + -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps + local target = depth * 256 + if sweep == 0 then + v.avAmp = target + elseif v.avAmp < target then + v.avAmp = min(target, v.avAmp + sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 + else + if sweep == 0 then + v.avAmp = depth * 256 + elseif v.keyOn then + v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) + end + v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 + end + -- frequency + local P = v.periodOut + avDelta + local freq + if st.linear then + freq = v.base * 2 ^ (-P / 768) + else + freq = if P > 0 then st.amiga / P else 0 + end + if envPitch ~= 0 then + freq *= 2 ^ (envPitch / 24) + end + v.inc = freq / st.sr + -- volume + local smp = v.smp + local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 + if it then + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) + end + if v.tremorMute then + vol = 0 + end + -- panning + local pan = v.pan + if envPan ~= 0 then + local range = 128 - abs(pan - 128) + pan += envPan * range / 32 + end + if it and ins and (ins.pps or 0) ~= 0 then + pan += (v.note - (ins.ppc or 60) - 1) * ins.pps / 2 + end + pan = clamp(pan, 0, 256) + pan = clamp(128 + (pan - 128) * st.separation, 0, 256) + local g = vol * st.master + if v.surround then + v.tl, v.tr = g * 0.5, -g * 0.5 + else + v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 + end + v.rampN = st.ramp + -- IT resonant filter + local cutoff = v.cutoff + if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then + local cc = cutoff + if filterEnv ~= nil then + cc = cutoff * (filterEnv + 32) / 64 + end + local fhz = 110 * 2 ^ (0.25 + cc / 24) + fhz = clamp(fhz, 120, min(20000, st.sr / 2)) + local dmp = 10 ^ (-v.reso * (24 / 128) / 20) + local fc = fhz * 2 * math.pi / st.sr + local d = (1 - 2 * dmp) * fc + if d > 2 then + d = 2 + end + d = (2 * dmp - d) / fc + local e = 1 / (fc * fc) + local den = 1 + d + e + v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den + v.fOn = not (cc >= 127 and v.reso == 0) + else + v.fOn = false + end +end + +-- tick(st) -> frames to mix for this tick (0 when the song ended) +function Player.tick(st: any): number + if st.ended then + return 0 + end + local tick = st.tick + if tick == 0 and st.patDelayRep == 0 then + local key = st.ord * 1024 + st.row + if st.visited[key] and not st.loopAllowed then + st.ended = true + return 0 + end + if st.visited[key] then + -- looping on: forget the song so far, keep playing + table.clear(st.visited) + end + st.fineDelay = 0 + processRow(st) + else + local t = tick % st.speed + local rep = tick >= st.speed or st.patDelayRep > 0 + for i = 1, st.nch do + local c = st.chans[i] + if c.delayTick == tick and not rep then + c.delayTick = -1 + trigger(st, c, c.dNote, c.dIns, c.dVol) + end + if rep and t == 0 then + c.vibDelta, c.arp = 0, 0 + else + runEffects(st, c, if t == 0 then 1 else t) + end + end + end + if st.ended then + return 0 + end + -- channel -> foreground voice + for i = 1, st.nch do + local c = st.chans[i] + local v = c.voice + if v and v.active and v.chan == i and not v.bg then + local P = arpPeriod(st, c.period, c.arp) + c.vibDelta + v.period, v.periodOut, v.base = c.period, P, c.base + v.vol = clamp(c.vol + c.tremDelta, 0, 64) + if c.muted then + v.vol = 0 + end + v.pan = clamp(c.pan + c.panbDelta, 0, 256) + v.surround = c.surround + v.chanVol = c.chanVol + v.tremorMute = not c.tremorOn + v.cutoff, v.reso = c.cutoff, c.reso + end + end + for _, v in st.voices do + if v.active then + updateVoice(st, v) + end + end + -- frames for this tick: 2.5 / tempo seconds, rounded per tick as OpenMPT / FT2 do + local frames = floor(st.sr * 2.5 / max(1, st.tempo) + 0.5) + -- advance + st.tick += 1 + if st.tick >= st.speed + st.fineDelay then + st.tick = 0 + if st.patDelayRep < st.patDelay then + st.patDelayRep += 1 + else + st.patDelay, st.patDelayRep = 0, 0 + advanceRow(st) + end + end + return frames +end + +return Player diff --git a/src/Formats/codecs/Tracker/Tables.luau b/src/Formats/codecs/Tracker/Tables.luau new file mode 100644 index 0000000..c621ec1 --- /dev/null +++ b/src/Formats/codecs/Tracker/Tables.luau @@ -0,0 +1,113 @@ +--!strict +--!native +-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the +-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M +-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker +-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). +local Tables = {} + +-- the ProTracker half-sine (32 steps, 0..255) +local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } + +-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) +local RANDOM: { number } = {} +do + local s = 12345 + for i = 1, 64 do + s = (s * 1103515245 + 12345) % 2147483648 + RANDOM[i] = (s // 65536) % 511 - 255 + end +end +function Tables.wave64(kind: number, pos: number): number + local p = pos % 64 + if kind == 1 then + return 255 - p * 8 + elseif kind == 2 then + return if p < 32 then 255 else -255 + elseif kind == 3 then + return RANDOM[p + 1] + end + local v = SINE32[(p % 32) + 1] + return if p >= 32 then -v else v +end + +-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. +-- IT: 0 sine, 1 ramp down, 2 square, 3 random. +local SINE256: { number } = {} +for i = 0, 255 do + SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) +end +function Tables.autoWave(kind: number, pos: number, it: boolean): number + local p = pos % 256 + if it then + if kind == 1 then + return 64 - (p + 1) // 2 + elseif kind == 2 then + return if p < 128 then 64 else -64 + elseif kind == 3 then + return RANDOM[(p % 64) + 1] // 4 + end + return SINE256[p + 1] + end + if kind == 1 then + return if p < 128 then 64 else -64 + elseif kind == 2 then + return 64 - (p + 1) // 2 + elseif kind == 3 then + return (p + 1) // 2 - 64 + end + return SINE256[p + 1] +end + +-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: +-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at +-- its base rate (8363 Hz). +local PERIODS = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, + 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, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, +} +Tables.PERIODS = PERIODS +Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) + +-- periodToNote(period) -> note (1..120), 0 for period 0 +function Tables.periodToNote(period: number): number + if period <= 0 then + return 0 + end + -- exact match first, then the nearest note on a log scale + for i = 1, #PERIODS do + if PERIODS[i] == period then + return i + Tables.PERIOD_FIRST_NOTE - 1 + end + end + local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) + return math.clamp(n, 1, 120) +end + +-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends +function Tables.noteToPeriod(note: number): number + local i = note - Tables.PERIOD_FIRST_NOTE + 1 + if i >= 1 and i <= #PERIODS then + return PERIODS[i] + end + return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) +end + +-- IT volume column "g" (tone portamento) speeds +Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } + +-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value +Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } +Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } + +-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate +-- (FT2 / ST3 period units, 4x ProTracker's) +Tables.AMIGA = 8363 * 1712 +-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) +Tables.AMIGA_PAL = 7093789.2 / 2 * 4 + +return Tables diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/Tracker/init.luau new file mode 100644 index 0000000..8412ef1 --- /dev/null +++ b/src/Formats/codecs/Tracker/init.luau @@ -0,0 +1,513 @@ +--!strict +-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read +-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio +-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM +-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. +-- +-- local Tracker = require("@formats/codecs/Tracker") +-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder +-- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- +-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): +-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks +-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) +-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) +-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) +-- linear linear frequency slides (XM / IT flag) or Amiga periods +-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column +-- is a sample number (MOD, S3M, IT sample mode) +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) } +-- 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 +-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = +-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 +-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the +-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; +-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1 +-- (0 = none). Tracker.cell / Tracker.setCell read and write cells. +-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, +-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), +-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), +-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / +-- vibRate (IT auto-vibrato) } +-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, +-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, +-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, +-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), +-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } +-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, +-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } +-- +-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768). +-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add +-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: +-- base = c5speed, ref 61. +-- +-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects +-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Player = require("@formats/codecs/Tracker/Player") +local Mixer = require("@formats/codecs/Tracker/Mixer") +local Pcm = require("@formats/codecs/Tracker/Pcm") +local Tables = require("@formats/codecs/Tracker/Tables") + +local Tracker = {} + +Tracker.Pcm = Pcm +Tracker.Tables = Tables + +export type Envelope = { + enabled: boolean, + ticks: { number }, + values: { number }, + loop: boolean, + loopStart: number, + loopEnd: number, + sustain: boolean, + susStart: number, + susEnd: number, + carry: boolean?, + filter: boolean?, +} + +export type Pattern = { rows: number, data: buffer } + +export type RenderOptions = { + sampleRate: number?, -- default 44100 + interpolation: ("linear" | "none")?, -- default "linear" + stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre) + loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false + maxDuration: number?, -- seconds; the render stops there (default 3600) +} + +local CELL = 5 + +-- ------------------------------------------------------------------------------------------------ constructors +-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults +function Tracker.newModule(format: string, channels: number): any + local m = { + kind = "music", + format = format, + title = "", + channels = channels, + speed = 6, + tempo = 125, + globalVolume = 128, + mixVolume = 48, + order = {}, + restart = 0, + linear = format == "xm" or format == "it", + instrumentMode = format == "xm" or format == "it", + flags = {}, + channelPan = {}, + channelVolume = {}, + channelMute = {}, + patterns = {}, + instruments = {}, + samples = {}, + meta = {}, + render = Tracker.renderMethod, + } + for i = 1, channels do + m.channelVolume[i] = 64 + if format == "mod" then + local k = (i - 1) % 4 + m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width + else + m.channelPan[i] = 128 + end + end + return m +end + +-- newPattern(rows, channels) -> an empty Pattern +function Tracker.newPattern(rows: number, channels: number): Pattern + return { rows = rows, data = buffer.create(rows * channels * CELL) } +end + +-- newSample() -> an empty Sample +function Tracker.newSample(name: string?): any + return { + name = name or "", + data = buffer.create(0), + length = 0, + channels = 1, + bits = 8, + loopStart = 0, + loopEnd = 0, + loopType = 0, + susStart = 0, + susEnd = 0, + susType = 0, + volume = 64, + globalVolume = 64, + pan = nil :: number?, + c5speed = 8363, + relativeNote = 0, + finetune = 0, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.newEnvelope(): Envelope + return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } +end + +-- newInstrument() -> an Instrument mapping every note to sample 0 (none) +function Tracker.newInstrument(name: string?): any + local sm, nm = table.create(120, 0), table.create(120, 0) + for i = 1, 120 do + nm[i] = i + end + return { + name = name or "", + sampleMap = sm, + noteMap = nm, + volEnv = nil :: Envelope?, + panEnv = nil :: Envelope?, + pitchEnv = nil :: Envelope?, + fadeout = 0, + nna = 0, + dct = 0, + dca = 0, + globalVolume = 128, + pan = nil :: number?, + pps = 0, + ppc = 60, + cutoff = nil :: number?, + resonance = nil :: number?, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, +-- channel 1-based); nil when out of range +function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number) + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return nil, 0, 0, 0, 0 + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) +end + +-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) +function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return false + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + buffer.writeu8(d, o, note % 256) + buffer.writeu8(d, o + 1, ins % 256) + buffer.writeu8(d, o + 2, vol % 256) + buffer.writeu8(d, o + 3, fx % 256) + buffer.writeu8(d, o + 4, param % 256) + return true +end + +-- ------------------------------------------------------------------------------------------------ validation +local function num(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v >= lo and v <= hi +end + +local function fixEnvelope(e: any): (any, string?) + if e == nil then + return nil + end + if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then + return nil, "bad envelope" + end + local n = math.min(#e.ticks, #e.values) + local last = -1 + for i = 1, n do + local t, v = e.ticks[i], e.values[i] + if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then + -- points must go forward: keep the valid prefix + n = i - 1 + break + end + last = t + end + for i = #e.ticks, n + 1, -1 do + e.ticks[i] = nil + end + for i = #e.values, n + 1, -1 do + e.values[i] = nil + end + if n == 0 then + e.enabled = false + end + local function idx(v: any): number + return if num(v, 1, math.max(1, n)) then math.floor(v) else 1 + end + e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) + e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) + if e.loopEnd < e.loopStart then + e.loop = false + end + if e.susEnd < e.susStart then + e.sustain = false + end + return e +end + +local function fixLoop(s: number, e: number, t: number, len: number): (number, number, number) + if not num(t, 0, 2) or t == 0 then + return 0, 0, 0 + end + s, e = math.floor(math.clamp(s, 0, len)), math.floor(math.clamp(e, 0, len)) + if e - s < 1 then + return 0, 0, 0 + end + if t == 2 and e - s < 2 then + t = 1 + end + return s, e, t +end + +-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and +-- numbers into range (in place) +function Tracker.validate(m: any): (boolean?, Err.Err?) + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "not a module") + end + if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format)) + end + if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad channel count") + end + if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then + return nil, Err.new(Err.ARG, "module without order / patterns / samples") + end + m.instruments = if type(m.instruments) == "table" then m.instruments else {} + m.flags = if type(m.flags) == "table" then m.flags else {} + m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {} + m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {} + m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {} + for i = 1, m.channels do + local p = m.channelPan[i] + if p ~= 512 and not num(p, 0, 256) then + m.channelPan[i] = 128 + end + if not num(m.channelVolume[i], 0, 64) then + m.channelVolume[i] = 64 + end + end + m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6 + m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125 + m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128 + m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48 + m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0 + for i, o in m.order do + if not num(o, 0, 255) then + return nil, Err.new(Err.ARG, "bad order entry " .. i) + end + end + for i, p in m.patterns do + if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then + return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) + end + end + for i, s in m.samples do + if type(s) ~= "table" then + return nil, Err.new(Err.ARG, "bad sample " .. i) + end + local nch = if s.channels == 2 then 2 else 1 + s.channels = nch + if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then + return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") + end + s.length = math.floor(s.length) + s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) + s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) + s.volume = if num(s.volume, 0, 64) then s.volume else 64 + s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64 + if s.pan ~= nil and not num(s.pan, 0, 256) then + s.pan = nil + end + s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363 + s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0 + s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0 + end + for i, ins in m.instruments do + if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then + return nil, Err.new(Err.ARG, "bad instrument " .. i) + end + for n = 1, 120 do + if not num(ins.sampleMap[n], 0, 1e6) then + ins.sampleMap[n] = 0 + end + if not num(ins.noteMap[n], 1, 120) then + ins.noteMap[n] = n + end + end + local err + ins.volEnv, err = fixEnvelope(ins.volEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.panEnv, err = fixEnvelope(ins.panEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0 + ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128 + if ins.pan ~= nil and not num(ins.pan, 0, 256) then + ins.pan = nil + end + if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then + ins.cutoff = nil + end + if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then + ins.resonance = nil + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ rendering +local Decoder = {} +Decoder.__index = Decoder + +-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err +function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) + local ok, err = Tracker.validate(m) + if not ok then + return nil, err + end + local sr = opts and opts.sampleRate or 44100 + local maxFrames = (opts and opts.maxDuration or 3600) * sr + local st = Player.new(m, sr, { stereoSeparation = 100 }) + local frames = 0 + while frames < maxFrames do + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + frames += f + end + return math.min(frames, maxFrames) / sr +end + +local function newPlayer(self: any) + self.st = Player.new(self.module, self.sampleRate, self.opts) + self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) + self.left = 0 + self.pos = 0 +end + +-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err +function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local o: RenderOptions = opts or {} + local sr = o.sampleRate or 44100 + if type(sr) ~= "number" or sr < 1000 or sr > 384000 then + return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") + end + local seconds, err = Tracker.duration(m, o) + if not seconds then + return nil, err + end + local frames = math.floor(seconds * sr + 0.5) + local self = setmetatable({ + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = m.title or "" }, + module = m, + opts = o, + linear = o.interpolation ~= "none", + maxFrames = (o.maxDuration or 3600) * sr, + st = nil :: any, + left = 0, + pos = 0, + }, Decoder) + newPlayer(self) + return self :: any, nil +end + +-- the Module method: module:render(opts) +function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder + local dec = Tracker.render(self, opts) + return dec :: any +end + +-- run(self, out?, n) -> frames produced (out nil: advance without mixing) +local function run(self: any, out: buffer?, n: number): number + local st = self.st + local done = 0 + while done < n do + if self.left <= 0 then + if self.pos + done >= self.maxFrames then + break + end + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + self.left = f + if f == 0 then + continue + end + end + local k = math.min(self.left, n - done) + Mixer.mix(st, out, done, k, self.linear) + self.left -= k + done += k + end + self.pos += done + return done +end + +-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end) +function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(tonumber(n) or 0)) + local o = out + if o == nil or buffer.len(o) < n * 8 then + o = buffer.create(n * 8) + else + buffer.fill(o, 0, 0, n * 8) + end + local got = run(self, o, n) + return o :: buffer, got +end + +-- seek(seconds): replays the song silently up to the position (sample positions included) +function Decoder.seek(self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) + newPlayer(self) + local chunk = 65536 + while self.pos < target do + local got = run(self, nil, math.min(chunk, target - self.pos)) + if got == 0 then + break + end + end + -- the gains ramp in from silence after a seek + for _, v in self.st.voices do + v.gl, v.gr = 0, 0 + end +end + +function Decoder.position(self: any): number + return self.pos / self.sampleRate +end + +return Tracker diff --git a/src/Formats/music/mod/init.luau b/src/Formats/music/mod/init.luau new file mode 100644 index 0000000..7f4eb88 --- /dev/null +++ b/src/Formats/music/mod/init.luau @@ -0,0 +1,361 @@ +--!strict +-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, +-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through +-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" +-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). +-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter +-- (E0x), PowerPacker-packed files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Mod = { + name = "mod", + category = "music", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) +} +export type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local Pcm = Tracker.Pcm +local Tables = Tracker.Tables + +local FIXED: { [string]: number } = { + ["M.K."] = 4, + ["M!K!"] = 4, + ["M&K!"] = 4, + ["N.T."] = 4, + ["FLT4"] = 4, + ["FLT8"] = 8, + ["CD81"] = 8, + ["OKTA"] = 8, + ["OCTA"] = 8, + ["EXO4"] = 4, + ["EXO8"] = 8, +} + +-- channels from the 4-byte signature at 1080, or nil +local function signatureChannels(sig: string): number? + local fixed = FIXED[sig] + if fixed then + return fixed + end + local d = string.match(sig, "^(%d)CHN$") + if d then + local n = tonumber(d) :: number + return if n >= 1 then n else nil + end + local dd = string.match(sig, "^(%d%d)C[HN]$") + if dd then + local n = tonumber(dd) :: number + return if n >= 1 and n <= 32 then n else nil + end + local t = string.match(sig, "^TDZ(%d)$") + if t then + local n = tonumber(t) :: number + return if n >= 1 then n else nil + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mod.sniff(r: Bytes.Reader): number + if r:size() < 1084 then + return 0 + end + local sig = r:peek(4, 1080) + if signatureChannels(sig) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + local size = r:size() + local sig = if size >= 1084 then r:peek(4, 1080) else "" + local channels = signatureChannels(sig) + local nsamples = 31 + if not channels then + -- a 15-sample Soundtracker module (no signature): only when the header is plausible + nsamples, channels = 15, 4 + end + local nch = channels :: number + local m = Tracker.newModule("mod", nch) + m.title = r:fixed(20) + local lengths: { number } = {} + for i = 1, nsamples do + local s = Tracker.newSample(r:fixed(22)) + local len = r:u16be() * 2 + local ft = r:u8() % 16 + local vol = r:u8() + local ls = r:u16be() * 2 + local ll = r:u16be() * 2 + if r.err then + return nil, r.err + end + if nsamples == 15 and (vol > 64 or ft ~= 0) then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") + end + s.finetune = (if ft >= 8 then ft - 16 else ft) * 16 + s.volume = math.min(vol, 64) + s.bits = 8 + if ll > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 + end + lengths[i] = len + m.samples[i] = s + end + local songLength = r:u8() + local restart = r:u8() + local order: { number } = {} + local maxPat = 0 + for i = 1, 128 do + local p = r:u8() + order[i] = p + maxPat = math.max(maxPat, p) + end + if r.err then + return nil, r.err + end + if songLength == 0 or songLength > 128 or maxPat >= 128 then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") + end + if nsamples == 31 then + r:skip(4) + end + for i = 1, songLength do + m.order[i] = order[i] + end + m.restart = if restart < songLength then restart else 0 + m.meta.signature = if nsamples == 31 then sig else nil + m.flags.amigaLimits = nch == 4 + -- patterns + local npat = maxPat + 1 + local patBytes = 64 * nch * 4 + if not r:need(npat * patBytes) then + return nil, r.err + end + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, nch) + local base = r.pos + p * patBytes + local d = pat.data + for i = 0, 64 * nch - 1 do + local o = base + i * 4 + local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) + local period = (b0 % 16) * 256 + b1 + local ins = (b0 // 16) * 16 + b2 // 16 + local q = i * 5 + buffer.writeu8(d, q, Tables.periodToNote(period)) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 3, b2 % 16) + buffer.writeu8(d, q + 4, b3) + end + m.patterns[p + 1] = pat + end + r:skip(npat * patBytes) + -- sample data (8-bit signed; the last samples of a truncated file are cut short) + local total = 0 + for i = 1, nsamples do + local s = m.samples[i] + local len = math.min(lengths[i], r:remaining()) + total += len * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) + end + r:skip(len) + s.data, s.length = data, len + if s.loopEnd > len then + s.loopEnd = len + if s.loopEnd - s.loopStart < 2 then + s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 + end + end + end + m.meta.source = { format = "mod", samples = nsamples } + m.render = Tracker.renderMethod + 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 + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to +-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. +function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "mod" and m.format ~= "xm" then + return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") + end + local nch = m.channels + if nch > 32 then + return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") + end + -- the sample for each instrument number + local smpOf: { any } = {} + if m.format == "xm" then + for i, ins in m.instruments do + local first = 0 + for n = 1, 120 do + local s = ins.sampleMap[n] + if s ~= 0 then + if first ~= 0 and s ~= first then + return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") + end + first = s + end + end + smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) + end + else + for i, s in m.samples do + smpOf[i] = s + end + end + if #smpOf > 31 then + return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order == 0 or #order > 128 then + return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") + end + local npat = #m.patterns + if npat > 100 then + return nil, Err.new(Err.ARG, "too many patterns for MOD") + end + for p, pat in m.patterns do + if pat.rows ~= 64 then + return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") + end + end + local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) + writeName(w, m.title or "", 20) + local datas: { buffer } = {} + for i = 1, 31 do + local s = smpOf[i] + if s then + local len = math.min(s.length, 131070) + local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) + if s.channels == 2 then + -- mix stereo samples down + local mono = buffer.create(len * 4) + for k = 0, len - 1 do + buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) + end + pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) + end + local even = len + len % 2 + local padded = buffer.create(even) + buffer.copy(padded, 0, pcm, 0, len) + datas[i] = padded + writeName(w, s.name or "", 22) + w:u16be(even // 2) + local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) + w:u8(ft % 16) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + if s.loopType > 0 and s.loopEnd <= even then + w:u16be(s.loopStart // 2) + w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2)) + else + w:u16be(0) + w:u16be(1) + end + else + w:fill(0, 22) + w:u16be(0) + w:u8(0) + w:u8(0) + w:u16be(0) + w:u16be(1) + end + end + w:u8(#order) + w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127) + for i = 1, 128 do + w:u8(order[i] or 0) + end + local sig + if nch == 4 then + sig = if npat > 64 then "M!K!" else "M.K." + elseif nch < 10 then + sig = nch .. "CHN" + else + sig = nch .. "CH" + end + w:string(sig) + for p = 1, npat do + local d = m.patterns[p].data + for i = 0, 64 * nch - 1 do + local q = i * 5 + local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) + local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0 + if period > 4095 then + period = 0 + end + if fx > 15 then + fx, param = 0, 0 + end + if ins > 31 then + ins = 0 + end + w:u8((ins // 16) * 16 + period // 256) + w:u8(period % 256) + w:u8((ins % 16) * 16 + fx) + w:u8(param) + end + end + for i = 1, 31 do + if datas[i] then + w:bytes(datas[i]) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mod.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mod diff --git a/tests/music/_similar.luau b/tests/music/_similar.luau new file mode 100644 index 0000000..b234d86 --- /dev/null +++ b/tests/music/_similar.luau @@ -0,0 +1,201 @@ +-- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and +-- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left, +-- right and mid, and 20 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides. +local S = {} + +local SR, HOP, BANDS = 44100, 2048, 20 +local F_LO, F_HI = 100, 16000 +S.SR = SR + +local WINDOW = table.create(HOP, 0) +for i = 0, HOP - 1 do + WINDOW[i + 1] = 0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) +end +local BAND_OF = table.create(HOP // 2, -1) +for b = 1, HOP // 2 - 1 do + local f = b * SR / HOP + if f >= F_LO and f < F_HI then + BAND_OF[b + 1] = math.min(BANDS - 1, math.floor(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS)) + end +end + +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 1, n - 1 do + local bit = n // 2 + while bit > 0 and j >= bit and (j // bit) % 2 == 1 do + j -= bit + bit //= 2 + end + j += bit + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + end + local size = 2 + while size <= n do + local ang = -2 * math.pi / size + local wr, wi = math.cos(ang), math.sin(ang) + local half = size // 2 + for start = 0, n - 1, size do + local cr, ci = 1, 0 + for k = 0, half - 1 do + local a, b = start + k + 1, start + k + half + 1 + local tr = re[b] * cr - im[b] * ci + local 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 + end + end + size *= 2 + end +end + +-- features(samples (interleaved stereo f32 buffer), frames) -> { frames, rmsL, rmsR, rmsM, bands } +function S.features(buf: buffer, frames: number): any + local n = frames // HOP + local out = { frames = n, rmsL = {}, rmsR = {}, rmsM = {}, bands = {} } + local re, im = table.create(HOP, 0), table.create(HOP, 0) + for k = 0, n - 1 do + local sl, sr, sm = 0, 0, 0 + for i = 0, HOP - 1 do + local o = ((k * HOP + i) * 2) * 4 + local l, r = buffer.readf32(buf, o), buffer.readf32(buf, o + 4) + local m = (l + r) / 2 + sl += l * l + sr += r * r + sm += m * m + re[i + 1] = m * WINDOW[i + 1] + im[i + 1] = 0 + end + table.insert(out.rmsL, math.sqrt(sl / HOP)) + table.insert(out.rmsR, math.sqrt(sr / HOP)) + table.insert(out.rmsM, math.sqrt(sm / HOP)) + fft(re, im, HOP) + local e = table.create(BANDS, 0) + for b = 1, HOP // 2 - 1 do + local j = BAND_OF[b + 1] + if j >= 0 then + e[j + 1] += re[b + 1] * re[b + 1] + im[b + 1] * im[b + 1] + end + end + for j = 1, BANDS do + table.insert(out.bands, math.sqrt(e[j])) + end + end + return out +end + +-- renderAll(decoder, maxFrames) -> interleaved buffer, frames +function S.renderAll(dec: any, maxFrames: number): (buffer, number) + local total = math.min(dec.frames, maxFrames) + local out = buffer.create(math.max(1, total) * 8) + local pos = 0 + local chunk = buffer.create(4096 * 8) + while pos < total do + local _, n = dec:read(math.min(4096, total - pos), chunk) + if n == 0 then + break + end + buffer.copy(out, pos * 8, chunk, 0, n * 8) + pos += n + end + return out, pos +end + +local function db(x: number): number + return 20 * math.log10(x + 1e-6) +end + +-- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames: +-- gainDb total mid energy ratio in dB (ours / ref) +-- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either) +-- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB) +-- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks) +function S.compare(a: any, b: any): any + local n = math.min(a.frames, b.frames) + local ea, eb = 0, 0 + for k = 1, n do + ea += a.rmsM[k] ^ 2 + eb += b.rmsM[k] ^ 2 + end + local gainDb = 10 * math.log10((ea + 1e-12) / (eb + 1e-12)) + local xs, ys = {}, {} + for k = 1, n do + local x, y = db(a.rmsM[k]), db(b.rmsM[k]) + if x > -60 or y > -60 then + table.insert(xs, x) + table.insert(ys, y) + end + end + local mx, my = 0, 0 + for i = 1, #xs do + mx += xs[i] + my += ys[i] + end + mx /= math.max(1, #xs) + my /= math.max(1, #ys) + local sxy, sxx, syy = 0, 0, 0 + for i = 1, #xs do + sxy += (xs[i] - mx) * (ys[i] - my) + sxx += (xs[i] - mx) ^ 2 + syy += (ys[i] - my) ^ 2 + end + local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1 + local cs, cn = 0, 0 + local bal, bn = 0, 0 + for k = 1, n do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + cs += if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0 + cn += 1 + end + local la, ra, lb, rb = a.rmsL[k], a.rmsR[k], b.rmsL[k], b.rmsR[k] + if lb + rb > 0.01 then + bal += math.abs((la - ra) / (la + ra + 1e-9) - (lb - rb) / (lb + rb)) + bn += 1 + end + end + return { + gainDb = gainDb, + envCorr = envCorr, + spectral = if cn > 0 then cs / cn else 1, + balance = if bn > 0 then bal / bn else 0, + frames = n, + } +end + +-- worst(ours, ref, count) -> the blocks with the lowest spectral similarity (for debugging): { {block, sim} } +function S.worst(a: any, b: any, count: number): { { number } } + local list = {} + for k = 1, math.min(a.frames, b.frames) do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + table.insert(list, { k, if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0, db(a.rmsM[k]), db(b.rmsM[k]) }) + end + end + table.sort(list, function(x, y) + return x[2] < y[2] + end) + local out = {} + for i = 1, math.min(count, #list) do + out[i] = list[i] + end + return out +end + +return S diff --git a/tests/music/mod.luau b/tests/music/mod.luau new file mode 100644 index 0000000..f873981 --- /dev/null +++ b/tests/music/mod.luau @@ -0,0 +1,77 @@ +-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Mod = require("@formats/music/mod") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/mod_cases") + +local t = T.suite("mod") + +t:eq(Mod.name, "mod", "name") +t:eq(Mod.category, "music", "category") +t:check(Mod.caps.decode and Mod.caps.encode, "caps") + +local function load(data: string): any + return Mod.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 1.5, envCorr = 0.95, spectral = 0.93, balance = 0.05, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(Mod.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-6s gain %+.2f dB, envelope r %.3f, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envCorr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envCorr < THRESH.envCorr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envCorr > THRESH.envCorr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") + -- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files) + local out, werr = Mod.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Mod.decode(Bytes.reader(out :: buffer)) + t:check(m2, c.name .. ": re-decode") + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = Mod.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py new file mode 100644 index 0000000..d1c5609 --- /dev/null +++ b/tools/fixtures/_tracker.py @@ -0,0 +1,495 @@ +# 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 20 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 = 20 +F_LO, F_HI = 100.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 diff --git a/tools/fixtures/mod.py b/tools/fixtures/mod.py new file mode 100644 index 0000000..6b63f81 --- /dev/null +++ b/tools/fixtures/mod.py @@ -0,0 +1,104 @@ +# MOD fixtures (tools/fixtures.py): generated ProTracker modules exercising the effects, rendered by openmpt123. +# tests/gen/mod_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, fx=0, param=0): + p[row][ch] = (note, ins, fx, param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "loop": (0, 64)}, + {"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64)}, + {"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 64}, + {"name": "tri ft", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 56, "finetune": 3, "loop": (0, 32)}, + ] + + +def song_basic(): + a, b = empty(4), empty(4) + mel = [49, 53, 56, 61, 56, 53, 51, 49] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0) + put(a, 0, 2, 49, 3, 0x1, 0x02) + put(a, 16, 2, 0, 0, 0x2, 0x03) + put(a, 32, 2, 61, 3, 0xC, 0x30) + put(a, 33, 2, 0, 0, 0xA, 0x02) + put(a, 48, 2, 0, 0, 0xA, 0x40) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2) + put(a, 60, 3, 61, 4, 0xE, 0xC2) + # pattern b: portamento, vibrato, tremolo, offsets, retrig, delay, fine slides, speed change, break + put(b, 0, 0, 49, 1) + put(b, 4, 0, 61, 0, 0x3, 0x08) + put(b, 8, 0, 0, 0, 0x3, 0x00) + put(b, 12, 0, 49, 0, 0x5, 0x02) + put(b, 16, 0, 56, 5, 0x4, 0x46) + put(b, 20, 0, 0, 0, 0x6, 0x01) + put(b, 24, 0, 0, 0, 0x4, 0x8F) + put(b, 0, 1, 37, 2, 0x7, 0x48) + put(b, 8, 1, 0, 0, 0x7, 0x00) + put(b, 16, 1, 44, 2, 0xE, 0x12) + put(b, 17, 1, 0, 0, 0xE, 0x12) + put(b, 20, 1, 0, 0, 0xE, 0x24) + put(b, 24, 1, 0, 0, 0xE, 0xB8) + put(b, 28, 1, 0, 0, 0xE, 0xA4) + put(b, 0, 3, 49, 4, 0x9, 0x08) + put(b, 8, 3, 49, 4, 0xE, 0x93) + put(b, 16, 3, 56, 4, 0xE, 0xD3) + put(b, 24, 2, 49, 3, 0xF, 0x03) + put(b, 32, 2, 51, 3, 0xF, 0x90) + put(b, 40, 2, 53, 3, 0xF, 0x06) + put(b, 40, 3, 61, 4, 0x9, 0x04) + put(b, 44, 0, 49, 5, 0xE, 0x53) + put(b, 48, 0, 0, 0, 0xD, 0x00) + return T.write_mod("basic", samples(), [0, 1], [a, b]) + + +def song_loops(): + a, b, c = empty(4), empty(4), empty(4) + put(a, 0, 0, 49, 1, 0xF, 0x04) + put(a, 4, 0, 0, 0, 0xE, 0x60) + put(a, 5, 1, 61, 2) + put(a, 8, 0, 53, 1, 0xE, 0x62) + put(a, 16, 0, 56, 1, 0xE, 0xE3) + put(a, 17, 2, 37, 3, 0xA, 0x01) + put(a, 32, 0, 0, 0, 0xD, 0x16) + put(b, 16, 0, 61, 1) + put(b, 20, 3, 49, 4, 0xF, 0x70) + put(b, 24, 0, 0, 0, 0xB, 0x02) + put(c, 0, 1, 50, 5) + put(c, 4, 1, 0, 0, 0xB, 0x01) + return T.write_mod("loops", samples(), [0, 1, 2], [a, b, c]) + + +def song_8ch(): + a = empty(8) + for ch in range(8): + put(a, ch * 2, ch, 37 + ch * 5, 1 + ch % 3, 0x8, ch * 32) + put(a, 32, 0, 61, 5, 0xE, 0x84) + put(a, 32, 7, 49, 4, 0x8, 0xFF) + put(a, 63, 0, 0, 0, 0xF, 0x00) + return T.write_mod("eight", samples(), [0], [a], channels=8) + + +def generate(ctx): + cases = [] + for nm, data in (("basic", song_basic()), ("loops", song_loops()), ("8ch", song_8ch())): + ref = T.reference(ctx, data, "mod") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("mod_cases", cases) +