ws-music: music/xm read/write/render (FT2 / OpenMPT instrument, tremor, envelope and E6x quirks), tone portamento never starts MOD/XM notes

This commit is contained in:
4DBug committed 2026-10-31 09:18:07 -05:00
1 parent 6c49ab38dd
commit 8b8b64885f
6 files changed
+858 -24

No files matched your search

+12
View File
@@ -74,6 +74,18 @@ local list: { Entry } = {
return require("@formats/music/sf2")
end,
},
{
name = "xm",
category = "music",
path = "music/xm",
extensions = { "xm" },
mime = { "audio/xm", "audio/x-xm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
load = function()
return require("@formats/music/xm")
end,
},
}
return list
+47 -24
View File
@@ -199,6 +199,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any
patDelayRep = 0,
fineDelay = 0,
jumpOrd = -1,
ft2BreakPos = 0,
breakRow = -1,
loopJump = -1,
ended = false,
@@ -242,6 +243,9 @@ function Player.masterGain(m: any, fmt: number): number
elseif fmt == S3M then
return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the master volume, 64 = 0.5
end
if fmt == XM then
return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count
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
@@ -295,6 +299,7 @@ local function advanceRow(st: any)
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
st.ft2BreakPos = 0
Player.startOrder(st, o, r)
return
end
@@ -309,7 +314,10 @@ local function advanceRow(st: any)
end
st.row += 1
if st.row >= st.pat.rows then
Player.startOrder(st, st.ord + 1, 0)
-- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep)
local r = if st.fmt == XM then st.ft2BreakPos else 0
st.ft2BreakPos = 0
Player.startOrder(st, st.ord + 1, r)
end
end
@@ -428,7 +436,7 @@ local function cutVoice(v: any)
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 function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any)
local v = c.voice
if v == nil or v.bg then
v = allocVoice(st)
@@ -456,9 +464,11 @@ local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, i
v.base = base
st.age += 1
v.order = st.age
if not keepEnv then
v.keyOn = true
v.fading = false
if keepEnv ~= true then
if keepEnv ~= "release" then
v.keyOn = true
v.fading = false
end
v.fade = 65536
v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0
v.avPos, v.avAmp = 0, 0
@@ -612,8 +622,9 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb
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)
if f == XM and v then
-- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no
-- fadeout); the new instrument applies from the next note
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
@@ -641,7 +652,8 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb
local ft = c.finetune
local period, base = notePeriod(st, realNote, smp, ft)
local v = c.voice
if porta and v and v.active then
if porta and ((v and v.active) or f == MOD or f == XM) then
-- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it)
c.target = period
if st.fmt == IT or st.fmt == S3M then
c.note = note
@@ -650,8 +662,15 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb
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
-- FT2: a note without an instrument number restarts the sample only (envelopes, key off and
-- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start
-- over but a key off stays
local keep: any = false
if f == XM and insIdx == 0 and c.voice ~= nil then
keep = if c.voice.ins == ins then true else "release"
end
c.triggered = true
c.tremorOn = 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
@@ -902,17 +921,19 @@ local function fxModXm(st: any, c: any, tick: number)
elseif c.loopCount == 0 then
c.loopCount = y
st.loopJump = c.loopRow
st.ft2BreakPos = c.loopRow
else
c.loopCount -= 1
if c.loopCount > 0 then
st.loopJump = c.loopRow
end
st.ft2BreakPos = c.loopRow
end
end
elseif x == 7 then
c.tremWave = y % 8
elseif x == 8 then
if tick == 0 and not xm then
if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it
c.pan = y * 17
c.surround = false
end
@@ -1051,8 +1072,9 @@ local function fxModXm(st: any, c: any, tick: number)
-- 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.tremorCount %= on + off
c.tremorOn = c.tremorCount < on
c.tremorCount += 1
end
end
@@ -1173,8 +1195,9 @@ local function fxS3mIt(st: any, c: any, tick: number)
on, off = on + 1, off + 1
end
on, off = max(on, 1), max(off, 1)
c.tremorCount = (c.tremorCount + 1) % (on + off)
c.tremorCount %= on + off
c.tremorOn = c.tremorCount < on
c.tremorCount += 1
end
elseif fx == 10 then -- J arpeggio
local p = mem(st, c, "mArp", param)
@@ -1550,9 +1573,7 @@ local function runEffects(st: any, c: any, tick: number)
if fx ~= 7 then
c.tremDelta = 0
end
if fx ~= 29 then
c.tremorOn = true
end
-- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2)
else
if fx ~= 18 then
c.tremDelta = 0
@@ -1584,9 +1605,6 @@ local function processRow(st: any)
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
@@ -1600,7 +1618,7 @@ local function processRow(st: any)
local _ = m
end
local function updateEnvelope(env: any, pos: number, keyOn: boolean): (number, number, boolean)
local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean)
-- returns value, next position, ended
local ticks, values = env.ticks, env.values
local n = #ticks
@@ -1626,9 +1644,14 @@ local function updateEnvelope(env: any, pos: number, keyOn: boolean): (number, n
end
local nextPos = pos + 1
local ended = false
if keyOn and env.sustain and ticks[env.susEnd] and nextPos > ticks[env.susEnd] then
-- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on)
-- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks),
-- IT after playing it (end - start + 1 ticks)
local se, le = ticks[env.susEnd], ticks[env.loopEnd]
local over = if it then 1 else 0
if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then
nextPos = ticks[env.susStart] or nextPos
elseif env.loop and ticks[env.loopEnd] and nextPos > ticks[env.loopEnd] then
elseif env.loop and le and pos <= le and nextPos >= le + over then
nextPos = ticks[env.loopStart] or nextPos
elseif nextPos > ticks[n] then
nextPos = ticks[n]
@@ -1646,7 +1669,7 @@ local function updateVoice(st: any, v: any)
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)
local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it)
envVol, v.volEnvPos = val, np
if ended and it then
if val <= 0 then
@@ -1658,12 +1681,12 @@ local function updateVoice(st: any, v: any)
end
e = ins.panEnv
if e and e.enabled and v.panEnvOn then
local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn)
local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it)
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)
local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it)
v.pitchEnvPos = np
if e.filter then
filterEnv = val
+560
View File
@@ -0,0 +1,560 @@
--!strict
-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker /
-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/Tracker Module and
-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit
-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga
-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files
-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies).
-- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write.
-- ------------------------------------------------------------------------------------------------ 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 Xm = {
name = "xm",
category = "music",
extensions = { "xm" },
mime = { "audio/xm", "audio/x-xm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
export type EncodeOptions = {
tracker: string?, -- the tracker name field (default: the source file's, else "formats-luau")
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "Extended Module: "
local Pcm = Tracker.Pcm
-- ------------------------------------------------------------------------------------------------ sniff
function Xm.sniff(r: Bytes.Reader): number
return if r:peek(17) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function readEnvelope(r: Bytes.Reader): ({ number }, { number })
local xs, ys = {}, {}
for i = 1, 12 do
xs[i] = r:u16le()
ys[i] = r:u16le()
end
return xs, ys
end
local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any
local e = Tracker.newEnvelope()
n = math.min(n, 12)
for i = 1, n do
e.ticks[i] = xs[i]
e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64)
end
e.enabled = bit32.band(typ, 1) ~= 0 and n > 0
e.sustain = bit32.band(typ, 2) ~= 0
e.loop = bit32.band(typ, 4) ~= 0
e.susStart, e.susEnd = sus + 1, sus + 1
e.loopStart, e.loopEnd = ls + 1, le + 1
-- the raw fields, for a faithful re-save
e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n }
return e
end
function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r:peek(17) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "no XM signature")
end
r:skip(17)
local title = r:fixed(20)
r:skip(1)
local tracker = r:fixed(20)
local version = r:u16le()
local hdrStart = r:tell()
local hdrSize = r:u32le()
local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le()
local orders = {}
for i = 1, 256 do
orders[i] = r:u8()
end
if r.err then
return nil, r.err
end
if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then
return nil, Err.new(Err.CORRUPT, "bad header counts")
end
if version < 0x0104 then
return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version))
end
local m = Tracker.newModule("xm", nch)
m.title = title
m.speed = if speed > 0 and speed < 256 then speed else 6
m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125
m.linear = bit32.band(flags, 1) ~= 0
m.restart = restart
for i = 1, songLen do
m.order[i] = orders[i]
end
m.meta.tracker = tracker
m.meta.source = { format = "xm", tracker = tracker, version = version }
-- patterns
if not r:seek(hdrStart + hdrSize) then
return nil, r.err
end
for p = 1, npat do
local start = r:tell()
local plen = r:u32le()
r:u8()
local rows = r:u16le()
local psize = r:u16le()
if r.err then
return nil, r.err
end
if rows < 1 or rows > 256 then
return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos)
end
r:seek(start + plen)
local pat = Tracker.newPattern(rows, nch)
m.patterns[p] = pat
local pr = r:slice(psize)
if r.err then
return nil, r.err
end
local d = pat.data
if psize > 0 then
for i = 0, rows * nch - 1 do
local b = pr:u8()
local note, ins, vol, fx, param = 0, 0, 0, 0, 0
if b >= 128 then
if bit32.band(b, 1) ~= 0 then
note = pr:u8()
end
if bit32.band(b, 2) ~= 0 then
ins = pr:u8()
end
if bit32.band(b, 4) ~= 0 then
vol = pr:u8()
end
if bit32.band(b, 8) ~= 0 then
fx = pr:u8()
end
if bit32.band(b, 16) ~= 0 then
param = pr:u8()
end
else
note, ins, vol, fx, param = b, pr:u8(), pr:u8(), pr:u8(), pr:u8()
end
if pr.err then
break -- a short pattern: the rest stays empty
end
if note == 97 then
note = 255
elseif note > 96 then
note = 0
end
if fx > 35 then
fx, param = 0, 0
end
local o = i * 5
buffer.writeu8(d, o, note)
buffer.writeu8(d, o + 1, ins)
buffer.writeu8(d, o + 2, vol)
buffer.writeu8(d, o + 3, fx)
buffer.writeu8(d, o + 4, param)
end
end
end
-- instruments and their samples
local total = 0
for i = 1, nins do
local start = r:tell()
local isize = r:u32le()
local ins = Tracker.newInstrument(r:fixed(22))
r:u8()
local ns = r:u16le()
if r.err then
-- a file cut inside the instruments: keep what was read
r.err = nil
break
end
m.instruments[i] = ins
ins.samples = {}
if ns == 0 then
r:seek(start + math.max(isize, 29))
continue
end
if ns > 256 then
return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples")
end
local shSize = r:u32le()
local keymap = {}
for n = 1, 96 do
keymap[n] = r:u8()
end
local vx, vy = readEnvelope(r)
local px, py = readEnvelope(r)
local nv, np = r:u8(), r:u8()
local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
local vt, pt = r:u8(), r:u8()
ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8()
ins.fadeout = r:u16le()
if r.err then
return nil, r.err
end
ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false)
ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true)
ins.headerSize = isize
r:seek(start + isize)
local base = #m.samples
local heads = {}
for k = 1, ns do
local hs = r:tell()
local len, ls, ll = r:u32le(), r:u32le(), r:u32le()
local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8()
local nm = r:fixed(22)
r:seek(hs + math.max(shSize, 40))
heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm }
end
if r.err then
return nil, r.err
end
for k = 1, ns do
local h = heads[k]
local s = Tracker.newSample(h.name)
local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8
local bps = bits // 8
s.bits = bits
s.volume = math.min(h.vol, 64)
s.finetune = h.ft
s.relativeNote = h.rel
s.pan = h.pan
local frames = h.len // bps
if h.res == 0xAD then
-- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length)
local bytes = 16 + (h.len + 1) // 2
r:skip(math.min(bytes, r:remaining()))
frames = h.len
s.data = buffer.create(frames * 4)
else
local avail = r:remaining() // bps
local got = math.min(frames, avail)
total += got * 4
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
end
local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true })
r:skip(got * bps)
s.data = data or buffer.create(0)
frames = if data then got else 0
end
s.length = frames
local lt = h.typ % 4
if lt == 3 then
lt = 2
end
if lt > 0 and h.ll > 0 then
s.loopStart = h.ls // bps
s.loopEnd = (h.ls + h.ll) // bps
s.loopType = lt
end
m.samples[base + k] = s
table.insert(ins.samples, base + k)
end
for n = 1, 120 do
local k = keymap[math.min(n, 96)]
ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0
end
ins.keymap = keymap
end
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
-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? }
local function instrumentsOf(m: any): ({ any }?, string?)
local out = {}
if m.format == "mod" then
for i, s in m.samples do
local km = table.create(96, 0)
out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil }
end
return out
end
for i, ins in m.instruments do
local list: { number } = {}
if type(ins.samples) == "table" then
for _, g in ins.samples do
table.insert(list, g)
end
end
local index: { [number]: number } = {}
for k, g in list do
index[g] = k - 1
end
local km = table.create(96, 0)
for n = 1, 96 do
local g = ins.sampleMap[n] or 0
if g > 0 and m.samples[g] then
if index[g] == nil then
table.insert(list, g)
index[g] = #list - 1
end
km[n] = index[g]
end
end
if #list > 255 then
return nil, "instrument " .. i .. " uses more than 255 samples"
end
local smps = {}
for k, g in list do
smps[k] = m.samples[g] or Tracker.newSample()
end
out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins }
end
return out
end
local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean)
local n = if e then math.min(#e.ticks, 12) else 0
for i = 1, 12 do
if i <= n then
w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535))
w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64))
else
w:u32le(0)
end
end
end
-- envelope count, type, sustain, loop start, loop end
local function envelopeFields(e: any): (number, number, number, number, number)
if not e then
return 0, 0, 0, 0, 0
end
local n = math.min(#e.ticks, 12)
local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0)
local raw = e.raw
if raw and raw.type % 8 == typ then
typ = raw.type -- keep unknown bits
end
local function idx(v: number): number
return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1))
end
local sus = idx(e.susStart)
local ls, le = idx(e.loopStart), idx(e.loopEnd)
if raw and n == 0 then
sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd
end
return n, typ, sus, ls, le
end
-- encode(module, opts) -> XM bytes ("xm" or "mod" modules)
function Xm.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 ~= "xm" and m.format ~= "mod" then
return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")")
end
local nch = m.channels
if nch > 64 then
return nil, Err.new(Err.ARG, "XM holds at most 64 channels")
end
local insts, ierr = instrumentsOf(m)
if not insts then
return nil, Err.new(Err.ARG, ierr or "bad instruments")
end
if #insts > 128 then
return nil, Err.new(Err.ARG, "XM holds at most 128 instruments")
end
if #m.patterns > 256 then
return nil, Err.new(Err.ARG, "XM holds at most 256 patterns")
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 > 256 then
return nil, Err.new(Err.ARG, "XM holds at most 256 order entries")
end
local w = Bytes.writer(65536)
w:string(MAGIC)
writeName(w, m.title, 20)
w:u8(0x1A)
writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "formats-luau", 20)
w:u16le(0x0104)
w:u32le(276)
w:u16le(#order)
w:u16le(if m.restart < #order then m.restart else 0)
w:u16le(nch)
w:u16le(#m.patterns)
w:u16le(#insts)
w:u16le(if m.linear then 1 else 0)
w:u16le(m.speed)
w:u16le(math.clamp(math.floor(m.tempo), 32, 999))
for i = 1, 256 do
w:u8(order[i] or 0)
end
-- patterns (every cell packed, as FT2-compatible writers may)
for _, pat in m.patterns do
local pk = Bytes.writer(pat.rows * nch * 2)
local d = pat.data
for i = 0, pat.rows * nch - 1 do
local o = i * 5
local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
if note == 255 then
note = 97
elseif note > 96 then
note = 0
end
if m.format == "mod" then
vol = 0
if fx > 15 then
fx, param = 0, 0
end
end
if ins > 128 then
ins = 0
end
local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0)
pk:u8(flags)
if note > 0 then
pk:u8(note)
end
if ins > 0 then
pk:u8(ins)
end
if vol > 0 then
pk:u8(vol)
end
if fx > 0 then
pk:u8(fx)
end
if param > 0 then
pk:u8(param)
end
end
local data = pk:finish()
if buffer.len(data) > 65535 then
return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB")
end
w:u32le(9)
w:u8(0)
w:u16le(pat.rows)
w:u16le(buffer.len(data))
w:bytes(data)
end
-- instruments
for _, it in insts do
local ins = it.ins
local smps = it.samples
if #smps == 0 then
w:u32le(29)
writeName(w, it.name, 22)
w:u8(0)
w:u16le(0)
continue
end
w:u32le(263)
writeName(w, it.name, 22)
w:u8(0)
w:u16le(#smps)
w:u32le(40)
for n = 1, 96 do
w:u8(it.keymap[n])
end
local ve, pe = ins and ins.volEnv, ins and ins.panEnv
writeEnvelope(w, ve, false)
writeEnvelope(w, pe, true)
local vn, vt, vs, vls, vle = envelopeFields(ve)
local pn, pt, ps, pls, ple = envelopeFields(pe)
w:u8(vn)
w:u8(pn)
w:u8(vs)
w:u8(vls)
w:u8(vle)
w:u8(ps)
w:u8(pls)
w:u8(ple)
w:u8(vt)
w:u8(pt)
w:u8(ins and ins.vibType or 0)
w:u8(ins and ins.vibSweep or 0)
w:u8(ins and ins.vibDepth or 0)
w:u8(ins and ins.vibRate or 0)
w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0)
w:fill(0, 22)
local datas = {}
for k, s in smps do
local mono = s.data
if s.channels == 2 then
mono = buffer.create(s.length * 4)
for f = 0, s.length - 1 do
buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2)
end
end
local bits = if s.bits == 16 then 16 else 8
local bps = bits // 8
datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true })
local typ = (if bits == 16 then 16 else 0)
local ls, ll = 0, 0
if s.loopType > 0 then
typ += s.loopType
ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps
end
local ft = s.finetune
local rel = s.relativeNote
if m.format == "mod" then
rel = 0
end
w:u32le(s.length * bps)
w:u32le(ls)
w:u32le(ll)
w:u8(math.clamp(math.floor(s.volume), 0, 64))
w:u8(math.clamp(math.floor(ft), -128, 127) % 256)
w:u8(typ)
w:u8(math.clamp(math.floor(s.pan or 128), 0, 255))
w:u8(math.clamp(math.floor(rel), -128, 127) % 256)
w:u8(0)
writeName(w, s.name, 22)
end
for _, dd in datas do
w:bytes(dd)
end
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Xm.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Xm