diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 450e651..5ddcb80 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,6 +10,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | | music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | | music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | +| music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 222ae4e..65f9734 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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 diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau index 7f34e11..bf0742d 100644 --- a/src/Formats/codecs/Tracker/Player.luau +++ b/src/Formats/codecs/Tracker/Player.luau @@ -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 diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau new file mode 100644 index 0000000..d2cbafa --- /dev/null +++ b/src/Formats/music/xm/init.luau @@ -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 diff --git a/tests/music/xm.luau b/tests/music/xm.luau new file mode 100644 index 0000000..2e47118 --- /dev/null +++ b/tests/music/xm.luau @@ -0,0 +1,77 @@ +-- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Xm = require("@formats/music/xm") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/xm_cases") + +local t = T.suite("xm") + +t:eq(Xm.name, "xm", "name") +t:eq(Xm.category, "music", "category") +t:check(Xm.caps.decode and Xm.caps.encode, "caps") + +local function load(data: string): any + return Xm.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 1.0, envErr = 1.0, 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(Xm.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("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr 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.envErr < THRESH.envErr, 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: XM -> XM gives the same bytes back (the fixtures use the FT2 layout) + local out, werr = Xm.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Xm.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 = Xm.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/xm.py b/tools/fixtures/xm.py new file mode 100644 index 0000000..fd40898 --- /dev/null +++ b/tools/fixtures/xm.py @@ -0,0 +1,161 @@ +# XM fixtures (tools/fixtures.py): generated FastTracker 2 modules exercising instruments (envelopes, fadeout, +# auto-vibrato, keymaps, 16-bit and ping-pong samples) and the effects, rendered by openmpt123. +# tests/gen/xm_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"] + +OFF = 97 +Gx, Hx, Kx, Lx, Px, Rx, Tx, Xx = 16, 17, 20, 21, 25, 27, 29, 33 + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=0, fx=0, param=0): + p[row][ch] = (note, ins, vol, fx, param) + + +def instruments(): + sine = {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + tri = {"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 48, "pan": 96, "relnote": 12, "finetune": -20, + "loop": (0, 32, 1)} + saw16 = {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 56, "pan": 160, + "loop": (0, 128, 1)} + ping = {"name": "ping", "data": T.s8(T.synth("saw", 200, 200, 0.7)), "volume": 64, "pan": 128, "finetune": 30, + "loop": (20, 150, 2)} + noise = {"name": "noise", "data": T.s8(T.synth("noise", 5000, 1, 0.7, decay=1500)), "volume": 60, "pan": 128} + square = {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + return [ + {"name": "env", "samples": [sine], "volenv": {"points": [(0, 0), (4, 64), (10, 40), (30, 20), (40, 0)], "sustain": 2}, + "fadeout": 1024}, + {"name": "panloop", "samples": [square], "panenv": {"points": [(0, 0), (8, 64), (16, 0)], "loop": (0, 2)}, + "volenv": {"points": [(0, 64), (20, 48), (60, 32)], "loop": (1, 2)}, "fadeout": 512}, + {"name": "autovib", "samples": [saw16], "vib": (0, 10, 8, 6)}, + {"name": "multi", "samples": [sine, tri], "keymap": [0] * 48 + [1] * 48}, + {"name": "ping", "samples": [ping]}, + {"name": "noise", "samples": [noise]}, + {"name": "sq vib", "samples": [square], "vib": (1, 0, 4, 20)}, + {"name": "empty"}, + ] + + +def song_instruments(): + a, b = empty(4), empty(4) + put(a, 0, 0, 49, 1) + put(a, 12, 0, OFF) + put(a, 20, 0, 56, 1) + put(a, 24, 0, 0, 0, 0, Kx, 3) + put(a, 32, 0, 61, 1) + put(a, 33, 0, 0, 0, 0, Lx, 20) + put(a, 40, 0, 63) + put(a, 44, 0, OFF) + put(a, 48, 0, 0, 1) + put(a, 0, 1, 37, 2) + put(a, 30, 1, OFF) + put(a, 40, 1, 44, 2) + put(a, 0, 2, 49, 3) + put(a, 32, 2, 56, 3) + put(a, 8, 3, 37, 4) + put(a, 16, 3, 61, 4) + put(a, 24, 3, 73, 4) + put(a, 32, 3, 85, 4) + put(a, 40, 3, 49, 5) + put(a, 52, 3, 61, 5) + put(a, 60, 3, 61, 8) + put(b, 0, 0, 49, 7) + put(b, 0, 1, 56, 3, 0x30) + put(b, 8, 1, 0, 3) + put(b, 16, 2, 61, 6, 0x40) + put(b, 20, 2, 61, 6, 0, 0x9, 0x08) + put(b, 24, 2, 61, 6, 0, 0xE, 0x93) + put(b, 32, 3, 49, 1) + put(b, 36, 3, 61) + put(b, 40, 3, OFF) + put(b, 44, 3, 63) + put(b, 48, 0, 0, 0, 0, 0xD, 0x00) + return T.write_xm("instruments", instruments(), [0, 1], [a, b], 4) + + +def song_effects(linear=True): + a, b = empty(6), empty(6, 48) + put(a, 0, 0, 49, 7, 0, 0x1, 0x04) + put(a, 4, 0, 0, 0, 0, 0x1, 0x00) + put(a, 8, 0, 0, 0, 0, 0x2, 0x08) + put(a, 12, 0, 0, 0, 0, 0xE, 0x18) + put(a, 13, 0, 0, 0, 0, 0xE, 0x10) + put(a, 14, 0, 0, 0, 0, 0xE, 0x2F) + put(a, 16, 0, 0, 0, 0, Xx, 0x1F) + put(a, 17, 0, 0, 0, 0, Xx, 0x10) + put(a, 18, 0, 0, 0, 0, Xx, 0x28) + put(a, 20, 0, 49, 7, 0, 0x3, 0x10) + put(a, 21, 0, 61, 0, 0, 0x3, 0x00) + put(a, 24, 0, 0, 0, 0, 0x5, 0x02) + put(a, 28, 0, 56, 0, 0, 0x4, 0x48) + put(a, 32, 0, 0, 0, 0, 0x6, 0x20) + put(a, 36, 0, 0, 0, 0, 0x7, 0x6F) + put(a, 40, 0, 0, 0, 0, Tx, 0x21) + put(a, 44, 0, 0, 0, 0, 0xA, 0x0F) + put(a, 46, 0, 0, 0, 0, 0xE, 0xA8) + put(a, 48, 0, 61, 7, 0, 0x0, 0x37) + put(a, 52, 0, 0, 0, 0, 0xE, 0xC3) + # channel 1: the volume column + put(a, 0, 1, 56, 6, 0x30) + put(a, 4, 1, 0, 0, 0x64) + put(a, 8, 1, 0, 0, 0x73) + put(a, 12, 1, 0, 0, 0x85) + put(a, 13, 1, 0, 0, 0x9A) + put(a, 16, 1, 0, 0, 0xA6) + put(a, 17, 1, 0, 0, 0xB8) + put(a, 24, 1, 0, 0, 0xC2) + put(a, 28, 1, 0, 0, 0xE4) + put(a, 32, 1, 0, 0, 0xD6) + put(a, 36, 1, 61, 0, 0xF8) + put(a, 40, 1, 49, 0, 0xF0) + # channel 2: panning, retrig, offset, delay + put(a, 0, 2, 61, 2, 0, 0x8, 0x20) + put(a, 8, 2, 0, 0, 0, Px, 0x30) + put(a, 16, 2, 0, 0, 0, Px, 0x06) + put(a, 24, 2, 61, 6, 0, Rx, 0x83) + put(a, 32, 2, 61, 6, 0, Rx, 0x32) + put(a, 40, 2, 61, 6, 0, 0x9, 0x06) + put(a, 48, 2, 61, 6, 0, 0xE, 0xD3) + put(a, 56, 2, 61, 6, 0x20, 0xE, 0xC2) + # channel 3: global volume, pattern loop, pattern delay, speed / tempo + put(a, 0, 3, 37, 3, 0, Gx, 0x30) + put(a, 8, 3, 0, 0, 0, Hx, 0x02) + put(a, 16, 3, 0, 0, 0, Hx, 0x40) + put(a, 24, 3, 0, 0, 0, 0xE, 0x60) + put(a, 26, 3, 0, 0, 0, 0xE, 0x62) + put(a, 32, 3, 0, 0, 0, 0xE, 0xE2) + put(a, 40, 3, 0, 0, 0, 0xF, 0x05) + put(a, 48, 3, 0, 0, 0, 0xF, 0x96) + # channel 4 / 5: an instrument change without a note, an empty instrument, a note after key off + put(a, 0, 4, 49, 1) + put(a, 8, 4, 0, 2) + put(a, 16, 4, OFF) + put(a, 24, 4, 51) + put(a, 32, 4, 51, 8) + put(a, 40, 4, 53, 1) + put(a, 4, 5, 73, 5, 0, 0xE, 0x80) + put(a, 20, 5, 0, 0, 0, 0x8, 0xC0) + # pattern b (48 rows): portamento in the other direction, arpeggio, a break and a jump back (song loop) + put(b, 0, 0, 73, 7, 0, 0x4, 0x00) + put(b, 0, 1, 61, 4) + put(b, 4, 1, 0, 0, 0, 0x0, 0x47) + put(b, 16, 1, 25, 4, 0, 0x2, 0x10) + put(b, 32, 0, 0, 0, 0, 0xB, 0x01) + return T.write_xm("effects", instruments(), [0, 1], [a, b], 6, speed=5, tempo=130, linear=linear, restart=1) + + +def generate(ctx): + cases = [] + for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))): + ref = T.reference(ctx, data, "xm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("xm_cases", cases)