--!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?, raw: any?, -- format-specific fields kept for a faithful re-save (XM) } 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(s0: any, e0: any, t0: any, len: number): (number, number, number) if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then return 0, 0, 0 end local s: number = math.floor(math.clamp(s0, 0, len)) local e: number = math.floor(math.clamp(e0, 0, len)) local t: number = math.floor(t0) if e - s < 1 or t == 0 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, nil 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, nil 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