diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..891c26c 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -76,6 +76,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` | | music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | | music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | +| music | mtm | .mtm | yes | - | render: true, channels: 1, 32 | `tests/music/mtm.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` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..17eb986 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,7 @@ | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `src/Formats/music/{mtm,669,stm,ult,okt,med,ptm,far,umx}/`, `src/Formats/codecs/audio/Tracker/Load.luau` (loaders and effect conversions ported from OpenMPT's Load_*.cpp / ModCommand / UMXTools) | libopenmpt 0.8.9 (OpenMPT Project Developers, Olivier Lapicque) | BSD-3-Clause: [openmpt-LICENSE.txt](openmpt-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/openmpt-LICENSE.txt b/licenses/openmpt-LICENSE.txt new file mode 100644 index 0000000..6f8a33d --- /dev/null +++ b/licenses/openmpt-LICENSE.txt @@ -0,0 +1,25 @@ +Copyright (c) 2004-2026, OpenMPT Project Developers and Contributors +Copyright (c) 1997-2003, Olivier Lapicque +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the OpenMPT project nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..af40316 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -866,6 +866,18 @@ local list: { Entry } = { return require("@formats/music/mod") end, }, + { + name = "mtm", + category = "music", + path = "music/mtm", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/mtm") + end, + }, { name = "s3m", category = "music", diff --git a/src/Formats/codecs/audio/Tracker/Load.luau b/src/Formats/codecs/audio/Tracker/Load.luau new file mode 100644 index 0000000..baaf81a --- /dev/null +++ b/src/Formats/codecs/audio/Tracker/Load.luau @@ -0,0 +1,287 @@ +--!strict +-- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the +-- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders +-- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter +-- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers +-- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence, +-- licenses/openmpt-LICENSE.txt), reduced to what the engine plays. +local Err = require("@formats/core/Err") +local Player = require("@formats/codecs/audio/Tracker/Player") +local Pcm = require("@formats/codecs/audio/Tracker/Pcm") +local Tables = require("@formats/codecs/audio/Tracker/Tables") + +local Load = {} + +local EXT = Player.EXT + +-- the S3M / IT letter code of each effect name (engine extension effects included) +local IT: { [string]: number } = { + speed = 1, + jump = 2, + ["break"] = 3, + volslide = 4, + portadown = 5, + portaup = 6, + toneporta = 7, + vibrato = 8, + tremor = 9, + arpeggio = 10, + vibratovol = 11, + toneportavol = 12, + chanvol = 13, + chanvolslide = 14, + offset = 15, + panslide = 16, + retrig = 17, + tremolo = 18, + s3mex = 19, + tempo = 20, + finevibrato = 21, + globalvol = 22, + globalvolslide = 23, + panning8 = 24, + panbrello = 25, + noteslideup = EXT.NOTE_SLIDE_UP, + noteslidedown = EXT.NOTE_SLIDE_DOWN, + noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG, + noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG, + autoportaup = EXT.AUTO_PORTA_UP, + autoportadown = EXT.AUTO_PORTA_DOWN, + freqadjust = EXT.FREQ_ADJUST, +} +Load.IT = IT + +-- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits +local WEIGHT: { [string]: number } = {} +for i, n in + { + "none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8", + "noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup", + "portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig", + "arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo", + "speed", "jump", "break", + } +do + WEIGHT[n] = i +end + +local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } + +-- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand) +function Load.isGlobal(name: string?, param: number): boolean + if name == nil then + return false + end + if GLOBAL[name] then + return true + end + local x = param // 16 + if name == "modex" then + return x == 0 or x == 6 or x == 0xE + elseif name == "s3mex" then + return x == 6 or x == 0xB or x == 0xE + end + return false +end + +-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand) +local MODFX: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", + [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", + [12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide", + [20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor", +} +function Load.modCommand(cmd: number, param: number): (string?, number) + if cmd == 0 and param == 0 then + return nil, 0 + elseif cmd == 0xF and param < 0x20 then + return "speed", param + end + local n = MODFX[cmd] + if n == "break" then + param = (param // 16) * 10 + param % 16 + end + return n, param +end + +-- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there, +-- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision) +function Load.itVolume(name: string?, param: number, force: boolean): number? + if name == "volume" then + return math.min(param, 64) + 1 + elseif name == "volume8" then + if not force and param % 4 ~= 0 then + return nil + end + return (param + 3) // 4 + 1 + elseif name == "portaup" or name == "portadown" then + if not force and (param % 4 ~= 0 or param >= 0xE0) then + return nil + end + return (if name == "portaup" then 115 else 105) + math.min(param // 4, 9) + 1 + elseif name == "toneporta" then + if param >= 0xF0 then + return 193 + 9 + 1 + end + for n = 0, 9 do + local v = Tables.IT_VOLPORTA[n + 1] + if (force and param <= v) or param == v then + return 193 + n + 1 + end + end + return nil + elseif name == "vibrato" then + if force then + param = math.min(param % 16, 9) + elseif param % 16 > 9 or param >= 16 then + return nil + end + return 203 + param % 16 + 1 + elseif name == "panning8" then + return 128 + (if param == 255 then 64 else param // 4) + 1 + elseif name == "volslide" then + local x, y = param // 16, param % 16 + if param == 0 then + return nil + elseif y == 0 then + return 85 + math.min(x, 9) + 1 + elseif x == 0 then + return 95 + math.min(y, 9) + 1 + elseif y == 0xF then + return 65 + math.min(x, 9) + 1 + elseif x == 0xF then + return 75 + math.min(y, 9) + 1 + end + return nil + elseif name == "s3mex" and param // 16 == 8 then + return 128 + (param % 16) * 4 + 2 + 1 + end + return nil +end + +-- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's +-- extended E commands become their S3M equivalents) +function Load.itEffect(name: string?, param: number): (number, number) + if name == nil then + return 0, 0 + end + if name == "modex" then + local x, y = param // 16, param % 16 + if x == 1 then + return IT.portaup, 0xF0 + y + elseif x == 2 then + return IT.portadown, 0xF0 + y + elseif x == 9 then + return IT.retrig, y + elseif x == 0xA then + return IT.volslide, y * 16 + 0xF + elseif x == 0xB then + return IT.volslide, 0xF0 + y + end + local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x] + if s then + return IT.s3mex, s * 16 + y + end + return 0, 0 + end + local code = IT[name] + if code == nil then + return 0, 0 + end + return code, param +end + +-- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param, +-- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the +-- heavier one when both cannot fit (OpenMPT's FillInTwoCommands) +function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number) + if e1 ~= nil and e1 == e2 then + e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) + end + for n = 0, 3 do + local v = Load.itVolume(e1, p1, n > 1) + if e1 == nil or v then + return v or 0, e2, p2, nil, 0 + end + e1, p1, e2, p2 = e2, p2, e1, p1 + end + if (WEIGHT[e1 :: string] or 0) > (WEIGHT[e2 :: string] or 0) then + e1, p1, e2, p2 = e2, p2, e1, p1 + end + return 0, e2, p2, e1, p1 +end + +-- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect +-- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or +-- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's +-- CPattern::WriteEffect). +function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean + local p = m.patterns[pattern + 1] + if not p then + return false + end + local fam = m.engine or m.format + local modLike = fam == "mod" or fam == "xm" + local nch = m.channels + local d = p.data + local guard = 0 + while row >= 0 and row < p.rows and guard < 1024 do + guard += 1 + local c0, c1 = 1, nch + if channel then + c0, c1 = channel, channel + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then + return true + end + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if f == 0 and (not modLike or q == 0) then + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + return true + end + end + if retry == "next" then + row += 1 + elseif retry == "prev" then + row -= 1 + else + return false + end + end + return false +end + +-- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm +-- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames +-- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes). +function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?) + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf)) + local avail = math.max(0, limit - offset) // (nch * bps) + local n = math.max(0, math.min(math.floor(frames), avail)) + budget.left -= n * nch * 4 + if budget.left < 0 then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, offset, n, spec) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", offset) + end + s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch + return true, nil +end + +-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99) +function Load.bcd(n: number): number + n = math.clamp(math.floor(n), 0, 99) + return (n // 10) * 16 + n % 10 +end + +return Load diff --git a/src/Formats/codecs/audio/Tracker/Player.luau b/src/Formats/codecs/audio/Tracker/Player.luau index 62df8b3..ed6af8f 100644 --- a/src/Formats/codecs/audio/Tracker/Player.luau +++ b/src/Formats/codecs/audio/Tracker/Player.luau @@ -23,6 +23,19 @@ local MOD, S3M, XM, IT = 1, 2, 3, 4 Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } +-- engine extension effects: format-specific commands of the other tracker formats, in any family (see +-- codecs/audio/Tracker) +local EXT = { + NOTE_SLIDE_UP = 0x40, + NOTE_SLIDE_DOWN = 0x41, + NOTE_SLIDE_UP_RETRIG = 0x42, + NOTE_SLIDE_DOWN_RETRIG = 0x43, + AUTO_PORTA_UP = 0x44, + AUTO_PORTA_DOWN = 0x45, + FREQ_ADJUST = 0x46, +} +Player.EXT = EXT + local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions -- ------------------------------------------------------------------------------------------------ state @@ -171,12 +184,20 @@ local function newChannel(i: number, pan: number, vol: number): any pitchEnvOn = true, muted = false, triggered = false, + autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down + autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running + hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) + slideCount = 0, -- note slides: ticks to the next step + mNoteSlide = 0, + tonePortaRow = false, } end -- new(module, opts) -> player state (module validated by the caller) function Player.new(m: any, sampleRate: number, opts: any): any - local fmt = FAMILY[m.format] or MOD + local fmt = FAMILY[m.engine or m.format] or MOD + local flags = m.flags + local ptPeriods = fmt == MOD or flags.periods == "amiga" local st: any = { m = m, fmt = fmt, @@ -189,8 +210,17 @@ function Player.new(m: any, sampleRate: number, opts: any): any insMode = m.instrumentMode and #m.instruments > 0, oldFx = m.flags.oldEffects or false, compatG = m.flags.compatGxx or false, - fastSlides = m.flags.fastSlides or false, - amigaLimits = m.flags.amigaLimits or false, + fastSlides = flags.fastSlides or false, + amigaLimits = flags.amigaLimits or false, + ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock) + hz = flags.periods == "hz", -- periods are frequencies in Hz + hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1, + hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1, + fastPortas = flags.fastPortas or false, + autoTonePorta = flags.autoTonePorta or false, + autoReset = flags.autoReset or false, + st2Tempo = flags.st2Tempo or false, + oktSlides = flags.oktSlides or false, ord = 0, row = 0, tick = 0, @@ -214,7 +244,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any master = 1, rows = 0, ramp = 64, - amiga = if fmt == MOD then AMIGA_PAL else AMIGA, + amiga = if ptPeriods then AMIGA_PAL else AMIGA, loopAllowed = opts and opts.loop or false, } for i = 1, m.channels do @@ -240,6 +270,9 @@ end -- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at -- volume 64 on one centred channel) function Player.masterGain(m: any, fmt: number): number + if type(m.preamp) == "number" then + return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader + end if fmt == IT or fmt == S3M then return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 end @@ -335,10 +368,15 @@ local function notePeriod(st: any, note: number, smp: any, ft: number?): (number end end local plin = (ref - note) * 64 - tr - if st.fmt == MOD then + if st.hz then + -- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5 + return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base + end + if st.ptPeriods then -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) local ftp = (ft or smp.finetune or 0) / 16 - return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base + local n = note + (if st.fmt == MOD or st.fmt == XM then smp.relativeNote or 0 else 0) + return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base end if st.linear then return plin, base @@ -350,6 +388,9 @@ local function arpPeriod(st: any, period: number, semis: number): number if semis == 0 then return period end + if st.hz then + return period * 2 ^ (semis / 12) + end if st.linear then return period - semis * 64 end @@ -357,7 +398,9 @@ local function arpPeriod(st: any, period: number, semis: number): number end local function clampPeriod(st: any, c: any) - if st.linear then + if st.hz then + c.period = clamp(c.period, 1, 1e6) + elseif st.linear then c.period = clamp(c.period, -6000, 6000) elseif st.amigaLimits then c.period = clamp(c.period, 113 * 4, 856 * 4) @@ -366,6 +409,17 @@ local function clampPeriod(st: any, c: any) end end +-- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency +-- moves units * hzSlide Hz the other way +local function slide(st: any, c: any, units: number) + if st.hz then + c.period -= units * st.hzScale + else + c.period += units + end + clampPeriod(st, c) +end + -- ------------------------------------------------------------------------------------------------ voices local function allocVoice(st: any): any local best, bestScore = nil, math.huge @@ -674,6 +728,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb keep = if c.voice.ins == ins then true else "release" end c.triggered = true + c.hzAdd = 0 c.tremorOn = true c.retrigCount = 0 v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) @@ -758,6 +813,9 @@ local function tonePorta(st: any, c: any, speed: number) if c.period == c.target then return end + if st.hz then + speed *= st.hzScale * st.hzTone + end if c.period < c.target then c.period = min(c.period + speed, c.target) else @@ -837,23 +895,21 @@ local function fxModXm(st: any, c: any, tick: number) if xm and param > 0 then c.mPortaUp = param end - if tick > 0 then - c.period -= (if xm then c.mPortaUp else param) * 4 - clampPeriod(st, c) + if tick > 0 or st.fastPortas then + slide(st, c, -(if xm then c.mPortaUp else param) * 4) end elseif fx == 2 then if xm and param > 0 then c.mPortaDn = param end - if tick > 0 then - c.period += (if xm then c.mPortaDn else param) * 4 - clampPeriod(st, c) + if tick > 0 or st.fastPortas then + slide(st, c, (if xm then c.mPortaDn else param) * 4) end elseif fx == 3 or fx == 5 then if fx == 3 and param > 0 then c.portaSpeed = param end - if tick > 0 then + if tick > 0 or st.fastPortas then tonePorta(st, c, c.portaSpeed * 4) end elseif fx == 4 or fx == 6 then @@ -909,16 +965,14 @@ local function fxModXm(st: any, c: any, tick: number) c.mFineUp = y end if tick == 0 then - c.period -= (if xm then c.mFineUp else y) * 4 - clampPeriod(st, c) + slide(st, c, -(if xm then c.mFineUp else y) * 4) end elseif x == 2 then if xm and y > 0 then c.mFineDn = y end if tick == 0 then - c.period += (if xm then c.mFineDn else y) * 4 - clampPeriod(st, c) + slide(st, c, (if xm then c.mFineDn else y) * 4) end elseif x == 4 then c.vibWave = y % 8 @@ -1054,16 +1108,14 @@ local function fxModXm(st: any, c: any, tick: number) c.mXFineUp = y end if tick == 0 then - c.period -= c.mXFineUp - clampPeriod(st, c) + slide(st, c, -c.mXFineUp) end elseif x == 2 then if y > 0 then c.mXFineDn = y end if tick == 0 then - c.period += c.mXFineDn - clampPeriod(st, c) + slide(st, c, c.mXFineDn) end end end @@ -1073,10 +1125,10 @@ local function fxModXm(st: any, c: any, tick: number) if param > 0 then c.mVolSlide = param end - if tick > 0 then + if tick > 0 or st.fastSlides then volSlideMod(c, c.mVolSlide) end - elseif tick > 0 then + elseif tick > 0 or st.fastSlides then volSlideMod(c, param) end end @@ -1161,16 +1213,15 @@ end local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) if p >= 0xF0 then if tick == 0 then - c.period += sign * (p % 16) * 4 + slide(st, c, sign * (p % 16) * 4) end elseif p >= 0xE0 then if tick == 0 then - c.period += sign * (p % 16) + slide(st, c, sign * (p % 16)) end - elseif tick > 0 then - c.period += sign * p * 4 + elseif tick > 0 or st.fastPortas then + slide(st, c, sign * p * 4) end - clampPeriod(st, c) end local function fxS3mIt(st: any, c: any, tick: number) @@ -1178,7 +1229,11 @@ local function fxS3mIt(st: any, c: any, tick: number) local it = st.fmt == IT if fx == 1 then -- A speed if tick == 0 and param > 0 then - st.speed = param + if st.st2Tempo then + st.speed, st.tempo = Tables.st2Tempo(param) + else + st.speed = param + end end elseif fx == 2 then -- B jump if tick == 0 then @@ -1446,7 +1501,7 @@ local function fxS3mIt(st: any, c: any, tick: number) c.portaSpeed = c.mEF end end - if tick > 0 then + if tick > 0 or st.fastPortas then tonePorta(st, c, c.portaSpeed * 4) end end @@ -1514,8 +1569,7 @@ local function volColIt(st: any, c: any, tick: number) c.mEF = p end if tick > 0 then - c.period += c.mEF * 4 - clampPeriod(st, c) + slide(st, c, c.mEF * 4) end elseif v <= 124 then local p = (v - 115) * 4 @@ -1523,8 +1577,7 @@ local function volColIt(st: any, c: any, tick: number) c.mEF = p end if tick > 0 then - c.period -= c.mEF * 4 - clampPeriod(st, c) + slide(st, c, -c.mEF * 4) end elseif v >= 193 and v <= 202 then local p = Tables.IT_VOLPORTA[v - 192] or 0 @@ -1550,6 +1603,62 @@ local function volColIt(st: any, c: any, tick: number) end end +-- ------------------------------------------------------------------------------------------------ extension effects +-- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family +local function fxExt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then + -- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides): + -- 1x = every tick, 5x = once on the first tick + if tick == 0 then + if param // 16 > 0 then + c.mNoteSlide = (param // 16) * 16 + c.mNoteSlide % 16 + end + if param % 16 > 0 then + c.mNoteSlide = (c.mNoteSlide // 16) * 16 + param % 16 + end + c.slideCount = c.mNoteSlide // 16 + end + local p = c.mNoteSlide + local go + if st.oktSlides then + go = p // 16 == 1 or tick == 0 + else + go = false + if tick > 0 then + c.slideCount -= 1 + go = c.slideCount == 0 + end + end + if go and c.smp and c.realNote > 0 then + c.slideCount = p // 16 + local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG + c.realNote = clamp(c.realNote + (if up then p % 16 else -(p % 16)), 1, 120) + c.period = notePeriod(st, c.realNote, c.smp, c.finetune) + if fx >= EXT.NOTE_SLIDE_UP_RETRIG then + retrigVoice(st, c) + end + end + elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then + if tick == 0 then + c.autoPorta = (if fx == EXT.AUTO_PORTA_UP then -param else param) * 4 + end + elseif fx == EXT.FREQ_ADJUST then + if tick == 0 then + c.hzAdd = param * 80 + end + end + -- auto slides: every tick (fast portamentos) or every tick but the first + if tick > 0 or st.fastPortas then + if c.autoPorta ~= 0 then + slide(st, c, c.autoPorta) + end + if c.autoTone and not c.tonePortaRow then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + -- ------------------------------------------------------------------------------------------------ rows and ticks local function noteDelayOf(st: any, fx: number, param: number): number if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then @@ -1573,6 +1682,9 @@ end local function runEffects(st: any, c: any, tick: number) c.vibDelta, c.arp = 0, 0 + if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then + fxExt(st, c, tick) + end if st.fmt == MOD or st.fmt == XM then fxModXm(st, c, tick) if st.fmt == XM then @@ -1621,6 +1733,15 @@ local function processRow(st: any) end c.fx, c.param, c.vcmd = fx, param, vcmd c.cutTick, c.keyOffTick = -1, -1 + if st.autoReset and fx ~= 0 and fx ~= 255 then + -- 669: any effect stops the auto slides + c.autoPorta, c.autoTone = 0, false + end + local tp = isPorta(st, fx, 0) + c.tonePortaRow = tp + if tp and st.autoTonePorta then + c.autoTone = param ~= 0 or not st.autoReset + end c.triggered = false local delay = noteDelayOf(st, fx, param) c.finetune = finetuneOf(st, fx, param) @@ -1750,7 +1871,9 @@ local function updateVoice(st: any, v: any) -- frequency local P = v.periodOut + avDelta local freq - if st.linear then + if st.hz then + freq = max(0, P + (v.hzAdd or 0)) + elseif st.linear then freq = v.base * 2 ^ (-P / 768) else freq = if P > 0 then st.amiga / P else 0 @@ -1762,9 +1885,9 @@ local function updateVoice(st: any, v: any) -- volume local smp = v.smp local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 - if it then - vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) - end + -- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader, + -- sets them) + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) if v.tremorMute then vol = 0 end @@ -1853,8 +1976,9 @@ function Player.tick(st: any): number local c = st.chans[i] local v = c.voice if v and v.active and v.chan == i and not v.bg then - local P = arpPeriod(st, c.period, c.arp) + c.vibDelta + local P = arpPeriod(st, c.period, c.arp) + (if st.hz then -c.vibDelta * st.hzScale else c.vibDelta) v.period, v.periodOut, v.base = c.period, P, c.base + v.hzAdd = c.hzAdd v.vol = clamp(c.vol + c.tremDelta, 0, 64) if c.muted then v.vol = 0 diff --git a/src/Formats/codecs/audio/Tracker/Tables.luau b/src/Formats/codecs/audio/Tracker/Tables.luau index 90e78d8..2378fee 100644 --- a/src/Formats/codecs/audio/Tracker/Tables.luau +++ b/src/Formats/codecs/audio/Tracker/Tables.luau @@ -110,4 +110,17 @@ Tables.AMIGA = 8363 * 1712 -- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) Tables.AMIGA_PAL = 7093789.2 / 2 * 4 +-- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor) +-- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM) +local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } +function Tables.st2Tempo(byte: number): (number, number) + local hi, lo = byte // 16, byte % 16 + local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates) + local spt = if d > 0 then 23863 // d else -(23863 // -d) + if spt <= 0 then + spt += 65536 + end + return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000 +end + return Tables diff --git a/src/Formats/codecs/audio/Tracker/init.luau b/src/Formats/codecs/audio/Tracker/init.luau index 55056f6..dc42016 100644 --- a/src/Formats/codecs/audio/Tracker/init.luau +++ b/src/Formats/codecs/audio/Tracker/init.luau @@ -1,6 +1,7 @@ --!strict --- codecs/audio/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 +-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders +-- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in +-- codecs/audio/Tracker/Load). The 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. -- @@ -9,14 +10,23 @@ -- 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 +-- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from +-- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four +-- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm", +-- music/669: "s3m", ...) and set the quirks they need in flags. +-- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family -- 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) } +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family), +-- amigaLimits (MOD), and the quirks of the other formats (any family): +-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in +-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta), +-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows), +-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo) } -- 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 @@ -25,7 +35,10 @@ -- 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. +-- (0 = none). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note +-- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones; +-- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency +-- adjust (+ param * 80 Hz, 669)). 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), @@ -85,12 +98,29 @@ export type RenderOptions = { local CELL = 5 +-- engine extension effects (see the Module notes above) +Tracker.EXT = Player.EXT + +-- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte +Tracker.st2Tempo = Tables.st2Tempo + +local FAMILIES = { mod = true, s3m = true, xm = true, it = true } + +-- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as +function Tracker.family(m: any): string? + local f = m.engine or m.format + return if type(f) == "string" and FAMILIES[f] then f else nil +end + -- ------------------------------------------------------------------------------------------------ constructors --- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults -function Tracker.newModule(format: string, channels: number): any +-- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family +-- (engine, default format) +function Tracker.newModule(format: string, channels: number, engine: string?): any + local fam = engine or format local m = { kind = "music", format = format, + engine = engine, title = "", channels = channels, speed = 6, @@ -99,8 +129,8 @@ function Tracker.newModule(format: string, channels: number): any mixVolume = 48, order = {}, restart = 0, - linear = format == "xm" or format == "it", - instrumentMode = format == "xm" or format == "it", + linear = fam == "xm" or fam == "it", + instrumentMode = fam == "xm" or fam == "it", flags = {}, channelPan = {}, channelVolume = {}, @@ -113,7 +143,7 @@ function Tracker.newModule(format: string, channels: number): any } for i = 1, channels do m.channelVolume[i] = 64 - if format == "mod" then + if fam == "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 @@ -285,8 +315,11 @@ 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)) + if not Tracker.family(m) then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format)) + end + if m.preamp ~= nil and not num(m.preamp, 0, 256) then + m.preamp = nil end if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then return nil, Err.new(Err.ARG, "bad channel count") diff --git a/src/Formats/music/mtm/init.luau b/src/Formats/music/mtm/init.luau new file mode 100644 index 0000000..049bb85 --- /dev/null +++ b/src/Formats/music/mtm/init.luau @@ -0,0 +1,226 @@ +--!strict +-- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared +-- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM): +-- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk +-- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row). +-- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Mtm = { + name = "mtm", + category = "music", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mtm.sniff(r: Bytes.Reader): number + if r:size() >= 66 and r:peek(3) == "MTM" and r:peekU8(3) < 0x20 and r:peekU8(33) >= 1 and r:peekU8(33) <= 32 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MultiTracker: a speed command resets the tempo to 125 and a tempo command the speed to 6, unless the module puts +-- both on one row somewhere (then it was written for players that treat them as ProTracker does) +local function speedTempoQuirk(m: any) + local speed, tempo, together = false, false, false + for _, p in m.patterns do + for row = 0, p.rows - 1 do + local s, t = false, false + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + if param < 0x20 then + s = true + else + t = true + end + end + end + speed, tempo, together = speed or s, tempo or t, together or (s and t) + end + end + if not (speed and tempo) or together then + return + end + for pi, p in m.patterns do + for row = 0, p.rows - 1 do + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + Load.writeEffect(m, pi - 1, row, 0xF, if param < 0x20 then 125 else 6, nil, nil, true) + break + end + end + end + end +end + +function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:size() < 66 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(3) ~= "MTM" then + return nil, Err.new(Err.CORRUPT, "no MTM signature") + end + r:skip(3) + local version = r:u8() + local title = r:fixed(20) + local numTracks, lastPattern, lastOrder = r:u16le(), r:u8(), r:u8() + local commentSize, numSamples, _attr, rowsPerTrack, nch = r:u16le(), r:u8(), r:u8(), r:u8(), r:u8() + local pans: { number } = {} + for i = 1, 32 do + pans[i] = r:u8() + end + if r.err then + return nil, r.err + end + if version >= 0x20 or lastOrder > 127 or rowsPerTrack > 64 or nch == 0 or nch > 32 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + local m = Tracker.newModule("mtm", nch, "xm") + m.title = title + m.linear = false + m.instrumentMode = false + for i = 1, nch do + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + -- samples + local sizes: { number } = {} + for i = 1, numSamples do + local s = Tracker.newSample(r:fixed(22)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + local ft, vol, attr = r:i8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + s.volume = math.min(vol, 64) + s.finetune = math.clamp(ft * 16, -128, 127) + local bits = if attr % 2 == 1 then 16 else 8 + s.bits = bits + local frames = 0 + if len > 2 then + frames = len + le = math.min(math.max(le, 1) - 1, len) + if ls + 4 >= le then + ls, le = 0, 0 + end + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + if le > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + end + end + sizes[i] = if len > 2 then len else 0 + s.length = frames + m.samples[i] = s + end + -- the order list + for i = 1, 128 do + local o = r:u8() + if i <= lastOrder + 1 then + m.order[i] = o + end + end + if r.err then + return nil, r.err + end + -- tracks (64 rows of 3 bytes each) and the patterns made of them + local rows = if rowsPerTrack > 0 then rowsPerTrack else 64 + local tracks = r:tell() + if not r:skip(192 * numTracks) then + return nil, r.err + end + local buf = r.buf + for p = 0, lastPattern do + local pat = Tracker.newPattern(rows, nch) + m.patterns[p + 1] = pat + for ch = 0, 31 do + local track = r:u16le() + if r.err then + return nil, r.err + end + if track > 0 and track <= numTracks and ch < nch then + local base = r.base + tracks + 192 * (track - 1) + for row = 0, rows - 1 do + local o = base + row * 3 + local b0, b1, b2 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * nch + ch) * 5 + if b0 >= 4 then + buffer.writeu8(pat.data, q, b0 // 4 + 25) -- C-4 = 49 plays the sample at 8363 Hz (OpenMPT keeps MTM / XM notes an octave up) + end + buffer.writeu8(pat.data, q + 1, (b0 % 4) * 16 + b1 // 16) + local cmd, param = b1 % 16, b2 + if cmd == 0xA then + param = if param >= 16 then param - param % 16 else param + elseif cmd == 8 then + cmd, param = 0, 0 -- no 8xx panning in MultiTracker + elseif cmd == 0xE then + local x = param // 16 + if x == 0 or x == 3 or x == 4 or x == 6 or x == 7 or x == 0xF then + cmd, param = 0, 0 -- not in MultiTracker + end + end + buffer.writeu8(pat.data, q + 3, cmd) + buffer.writeu8(pat.data, q + 4, param) + end + end + end + end + speedTempoQuirk(m) + -- the song message (40-character lines), then the sample data (unsigned PCM) + m.meta.message = r:string(commentSize) + if r.err then + r.err = nil + end + local pos = r.pos + for i = 1, numSamples do + local s = m.samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(buf, pos, s.length, { bits = s.bits, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + s.loopEnd = math.min(s.loopEnd, s.length) + end + end + m.meta.source = { format = "mtm", version = version, tracks = numTracks } + 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 + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mtm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mtm diff --git a/tests/music/_similar.luau b/tests/music/_similar.luau index e97f7eb..50127be 100644 --- a/tests/music/_similar.luau +++ b/tests/music/_similar.luau @@ -206,4 +206,79 @@ function S.worst(a: any, b: any, count: number): { { number } } return out end +-- against(t, Fmt, cases, thresh, family?): the shared body of the tracker loader tests (ws-audio2: mtm, 669, stm, ult, +-- okt, med, ptm, far, umx): each case decodes, sniffs, plays as long as openmpt's render (thresh.duration s) and +-- matches its loudness / envelope / spectrum / balance within thresh; then a seek. cases: { name, data, ref, +-- duration }. Returns the decoded modules. The tests run their fuzz pass with S.fuzzer / S.samples. +function S.against(t: any, Fmt: any, cases: { any }, thresh: any, family: string?): { any } + local Bytes = require("@formats/core/Bytes") + local Tracker = require("@formats/codecs/audio/Tracker") + local mods = {} + for _, c in cases do + local m, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(m, c.name .. ": " .. tostring(err)) + if not m then + continue + end + table.insert(mods, m) + t:eq(m.format, Fmt.name, c.name .. ": format") + if family then + t:eq(Tracker.family(m), family, c.name .. ": engine family") + end + t:check(Fmt.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 f = S.features(buf, frames) + local r = S.compare(f, c.ref) + t:note("%-8s 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(f, 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") + end + -- seek: the position after a seek and the output continuing + local m = mods[1] + if m then + local dec = m:render() + dec:seek(1) + t:check(math.abs(dec:position() - 1) < 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 + return mods +end + +-- fuzzer(Fmt) -> the fuzz function of a tracker loader: decode, and a short render of whatever decodes +function S.fuzzer(Fmt: any): (buffer) -> any + local Bytes = require("@formats/core/Bytes") + local Tracker = require("@formats/codecs/audio/Tracker") + return function(b: buffer): any + local fm = Fmt.decode(Bytes.reader(b)) + if fm then + local d = Tracker.render(fm, { maxDuration = 0.5, sampleRate = 8000 }) + if d then + d:read(4000) + end + end + return fm + end +end + +-- samples(cases) -> the fuzz seeds (each case's data) +function S.samples(cases: { any }): { string } + local out = {} + for _, c in cases do + table.insert(out, c.data) + end + return out +end + return S diff --git a/tests/music/mtm.luau b/tests/music/mtm.luau new file mode 100644 index 0000000..2e1a784 --- /dev/null +++ b/tests/music/mtm.luau @@ -0,0 +1,20 @@ +-- music/mtm tests: generated MultiTracker modules (tools/fixtures/mtm.py) parsed, rendered through codecs/audio/Tracker +-- and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Mtm = require("@formats/music/mtm") +local Cases = require("@tests/gen/mtm_cases") + +local t = T.suite("mtm") + +t:eq(Mtm.name, "mtm", "name") +t:eq(Mtm.category, "music", "category") +t:check(Mtm.caps.decode and not Mtm.caps.encode, "caps") + +local mods = S.against(t, Mtm, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "xm") +t:check(mods[1] and #mods[1].samples == 5 and mods[1].samples[3].bits == 16, "16-bit sample") +t:check(mods[1] and mods[1].meta.message ~= nil, "message") + +t:fuzz("decode", S.fuzzer(Mtm), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index eeef247..db34ec3 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -493,3 +493,55 @@ def reference(ctx, data, ext, extra=()): f = features(left, right) f["duration"] = duration(ctx, data, ext) return f + + +# ---------------------------------------------------------------------------------------------- other trackers +# (ws-audio2: MTM, 669, STM, ULT, OKT, MED, PTM, FAR, UMX writers for tools/fixtures/{mtm,669,...}.py) +def write_mtm(title, samples, orders, patterns, channels, pans=None, rows=64, comment=b""): + """samples: [{name, data (raw unsigned bytes; 16-bit: little-endian unsigned), bits 8|16, volume 0..64, + finetune -8..7, loop: (start, end) in bytes | None}]; patterns: [[row: [(note, ins, fx, param)] * channels] * rows] + with note 0 = none else our note (1 = C-0; 49 = C-4 plays at 8363 Hz; >= 25)""" + tracks, index = [], {} + table = [] + for pat in patterns: + ids = [] + for ch in range(32): + if ch >= channels: + ids.append(0) + continue + tb = bytearray() + for r in range(rows): + note, ins, fx, param = pat[r][ch] if r < len(pat) else (0, 0, 0, 0) + n = note - 25 if note else 0 + tb += bytes([(n << 2) | (ins >> 4), ((ins & 15) << 4) | fx, param]) + tb = bytes(tb) + b"\0" * (192 - len(tb)) + if not any(tb): + ids.append(0) + continue + if tb not in index: + tracks.append(tb) + index[tb] = len(tracks) + ids.append(index[tb]) + table.append(ids) + out = bytearray(b"MTM\x10" + name(title, 20)) + out += struct.pack(" tempo 125, tempo -> speed 6)""" + a, b = empty(4), empty(4) + for r in range(0, 64, 4): + put(a, r, 0, 49 + (r // 4) % 12, 1) + put(b, r, 1, 61 - (r // 4) % 12, 2) + put(a, 0, 3, 0, 0, 0xF, 0x03) + put(a, 32, 3, 0, 0, 0xF, 0xA0) + put(b, 16, 3, 0, 0, 0xF, 0x04) + put(b, 40, 3, 0, 0, 0xF, 0x50) + put(b, 0, 2, 37, 4, 0xB, 0x02) + return T.write_mtm("quirk", samples(), [0, 1, 0], [a, b], 4) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("quirk", song_quirk())): + ref = T.reference(ctx, data, "mtm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("mtm_cases", cases) +