--!strict -- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, -- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or -- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through -- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" -- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). -- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter -- (E0x), PowerPacker-packed files. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Tracker = require("@formats/codecs/Tracker") -- ------------------------------------------------------------------------------------------------ contract local Mod = { name = "mod", category = "music", extensions = { "mod", "m15", "stk", "nst" }, mime = { "audio/x-mod", "audio/mod" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, } export type DecodeOptions = { maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) } export type EncodeOptions = {} -- ------------------------------------------------------------------------------------------------ constants local Pcm = Tracker.Pcm local Tables = Tracker.Tables local FIXED: { [string]: number } = { ["M.K."] = 4, ["M!K!"] = 4, ["M&K!"] = 4, ["N.T."] = 4, ["FLT4"] = 4, ["FLT8"] = 8, ["CD81"] = 8, ["OKTA"] = 8, ["OCTA"] = 8, ["EXO4"] = 4, ["EXO8"] = 8, } -- channels from the 4-byte signature at 1080, or nil local function signatureChannels(sig: string): number? local fixed = FIXED[sig] if fixed then return fixed end local d = string.match(sig, "^(%d)CHN$") if d then local n = tonumber(d) :: number return if n >= 1 then n else nil end local dd = string.match(sig, "^(%d%d)C[HN]$") if dd then local n = tonumber(dd) :: number return if n >= 1 and n <= 32 then n else nil end local t = string.match(sig, "^TDZ(%d)$") if t then local n = tonumber(t) :: number return if n >= 1 then n else nil end return nil end -- ------------------------------------------------------------------------------------------------ sniff function Mod.sniff(r: Bytes.Reader): number if r:size() < 1084 then return 0 end local sig = r:peek(4, 1080) if signatureChannels(sig) then return 0.8 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local maxBytes = opts and opts.maxBytes or 2 ^ 26 local size = r:size() local sig = if size >= 1084 then r:peek(4, 1080) else "" local channels = signatureChannels(sig) local nsamples = 31 if not channels then -- a 15-sample Soundtracker module (no signature): only when the header is plausible nsamples, channels = 15, 4 end local nch = channels :: number local m = Tracker.newModule("mod", nch) m.title = r:fixed(20) local lengths: { number } = {} for i = 1, nsamples do local s = Tracker.newSample(r:fixed(22)) local len = r:u16be() * 2 local ft = r:u8() % 16 local vol = r:u8() local ls = r:u16be() * 2 local ll = r:u16be() * 2 if r.err then return nil, r.err end if nsamples == 15 and (vol > 64 or ft ~= 0) then return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") end s.finetune = (if ft >= 8 then ft - 16 else ft) * 16 s.volume = math.min(vol, 64) s.bits = 8 if ll > 2 then s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 end lengths[i] = len m.samples[i] = s end local songLength = r:u8() local restart = r:u8() local order: { number } = {} local maxPat = 0 for i = 1, 128 do local p = r:u8() order[i] = p maxPat = math.max(maxPat, p) end if r.err then return nil, r.err end if songLength == 0 or songLength > 128 or maxPat >= 128 then return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") end if nsamples == 31 then r:skip(4) end for i = 1, songLength do m.order[i] = order[i] end m.restart = if restart < songLength then restart else 0 m.meta.signature = if nsamples == 31 then sig else nil m.flags.amigaLimits = nch == 4 -- patterns local npat = maxPat + 1 local patBytes = 64 * nch * 4 if not r:need(npat * patBytes) then return nil, r.err end local buf = r.buf for p = 0, npat - 1 do local pat = Tracker.newPattern(64, nch) local base = r.pos + p * patBytes local d = pat.data for i = 0, 64 * nch - 1 do local o = base + i * 4 local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) local period = (b0 % 16) * 256 + b1 local ins = (b0 // 16) * 16 + b2 // 16 local q = i * 5 buffer.writeu8(d, q, Tables.periodToNote(period)) buffer.writeu8(d, q + 1, ins) buffer.writeu8(d, q + 3, b2 % 16) buffer.writeu8(d, q + 4, b3) end m.patterns[p + 1] = pat end r:skip(npat * patBytes) -- sample data (8-bit signed; the last samples of a truncated file are cut short) local total = 0 for i = 1, nsamples do local s = m.samples[i] local len = math.min(lengths[i], r:remaining()) total += len * 4 if total > maxBytes then return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") end local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) if not data then return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) end r:skip(len) s.data, s.length = data, len if s.loopEnd > len then s.loopEnd = len if s.loopEnd - s.loopStart < 2 then s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 end end end m.meta.source = { format = "mod", samples = nsamples } m.render = Tracker.renderMethod local ok, verr = Tracker.validate(m) if not ok then return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") end return m, nil end -- ------------------------------------------------------------------------------------------------ encode local function writeName(w: Bytes.Writer, s: string, n: number) local t = string.sub(s or "", 1, n) w:string(t) w:fill(0, n - #t) end -- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to -- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) local ok, verr = Tracker.validate(m) if not ok then return nil, verr end if m.format ~= "mod" and m.format ~= "xm" then return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") end local nch = m.channels if nch > 32 then return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") end -- the sample for each instrument number local smpOf: { any } = {} if m.format == "xm" then for i, ins in m.instruments do local first = 0 for n = 1, 120 do local s = ins.sampleMap[n] if s ~= 0 then if first ~= 0 and s ~= first then return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") end first = s end end smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) end else for i, s in m.samples do smpOf[i] = s end end if #smpOf > 31 then return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") end local order: { number } = {} for _, o in m.order do if o == 255 then break elseif o ~= 254 then table.insert(order, o) end end if #order == 0 or #order > 128 then return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") end local npat = #m.patterns if npat > 100 then return nil, Err.new(Err.ARG, "too many patterns for MOD") end for p, pat in m.patterns do if pat.rows ~= 64 then return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") end end local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) writeName(w, m.title or "", 20) local datas: { buffer } = {} for i = 1, 31 do local s = smpOf[i] if s then local len = math.min(s.length, 131070) local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) if s.channels == 2 then -- mix stereo samples down local mono = buffer.create(len * 4) for k = 0, len - 1 do buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) end pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) end local even = len + len % 2 local padded = buffer.create(even) buffer.copy(padded, 0, pcm, 0, len) datas[i] = padded writeName(w, s.name or "", 22) w:u16be(even // 2) local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) w:u8(ft % 16) w:u8(math.clamp(math.floor(s.volume), 0, 64)) if s.loopType > 0 and s.loopEnd <= even then w:u16be(s.loopStart // 2) w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2)) else w:u16be(0) w:u16be(1) end else w:fill(0, 22) w:u16be(0) w:u8(0) w:u8(0) w:u16be(0) w:u16be(1) end end w:u8(#order) w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127) for i = 1, 128 do w:u8(order[i] or 0) end local sig if nch == 4 then sig = if npat > 64 then "M!K!" else "M.K." elseif nch < 10 then sig = nch .. "CHN" else sig = nch .. "CH" end w:string(sig) for p = 1, npat do local d = m.patterns[p].data for i = 0, 64 * nch - 1 do local q = i * 5 local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0 if period > 4095 then period = 0 end if fx > 15 then fx, param = 0, 0 end if ins > 31 then ins = 0 end w:u8((ins // 16) * 16 + period // 256) w:u8(period % 256) w:u8((ins % 16) * 16 + fx) w:u8(param) end end for i = 1, 31 do if datas[i] then w:bytes(datas[i]) end end return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ open -- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Mod.decode(r, opts) if not m then return nil, err end return Tracker.render(m, opts) end return Mod