561 lines
16 KiB
Luau
561 lines
16 KiB
Luau
--!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
|