From 384cdc407d655d971c1a445946fbfe89fb9e0106 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:11:20 -0500 Subject: [PATCH 01/12] ws-audio2: music/mtm (MultiTracker) on the tracker engine; engine: m.engine family, m.preamp, flags (periods amiga/hz, fastPortas, autoTonePorta, autoReset, st2Tempo, oktSlides), extension effects (note slides, auto portamento, frequency adjust), codecs/audio/Tracker/Load helpers (OpenMPT BSD) Engine changes are backward compatible: m.engine defaults to m.format; the channel / sample / instrument global volumes now apply in every family (defaults leave MOD / S3M / XM unchanged); mod/s3m/xm/it tests green. --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/openmpt-LICENSE.txt | 25 ++ src/Formats/Registry.luau | 12 + src/Formats/codecs/audio/Tracker/Load.luau | 287 +++++++++++++++++++ src/Formats/codecs/audio/Tracker/Player.luau | 204 ++++++++++--- src/Formats/codecs/audio/Tracker/Tables.luau | 13 + src/Formats/codecs/audio/Tracker/init.luau | 57 +++- src/Formats/music/mtm/init.luau | 226 +++++++++++++++ tests/music/_similar.luau | 75 +++++ tests/music/mtm.luau | 20 ++ tools/fixtures/_tracker.py | 52 ++++ tools/fixtures/mtm.py | 105 +++++++ 13 files changed, 1026 insertions(+), 52 deletions(-) create mode 100644 licenses/openmpt-LICENSE.txt create mode 100644 src/Formats/codecs/audio/Tracker/Load.luau create mode 100644 src/Formats/music/mtm/init.luau create mode 100644 tests/music/mtm.luau create mode 100644 tools/fixtures/mtm.py 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) + From 33d87e0c4d1277f394e4c3c539a0b8c71fc09472 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:13:48 -0500 Subject: [PATCH 02/12] ws-audio2: music/669 (Composer 669 / UNIS 669): s3m family with Hz periods, fast + auto slides, frequency adjust, per-pattern speed and break rows --- docs/FORMATS.md | 3 +- src/Formats/Registry.luau | 12 ++ src/Formats/music/669/init.luau | 209 ++++++++++++++++++++++++++++++++ tests/music/669.luau | 19 +++ tools/fixtures/669.py | 94 ++++++++++++++ tools/fixtures/_tracker.py | 30 +++++ 6 files changed, 366 insertions(+), 1 deletion(-) create mode 100644 src/Formats/music/669/init.luau create mode 100644 tests/music/669.luau create mode 100644 tools/fixtures/669.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 891c26c..4432463 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -73,6 +73,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` | | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | | subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` | +| music | 669 | .669 | yes | - | render: true, channels: 8, 8 | `tests/music/669.luau` | | 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` | @@ -97,7 +98,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part - - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read + - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders - codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. - **compress** diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index af40316..2638300 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -830,6 +830,18 @@ local list: { Entry } = { return require("@formats/subtitle/vtt") end, }, + { + name = "669", + category = "music", + path = "music/669", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, + load = function() + return require("@formats/music/669") + end, + }, { name = "it", category = "music", diff --git a/src/Formats/music/669/init.luau b/src/Formats/music/669/init.luau new file mode 100644 index 0000000..051ed29 --- /dev/null +++ b/src/Formats/music/669/init.luau @@ -0,0 +1,209 @@ +--!strict +-- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and +-- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides +-- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until +-- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F), +-- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms). +-- Not supported: UNIS 669's "super fast" speed 0, 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 Six69 = { + name = "669", + category = "music", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +-- the 669 effects (high nibble of the effect byte) by name +local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +-- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too) +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 497 then + return false + end + local magic = r:peek(2) + if magic ~= "if" and magic ~= "JN" then + return false + end + local nsmp, npat, restart = r:peekU8(110), r:peekU8(111), r:peekU8(112) + if nsmp > 64 or restart >= 128 or npat > 128 then + return false + end + local bad = 0 + for i = 2, 109 do + local c = r:peekU8(i) + if c > 0 and c <= 31 then + bad += 1 + if bad > 40 then + return false + end + end + end + for i = 0, 127 do + local o, t, b = r:peekU8(113 + i), r:peekU8(241 + i), r:peekU8(369 + i) + if (o >= 128 and o < 0xFE) or (o < 128 and t == 0) or t > 15 or b >= 64 then + return false + end + end + return true +end + +function Six69.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 497 then Err.TRUNCATED else Err.CORRUPT, "not a 669 module") + end + local extended = r:peek(2) == "JN" + r:skip(2) + local message = r:string(108) + local nsmp, npat, restart = r:u8(), r:u8(), r:u8() + local orders, tempos, breaks = {}, {}, {} + for i = 1, 128 do + orders[i] = r:u8() + end + for i = 1, 128 do + tempos[i] = r:u8() + end + for i = 1, 128 do + breaks[i] = r:u8() + end + if not r:need(nsmp * 25 + npat * 1536) then + return nil, r.err + end + local m = Tracker.newModule("669", 8, "s3m") + m.title = (string.gsub(string.sub(message, 1, 36), "[%z ]+$", "")) + m.meta.message = message + m.speed, m.tempo = 4, 78 + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide, m.flags.hzTonePorta = "hz", 20, 0.5 + m.flags.fastPortas, m.flags.autoTonePorta, m.flags.autoReset = true, true, true + for i = 1, 8 do + m.channelPan[i] = if i % 2 == 0 then 0xD0 else 0x30 + end + local lengths: { number } = {} + for i = 1, nsmp do + local s = Tracker.newSample(r:fixed(13)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + if len >= 0x4000000 then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. " too long") + end + s.c5speed = 8363 + if not (le > len and ls == 0) and le ~= 0 then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + lengths[i] = len + m.samples[i] = s + end + for i = 1, 128 do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + if orders[restart + 1] < npat then + m.restart = restart + end + -- patterns: 64 rows x 8 channels x 3 bytes (note / instrument, instrument / volume, effect / parameter) + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 8) + m.patterns[p + 1] = pat + local d = pat.data + local effect = table.create(8, 0xFF) -- the last effect per channel (balance slides repeat) + for row = 0, 63 do + for ch = 0, 7 do + local o = r.pos + (row * 8 + ch) * 3 + local ni, iv, ep = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * 8 + ch) * 5 + local hasNote = ni < 0xFE + if hasNote then + buffer.writeu8(d, q, ni // 4 + 37) + buffer.writeu8(d, q + 1, (ni % 4) * 16 + iv // 16 + 1) + effect[ch + 1] = 0xFF + end + if ni <= 0xFE then + buffer.writeu8(d, q + 2, ((iv % 16) * 64 + 8) // 15 + 1) + end + if ep ~= 0xFF then + effect[ch + 1] = ep + end + local e = effect[ch + 1] + if e ~= 0xFF then + local cmd, param = e // 16, e % 16 + local name = EFFECTS[cmd + 1] + if cmd == 4 then + param = param * 17 -- vibrato: speed = depth + elseif cmd == 6 then + param = if param == 0 then 0x4F elseif param == 1 then 0xF4 else -1 + elseif cmd == 7 and not (hasNote and extended) then + name = nil + end + if name ~= "panslide" then + effect[ch + 1] = 0xFF + end + if name and param >= 0 then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + r:skip(1536) + if breaks[p + 1] < 63 then + Load.writeEffect(m, p, breaks[p + 1], IT["break"], 0, "next") + end + Load.writeEffect(m, p, 0, IT.speed, tempos[p + 1], "next") + end + -- sample data: unsigned 8-bit + local pos = r.pos + for i = 1, nsmp do + local s = m.samples[i] + local ok, err = Load.readSample(buf, pos, lengths[i], { bits = 8, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += lengths[i] + end + m.meta.source = { format = "669", tracker = if extended then "UNIS 669" else "Composer 669" } + 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 Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Six69.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Six69 diff --git a/tests/music/669.luau b/tests/music/669.luau new file mode 100644 index 0000000..668b967 --- /dev/null +++ b/tests/music/669.luau @@ -0,0 +1,19 @@ +-- music/669 tests: generated Composer 669 / UNIS 669 modules (tools/fixtures/669.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 Six69 = require("@formats/music/669") +local Cases = require("@tests/gen/669_cases") + +local t = T.suite("669") + +t:eq(Six69.name, "669", "name") +t:eq(Six69.category, "music", "category") +t:check(Six69.caps.decode and not Six69.caps.encode, "caps") + +local mods = S.against(t, Six69, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "s3m") +t:check(mods[2] and mods[2].meta.source.tracker == "UNIS 669", "UNIS 669") + +t:fuzz("decode", S.fuzzer(Six69), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/669.py b/tools/fixtures/669.py new file mode 100644 index 0000000..df848ab --- /dev/null +++ b/tools/fixtures/669.py @@ -0,0 +1,94 @@ +# 669 fixtures (tools/fixtures.py): generated Composer 669 / UNIS 669 modules exercising the effects, rendered by +# openmpt123. +# tests/gen/669_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(): + return [[(0, 0, None, None) for _ in range(8)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=None, param=0): + p[row][ch] = (note, ins, vol, None if cmd is None else (cmd << 4) | param) + + +def samples(): + return [ + {"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "loop": (0, 64)}, + {"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "loop": (0, 64)}, + {"name": "saw", "data": T.u8(T.synth("saw", 100, 100, 0.6)), "loop": (0, 100)}, + {"name": "noise", "data": T.u8(T.synth("noise", 6000, 1, 0.7, decay=1500))}, + {"name": "tri", "data": T.u8(T.synth("tri", 50, 50, 0.8)), "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + a, b = empty(), empty() + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, 15) + put(a, 0, 1, 49, 2, 12) + put(a, 8, 1, 0, 0, None, 0, 2) # auto portamento up (runs until the next effect) + put(a, 16, 1, 0, 0, None, 1, 3) # auto portamento down + put(a, 24, 1, 0, 0, None, 5, 3) # speed (stops the auto slide) + put(a, 28, 1, 56, 2, 10) + put(a, 32, 1, 61, 2, None, 2, 2) # tone portamento (keeps going) + put(a, 40, 1, 49, 2, None, 2, 4) + put(a, 48, 1, 0, 0, 6, 3, 5) # frequency adjust + put(a, 52, 1, 0, 0, None, 4, 3) # frequency vibrato + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 15 - r // 8) + put(a, 4, 2, 37, 3, 15) + put(a, 36, 2, 0, 0, 4) + put(a, 10, 4, 73, 5, 9) + put(a, 20, 4, 0, 0, None, 4, 6) + # b: speed per pattern, a break row, more slides + put(b, 0, 0, 49, 1, 15) + put(b, 4, 0, 0, 0, None, 1, 1) + put(b, 12, 0, 61, 1, 15) + put(b, 16, 0, 0, 0, None, 0, 1) + put(b, 20, 0, 0, 0, 10, None) + put(b, 0, 2, 37, 3, 12) + put(b, 8, 2, 44, 3, None, 2, 1) + put(b, 24, 2, 0, 0, None, 3, 2) + put(b, 0, 5, 56, 5, 13) + put(b, 16, 5, 52, 2, 13) + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(8): + if ch not in keep: + row[ch] = (0, 0, None, None) + return T.write_669("effects 669", samples(), [0, 1], [a, b], [4, 3], [63, 40]) + + +def song_unis(): + """UNIS 669: balance slides, slot retrigger, a restart position""" + a = empty() + put(a, 0, 0, 61, 1, 15, 6, 0) # balance slide left (repeats until the next note) + put(a, 16, 0, 64, 1, 15, 6, 1) # right + put(a, 32, 1, 49, 4, 15, 7, 3) # slot retrigger + put(a, 40, 1, 49, 4, 15, 7, 6) + put(a, 8, 2, 68, 2, 11) + put(a, 48, 3, 56, 3, 14) + return T.write_669("unis", samples(), [0, 0], [a], [5], [63], extended=True) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("unis", song_unis())): + ref = T.reference(ctx, data, "669") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("669_cases", cases) diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index db34ec3..361f948 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -545,3 +545,33 @@ def write_mtm(title, samples, orders, patterns, channels, pans=None, rows=64, co def u16(xs): return b"".join(struct.pack("= 37), ins 1-based, vol 0..15 or None, effect byte (cmd << 4 | param) + or None; tempos / breaks: per pattern""" + out = bytearray(b"JN" if extended else b"if") + msg = message.encode()[:108] + out += msg + b" " * (108 - len(msg)) + out += bytes([len(samples), len(patterns), restart]) + out += bytes(orders) + b"\xff" * (128 - len(orders)) + out += bytes(tempos) + b"\x04" * (128 - len(tempos)) + out += bytes(breaks) + b"\x3f" * (128 - len(breaks)) + for s in samples: + ls, le = s.get("loop") or (0, 0xFFFFF) + out += name(s.get("name", ""), 13) + struct.pack("> 4), ((i & 15) << 4) | (vol if vol is not None else 0)]) + elif vol is not None: + out += bytes([0xFE, vol]) + else: + out += b"\xff\x00" + out.append(0xFF if eff is None else eff) + for s in samples: + out += s["data"] + return bytes(out) From 80f5fd2c5b010842b9d20bdf2a302ed99a4044c7 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:19:23 -0500 Subject: [PATCH 03/12] ws-audio2: music/stm (Scream Tracker 2): s3m family with the ST2 tempo byte, deferred Bxx, no effect memory --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/music/stm/init.luau | 233 ++++++++++++++++++++++++++++++++ tests/music/stm.luau | 19 +++ tools/fixtures/_tracker.py | 41 ++++++ tools/fixtures/stm.py | 90 ++++++++++++ 6 files changed, 396 insertions(+) create mode 100644 src/Formats/music/stm/init.luau create mode 100644 tests/music/stm.luau create mode 100644 tools/fixtures/stm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 4432463..dd58d62 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -80,6 +80,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | stm | .stm | yes | - | render: true, channels: 4, 4 | `tests/music/stm.luau` | | music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 2638300..ad8137b 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -914,6 +914,18 @@ local list: { Entry } = { return require("@formats/music/sf2") end, }, + { + name = "stm", + category = "music", + path = "music/stm", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, + load = function() + return require("@formats/music/stm") + end, + }, { name = "xm", category = "music", diff --git a/src/Formats/music/stm/init.luau b/src/Formats/music/stm/init.luau new file mode 100644 index 0000000..c2bf826 --- /dev/null +++ b/src/Formats/music/stm/init.luau @@ -0,0 +1,233 @@ +--!strict +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples). +-- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module +-- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the +-- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump +-- happens at the end of the pattern or at the next Cxx). +-- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), 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 Stm = { + name = "stm", + category = "music", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +-- .ABCDEFGHIJ (K..O do nothing) +local EFFECTS = { "speed", "jump", "break", "volslide", "portadown", "portaup", "toneporta", "vibrato", "tremor", "arpeggio" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 48 then + return false + end + local eof, ftype, major, minor = r:peekU8(28), r:peekU8(29), r:peekU8(30), r:peekU8(31) + local npat, gv = r:peekU8(33), r:peekU8(34) + if ftype ~= 2 or (eof ~= 0x1A and eof ~= 2) or major ~= 2 or (minor ~= 0 and minor ~= 10 and minor ~= 20 and minor ~= 21) then + return false + end + if npat > 64 or (gv > 64 and gv ~= 0x58) then + return false + end + for i = 20, 27 do + local c = r:peekU8(i) + if c < 0x20 or c >= 0x7F then + return false + end + end + return true +end + +function Stm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.7 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a tempo byte of files before ST 2.21 is decimal +local function tempoByte(v: number, minor: number): number + return if minor < 21 then (v // 10) * 16 + v % 10 else v +end + +function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not a Scream Tracker 2 module") + end + local title = r:fixed(20) + local tracker = r:fixed(8) + r:skip(3) + local minor, initTempo, npat, gv = r:u8(), r:u8(), r:u8(), r:u8() + r:skip(13) + local m = Tracker.newModule("stm", 4, "s3m") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.st2Tempo = true + initTempo = tempoByte(initTempo, minor) + if initTempo == 0 then + initTempo = 0x60 + end + m.speed, m.tempo = Tracker.st2Tempo(initTempo) + if minor > 10 then + m.globalVolume = math.min(gv, 64) * 2 + end + local offsets: { number } = {} + for i = 1, 31 do + local s = Tracker.newSample(r:fixed(12)) + local zero = r:u8() + r:skip(1) + local off, len, ls, le = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local vol = r:u8() + r:skip(1) + local rate = r:u16le() + r:skip(6) + if r.err then + return nil, r.err + end + if zero ~= 0 and zero ~= 46 then + return nil, Err.new(Err.CORRUPT, "bad sample header " .. i) + end + s.c5speed = if rate > 0 then rate else 8363 + s.volume = math.min(vol, 64) + if len < 2 then + len = 0 + end + if ls < len and le > ls and le ~= 0xFFFF then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + len = math.max(le, len) -- ST2 lets a loop run into the next sample's data + end + s.length = len + offsets[i] = off * 16 + m.samples[i] = s + end + for i = 1, (if minor == 0 then 64 else 128) do + local o = r:u8() + if o == 99 or o == 255 then + o = 255 + elseif o > 63 then + return nil, Err.new(Err.CORRUPT, "bad order list") + end + m.order[i] = o + end + if r.err then + return nil, r.err + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + -- patterns: 64 rows x 4 channels; one byte 0xFB (C-0, volume 0), 0xFC (nothing) or 0xFD (note cut), else 4 bytes + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 4) + m.patterns[p + 1] = pat + local d = pat.data + local breakPos, breakRow = -1, 63 -- ST2: Bxx only sets the next order, taken at the pattern's end or a Cxx + for row = 0, 63 do + for ch = 0, 3 do + local q = (row * 4 + ch) * 5 + local note = r:u8() + local insVol, volCmd, info = 0, 0, 0 + if note == 0xFB then + note = 0 -- a C-0 at volume 0 (OpenMPT reads it so) + elseif note == 0xFD then + buffer.writeu8(d, q, 254) + elseif note ~= 0xFC then + insVol, volCmd, info = r:u8(), r:u8(), r:u8() + end + if note ~= 0xFC and note ~= 0xFD then + if note == 0xFE then + buffer.writeu8(d, q, 254) + elseif note < 0x60 then + buffer.writeu8(d, q, (note // 16) * 12 + note % 16 + 37) + end + local ins = insVol // 8 + buffer.writeu8(d, q + 1, if ins > 31 then 0 else ins) + local vol = insVol % 8 + (volCmd // 16) * 8 + if vol <= 64 then + buffer.writeu8(d, q + 2, vol + 1) + end + local name, param = EFFECTS[volCmd % 16], info + if name == "volslide" then + param = if param % 16 > 0 then param % 16 else param - param % 16 + elseif name == "break" then + param = ((param - param % 16) * 10 + param % 16) % 256 + if breakPos >= 0 and param == 0 then + name, param = "jump", breakPos -- Bxx + C00 is a plain Bxx + breakPos = -1 + end + breakRow = math.min(breakRow, row) + if name == "break" then + param = Load.bcd(param) + end + elseif name == "jump" then + breakPos, breakRow = param, 63 + name = nil + elseif name == "speed" then + param = tempoByte(param, minor) + if param == 0 then + name = nil + end + elseif name ~= "tremor" and param == 0 then + name = nil -- no effect memory in ST2 + end + if name then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + if r.err then + return nil, r.err + end + if breakPos >= 0 then + Load.writeEffect(m, p, breakRow, IT.jump, breakPos, "prev") + end + end + -- sample data: signed 8-bit at the paragraph offsets (samples at volume 0 are not read) + local buf = r.buf + for i = 1, 31 do + local s = m.samples[i] + local len = s.length + s.length = 0 + if len > 0 and s.volume > 0 and offsets[i] > 48 then + local ok, err = Load.readSample(buf, r.base + offsets[i], len, { bits = 8, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + end + end + m.meta.source = { format = "stm", tracker = tracker, version = "2." .. minor } + 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 Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Stm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Stm diff --git a/tests/music/stm.luau b/tests/music/stm.luau new file mode 100644 index 0000000..4b2ccfa --- /dev/null +++ b/tests/music/stm.luau @@ -0,0 +1,19 @@ +-- music/stm tests: generated Scream Tracker 2 modules (tools/fixtures/stm.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 Stm = require("@formats/music/stm") +local Cases = require("@tests/gen/stm_cases") + +local t = T.suite("stm") + +t:eq(Stm.name, "stm", "name") +t:eq(Stm.category, "music", "category") +t:check(Stm.caps.decode and not Stm.caps.encode, "caps") + +local mods = S.against(t, Stm, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "s3m") +t:check(mods[1] and mods[1].meta.source.tracker == "!Scream!", "tracker name") + +t:fuzz("decode", S.fuzzer(Stm), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index 361f948..c9237e5 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -575,3 +575,44 @@ def write_669(message, samples, orders, patterns, tempos, breaks, restart=0, ext for s in samples: out += s["data"] return bytes(out) + + +def write_stm(title, samples, orders, patterns, tempo=0x60, gvol=64, minor=21): + """samples: [{name, data (signed bytes), volume, c2spd, loop: (start, end) | None}] (up to 31); patterns: [[row: + [(note, ins, vol, cmd, info)] * 4] * 64] with note 0 = none, 254 = cut, else our note (>= 37); vol None = none; + cmd 0 = none (A = 1, letters as in S3M)""" + head = bytearray(name(title, 20) + b"!Scream!" + bytes([0x1A, 2, 2, minor, tempo, len(patterns), gvol]) + b"\0" * 13) + smp_at = len(head) + head += b"\0" * (31 * 32) + head += bytes(orders) + bytes([99] * ((64 if minor == 0 else 128) - len(orders))) + for pat in patterns: + for row in pat: + for (note, ins, vol, cmd, info) in row: + if note in ("skip", "fb"): + head.append(0xFC if note == "skip" else 0xFB) # nothing / a C-0 at volume 0 + continue + if note == 254: + nb = 0xFE + elif note: + n = note - 37 + nb = (n // 12) << 4 | (n % 12) + else: + nb = 0xFF + v = 65 if vol is None else vol + head += bytes([nb, (ins << 3) | (v & 7), ((v >> 3) << 4) | cmd, info]) + body = head + for i in range(31): + h = bytearray(32) + if i < len(samples): + s = samples[i] + while len(body) % 16: + body.append(0) + off = len(body) // 16 + body += s["data"] + ls, le = s.get("loop") or (0, 0xFFFF) + h[0:12] = name(s.get("name", ""), 12) + struct.pack_into(" Date: Sat, 31 Oct 2026 14:25:08 -0500 Subject: [PATCH 04/12] ws-audio2: music/ult (UltraTracker): it family, two effect columns folded into the IT volume column, sustain loops, auto tone portamento (also from the volume column) --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/audio/Tracker/Load.luau | 4 + src/Formats/codecs/audio/Tracker/Player.luau | 4 +- src/Formats/music/ult/init.luau | 309 +++++++++++++++++++ tests/music/ult.luau | 19 ++ tools/fixtures/_tracker.py | 47 +++ tools/fixtures/ult.py | 95 ++++++ 8 files changed, 489 insertions(+), 2 deletions(-) create mode 100644 src/Formats/music/ult/init.luau create mode 100644 tests/music/ult.luau create mode 100644 tools/fixtures/ult.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index dd58d62..de3fc59 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -81,6 +81,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | stm | .stm | yes | - | render: true, channels: 4, 4 | `tests/music/stm.luau` | +| music | ult | .ult | yes | - | render: true, channels: 1, 32 | `tests/music/ult.luau` | | music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ad8137b..c3b557c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -926,6 +926,18 @@ local list: { Entry } = { return require("@formats/music/stm") end, }, + { + name = "ult", + category = "music", + path = "music/ult", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + 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/ult") + end, + }, { name = "xm", category = "music", diff --git a/src/Formats/codecs/audio/Tracker/Load.luau b/src/Formats/codecs/audio/Tracker/Load.luau index baaf81a..884a77a 100644 --- a/src/Formats/codecs/audio/Tracker/Load.luau +++ b/src/Formats/codecs/audio/Tracker/Load.luau @@ -201,6 +201,10 @@ function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number for n = 0, 3 do local v = Load.itVolume(e1, p1, n > 1) if e1 == nil or v then + if v == nil and (e2 == "volume" or e2 == "volume8") then + -- the engine's IT family sets volumes in the volume column only + return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0 + end return v or 0, e2, p2, nil, 0 end e1, p1, e2, p2 = e2, p2, e1, p1 diff --git a/src/Formats/codecs/audio/Tracker/Player.luau b/src/Formats/codecs/audio/Tracker/Player.luau index ed6af8f..78c11dc 100644 --- a/src/Formats/codecs/audio/Tracker/Player.luau +++ b/src/Formats/codecs/audio/Tracker/Player.luau @@ -1737,10 +1737,10 @@ local function processRow(st: any) -- 669: any effect stops the auto slides c.autoPorta, c.autoTone = 0, false end - local tp = isPorta(st, fx, 0) + local tp = isPorta(st, fx, vcmd) c.tonePortaRow = tp if tp and st.autoTonePorta then - c.autoTone = param ~= 0 or not st.autoReset + c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0) end c.triggered = false local delay = noteDelayOf(st, fx, param) diff --git a/src/Formats/music/ult/init.luau b/src/Formats/music/ult/init.luau new file mode 100644 index 0000000..6071b0a --- /dev/null +++ b/src/Formats/music/ult/init.luau @@ -0,0 +1,309 @@ +--!strict +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored +-- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt). +-- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects +-- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect +-- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone +-- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune. +-- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the +-- high byte is dropped), the logarithmic volumes of pre-1.4 files, 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 Ult = { + name = "ult", + category = "music", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + 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) +} + +-- ------------------------------------------------------------------------------------------------ constants +local EFFECTS: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [7] = "tremolo", + [9] = "offset", [10] = "volslide", [11] = "panning8", [12] = "volume8", [13] = "break", [15] = "speed", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ult.sniff(r: Bytes.Reader): number + local v = r:peekU8(14) + if r:size() >= 48 and r:peek(14) == "MAS_UTrack_V00" and v >= 0x31 and v <= 0x34 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +local function translate(e: number, param: number, version: number): (string?, number) + local name = EFFECTS[e] + if e == 0 then + if param == 0 or version < 3 then + name = nil + end + elseif e == 5 then + if (param % 16 == 0xC or param // 16 == 0xC) and version >= 3 then + return "keyoff", 0 + end + elseif e == 7 then + if version < 4 then + name = nil + end + elseif e == 0xA then + if param >= 16 then + param -= param % 16 + end + elseif e == 0xB then + param = (param % 16) * 0x11 + elseif e == 0xD then + param = 10 * (param // 16) + param % 16 + elseif e == 0xE then + local x, y = param // 16, param % 16 + if x == 1 then + return "portaup", 0xF0 + y + elseif x == 2 then + return "portadown", 0xF0 + y + elseif x == 8 and version >= 4 then + return "s3mex", 0x60 + y + elseif x == 9 then + return "retrig", y + elseif x == 0xA then + return "volslide", y * 16 + 0xF + elseif x == 0xB then + return "volslide", 0xF0 + y + elseif x == 0xC or x == 0xD then + return "s3mex", param + end + return nil, param + elseif e == 0xF then + if param > 0x2F then + name = "tempo" + end + end + return name, param +end + +-- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number) + if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then + return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0 + elseif b == "volslide" and (a == "vibrato" or a == "toneportavol") and pa == 0 then + return if a == "vibrato" then "vibratovol" else "toneportavol", pb, nil, 0 + end + return a, pa, b, pb +end + +-- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param, +-- lost global effect (name?, param) +local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number) + local rep = 1 + local b = r:u8() + if b == 0xFC then + rep = r:u8() + b = r:u8() + end + local note = if b > 0 and b < 97 then b + 24 else 0 + local ins, cmd, p1, p2 = r:u8(), r:u8(), r:u8(), r:u8() + local c1, q1 = translate(cmd % 16, p1, version) + local c2, q2 = translate(cmd // 16, p2, version) + if c1 == "offset" and c2 == "offset" then + local off = (p2 * 256 + p1) // 64 + return rep, note, ins, 0, Load.IT.offset, off % 256, nil, 0 + elseif c1 == "offset" then + q1 = math.min(p1 * 4, 255) + elseif c2 == "offset" then + q2 = math.min(p2 * 4, 255) + elseif c1 ~= nil and c1 == c2 then + c2 = nil + end + if c2 == nil then -- (OpenMPT also swaps for CMD_VOLUME, which ULT never produces) + c1, q1, c2, q2 = c2, q2, c1, q1 + end + c2, q2, c1, q1 = combine(c2, q2, c1, q1) + if c1 == "keyoff" or c2 == "keyoff" then + -- key off (5xC): a note-off when the cell has no note + if note == 0 then + note = 255 + end + if c1 == "keyoff" then + c1 = nil + else + c2 = nil + end + end + local vol, name, param, lost, lostParam = Load.fillTwo(c1, q1, c2, q2) + local fx, fp = Load.itEffect(name, param) + return rep, note, ins, vol, fx, fp, lost, lostParam +end + +function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Ult.sniff(r) == 0 then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not an UltraTracker module") + end + r:skip(14) + local version = r:u8() - 0x30 + local title = (string.gsub(r:fixed(32), " +$", "")) + local lines = r:u8() + local message = r:string(lines * 32) + local nsmp = r:u8() + if r.err then + return nil, r.err + end + local samples, sizes = {}, {} + for i = 1, nsmp do + local s = Tracker.newSample((string.gsub(r:fixed(32), " +$", ""))) + r:skip(12) + local ls, le, ss, se = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local vol, flags = r:u8(), r:u8() + local speed, finetune = 8363, 0 + if version >= 4 then + speed, finetune = r:u16le(), r:i16le() + else + finetune = r:i16le() + end + if r.err then + return nil, r.err + end + local bits = if bit32.band(flags, 4) ~= 0 then 16 else 8 + s.bits = bits + sizes[i] = 0 + if se > ss then + s.length = se - ss + sizes[i] = s.length * bits // 8 + s.volume = vol / 4 + s.c5speed = math.max(1, speed * 2 * 2 ^ (finetune / (12 * 32768))) + if bit32.band(flags, 8) ~= 0 then + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.susStart, s.susEnd = ls, le + s.susType = if bit32.band(flags, 16) ~= 0 then 2 else 1 + end + end + samples[i] = s + end + local order = {} + for i = 1, 256 do + order[i] = r:u8() + end + local nch, npat = r:u8() + 1, r:u8() + 1 + if r.err then + return nil, r.err + end + if nch > 32 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " channels") + end + local m = Tracker.newModule("ult", nch, "it") + m.title = title + m.meta.message = message + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx, m.flags.autoTonePorta = true, true, true + m.samples = samples + for i = 1, 256 do + m.order[i] = order[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + for i = 1, nch do + m.channelPan[i] = if version >= 3 then (r:u8() % 16) * 16 + 8 elseif i % 2 == 0 then 192 else 64 + end + for p = 1, npat do + m.patterns[p] = Tracker.newPattern(64, nch) + end + -- events, channel by channel, pattern by pattern + local speed0 = false + for ch = 0, nch - 1 do + for p = 0, npat - 1 do + if r:remaining() < 5 then + break + end + local d = m.patterns[p + 1].data + local row = 0 + while row < 64 do + local rep, note, ins, vol, fx, param, lost, lostParam = readEvent(r, version) + if r.err then + break + end + if lost and Load.isGlobal(lost, lostParam) then + local lf, lp = Load.itEffect(lost, lostParam) + Load.writeEffect(m, p, row, lf, lp, "next") + end + rep = math.min(rep, 64 - row) + if rep == 0 then + break + end + if fx == Load.IT.speed and param == 0 then + speed0 = true + end + for _ = 1, rep do + local q = (row * nch + ch) * 5 + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 2, vol) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + row += 1 + end + end + end + end + r.err = nil + if speed0 then + -- speed 0 resets the song speed and tempo (UltraTracker) + for p, pat in m.patterns do + for row = 0, 63 do + for ch = 0, nch - 1 do + local q = (row * nch + ch) * 5 + if buffer.readu8(pat.data, q + 3) == Load.IT.speed and buffer.readu8(pat.data, q + 4) == 0 then + buffer.writeu8(pat.data, q + 4, 6) + Load.writeEffect(m, p - 1, row, Load.IT.tempo, 125, "next") + end + end + end + end + end + -- sample data: signed 8 / 16-bit + local pos = r.pos + for i = 1, nsmp do + local s = samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(r.buf, pos, s.length, { bits = s.bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + end + end + m.meta.source = { format = "ult", version = version } + 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 Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ult.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ult diff --git a/tests/music/ult.luau b/tests/music/ult.luau new file mode 100644 index 0000000..3df1f53 --- /dev/null +++ b/tests/music/ult.luau @@ -0,0 +1,19 @@ +-- music/ult tests: generated UltraTracker modules (tools/fixtures/ult.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 Ult = require("@formats/music/ult") +local Cases = require("@tests/gen/ult_cases") + +local t = T.suite("ult") + +t:eq(Ult.name, "ult", "name") +t:eq(Ult.category, "music", "category") +t:check(Ult.caps.decode and not Ult.caps.encode, "caps") + +local mods = S.against(t, Ult, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "it") +t:check(mods[1] and mods[1].samples[3].bits == 16 and mods[1].samples[3].susType == 2, "16-bit ping-pong sustain loop") + +t:fuzz("decode", S.fuzzer(Ult), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index c9237e5..2287bc1 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -616,3 +616,50 @@ def write_stm(title, samples, orders, patterns, tempo=0x60, gvol=64, minor=21): struct.pack_into("= 4: + out += struct.pack("= 3: + out += bytes(pans or [(i % 2) * 15 for i in range(channels)]) + for ch in range(channels): + for pat in patterns: + evs = [] + for row in pat: + note, ins, e1, p1, e2, p2 = row[ch] + evs.append(bytes([note - 24 if note else 0, ins, (e2 << 4) | e1, p1, p2])) + i = 0 + while i < len(evs): + j = i + while j + 1 < len(evs) and evs[j + 1] == evs[i] and j - i < 250: + j += 1 + if j > i: + out += bytes([0xFC, j - i + 1]) + evs[i] + else: + out += evs[i] + i = j + 1 + for s in samples: + out += s["data"] + return bytes(out) diff --git a/tools/fixtures/ult.py b/tools/fixtures/ult.py new file mode 100644 index 0000000..8218e1c --- /dev/null +++ b/tools/fixtures/ult.py @@ -0,0 +1,95 @@ +# ULT fixtures (tools/fixtures.py): generated UltraTracker modules exercising the effects (two per cell), rendered by +# openmpt123. +# tests/gen/ult_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch): + return [[(0, 0, 0, 0, 0, 0) for _ in range(ch)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, e1=0, p1=0, e2=0, p2=0): + p[row][ch] = (note, ins, e1, p1, e2, p2) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 255, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 180, "speed": 16726, "loop": (0, 64)}, + {"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 240, "loop": (0, 200), "pingpong": True}, + {"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 230}, + {"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 200, "speed": 10000, "finetune": 3000, "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + a, b = empty(6), empty(6) + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, 0xC, 0x80 + i * 8) # note + set volume (volume column) + put(a, 0, 1, 49, 2) + put(a, 4, 1, 0, 0, 0xA, 0x04) # volume slide down + put(a, 8, 1, 0, 0, 0xA, 0x20, 0x4, 0x46) # slide + vibrato: two columns + put(a, 16, 1, 51, 2, 0x2, 0x03) + put(a, 20, 1, 0, 0, 0x1, 0x06, 0xB, 0x0C) # porta up + panning + put(a, 24, 1, 0, 0, 0xE, 0x14) # fine porta up + put(a, 28, 1, 56, 2, 0x4, 0x46) + put(a, 40, 1, 49, 2) + put(a, 41, 1, 61, 0, 0x3, 0x10) # tone portamento (keeps going) + put(a, 48, 1, 54, 2, 0x7, 0x58) # tremolo (v4) + put(a, 56, 1, 0, 0, 0xE, 0xA4) + put(a, 58, 1, 0, 0, 0xE, 0xB8) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 0xC, 255 - r * 3) + put(a, 20, 3, 61, 4, 0x9, 0x20) # offset (x 4) + put(a, 32, 3, 61, 4, 0xE, 0xC3) # note cut + put(a, 40, 3, 61, 4, 0xE, 0xD2) # note delay + put(a, 4, 2, 37, 3) + put(a, 30, 2, 0, 0, 0x5, 0x0C) # key off: the sustain loop ends + put(a, 36, 2, 44, 3, 0x0, 0x47) # arpeggio + put(a, 2, 4, 73, 5, 0xB, 0x03) + put(a, 44, 4, 0, 0, 0xE, 0x93) # retrigger + put(a, 10, 5, 56, 1, 0xF, 0x04) # speed + put(a, 34, 5, 0, 0, 0xF, 0x90) # tempo + put(b, 0, 0, 49, 1, 0xC, 0xFF, 0xF, 0x05) # volume + speed in one cell + put(b, 8, 0, 61, 1, 0x1, 0x04, 0xA, 0x03) # porta up -> volume column + put(b, 16, 0, 56, 1, 0x3, 0x08, 0x4, 0x05) # tone porta + vibrato depth + put(b, 24, 2, 49, 3, 0xE, 0x84) # fine pattern delay + put(b, 0, 5, 37, 2, 0xA, 0xF0, 0x3, 0x00) + put(b, 32, 4, 68, 5, 0xD, 0x00, 0xC, 0x60) # break + volume + if keep is not None: # debugging: only some channels (their speed / tempo / break effects stay) + for p in (a, b): + for row in p: + for ch in range(6): + if ch not in keep and row[ch][2] not in (0xD, 0xF) and row[ch][4] not in (0xD, 0xF): + row[ch] = (0, 0, 0, 0, 0, 0) + return T.write_ult("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9]) + + +def song_old(): + """a v1.3 file: no tremolo, no sample speed; arpeggio""" + a = empty(4) + for r in range(0, 64, 4): + put(a, r, r // 4 % 4, 49 + (r // 4) % 12, 1 + r // 4 % 3, 0x0, 0x37) + put(a, 32, 0, 0, 0, 0xF, 0x03) + return T.write_ult("old", samples(), [0, 0], [a], 4, version=3) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("old", song_old())): + ref = T.reference(ctx, data, "ult") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("ult_cases", cases) From 60544a3a7762adf2010be56c38d18523698423d1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:29:01 -0500 Subject: [PATCH 05/12] ws-audio2: music/ptm (PolyTracker): it family, MOD letters with S3M fine slides, note slides, delta 8 / 16-bit samples; engine flags.panLaw = ft2 (square-root panning) ops/MusicOps: accept modules of the other tracker formats by their engine family (Tracker.family), a one-line backward-compatible change. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/audio/Tracker/Player.luau | 5 + src/Formats/codecs/audio/Tracker/init.luau | 3 +- src/Formats/music/ptm/init.luau | 224 +++++++++++++++++++ src/Formats/ops/MusicOps.luau | 7 +- tests/music/ptm.luau | 19 ++ tools/fixtures/_tracker.py | 53 +++++ tools/fixtures/ptm.py | 89 ++++++++ 9 files changed, 409 insertions(+), 4 deletions(-) create mode 100644 src/Formats/music/ptm/init.luau create mode 100644 tests/music/ptm.luau create mode 100644 tools/fixtures/ptm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 20f9bd8..aee90a4 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -78,6 +78,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | ptm | .ptm | yes | - | render: true, channels: 1, 32 | `tests/music/ptm.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 | stm | .stm | yes | - | render: true, channels: 4, 4 | `tests/music/stm.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d68b3e7..d8c97a7 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -890,6 +890,18 @@ local list: { Entry } = { return require("@formats/music/mtm") end, }, + { + name = "ptm", + category = "music", + path = "music/ptm", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + 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/ptm") + end, + }, { name = "s3m", category = "music", diff --git a/src/Formats/codecs/audio/Tracker/Player.luau b/src/Formats/codecs/audio/Tracker/Player.luau index 78c11dc..622fd00 100644 --- a/src/Formats/codecs/audio/Tracker/Player.luau +++ b/src/Formats/codecs/audio/Tracker/Player.luau @@ -221,6 +221,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any autoReset = flags.autoReset or false, st2Tempo = flags.st2Tempo or false, oktSlides = flags.oktSlides or false, + ft2Pan = flags.panLaw == "ft2", ord = 0, row = 0, tick = 0, @@ -1905,6 +1906,10 @@ local function updateVoice(st: any, v: any) local g = vol * st.master if v.surround then v.tl, v.tr = g * 0.5, -g * 0.5 + elseif st.ft2Pan then + -- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255 + local p = min(pan, 255) + v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256) else v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 end diff --git a/src/Formats/codecs/audio/Tracker/init.luau b/src/Formats/codecs/audio/Tracker/init.luau index dc42016..30ee68d 100644 --- a/src/Formats/codecs/audio/Tracker/init.luau +++ b/src/Formats/codecs/audio/Tracker/init.luau @@ -26,7 +26,8 @@ -- 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) } +-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo), +-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels) } -- 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 diff --git a/src/Formats/music/ptm/init.luau b/src/Formats/music/ptm/init.luau new file mode 100644 index 0000000..ad06f91 --- /dev/null +++ b/src/Formats/music/ptm/init.luau @@ -0,0 +1,224 @@ +--!strict +-- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD +-- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx +-- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger, +-- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the +-- byte stream, as PolyTracker stores them), ping-pong loops. +-- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, 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 Ptm = { + name = "ptm", + category = "music", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + 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) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- PolyTracker's effects past MOD's 0..F +local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then + return false + end + local h = r:sub(32, 10) + local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le() + return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128 +end + +function Ptm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values +local function delta16(buf: buffer, off: number, frames: number, limit: number): (buffer, number) + local n = math.max(0, math.min(frames, (limit - off) // 2)) + local raw = buffer.create(n * 2) + local acc = 0 + for i = 0, n * 2 - 1 do + acc = (acc + buffer.readu8(buf, off + i)) % 256 + buffer.writeu8(raw, i, acc) + end + return raw, n +end + +function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 608 then Err.TRUNCATED else Err.CORRUPT, "not a PolyTracker module") + end + local title = r:fixed(28) + r:skip(1) + local vlo, vhi = r:u8(), r:u8() + r:skip(1) + local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:seek(64) + local m = Tracker.newModule("ptm", nch, "it") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx = true, true + m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels + for i = 1, 32 do + local p = r:u8() + if i <= nch then + m.channelPan[i] = (p % 16) * 16 + 4 + end + end + for i = 1, 256 do + local o = r:u8() + if i <= nord then + m.order[i] = o + end + end + local patOff: { number } = {} + for i = 1, 128 do + patOff[i] = r:u16le() * 16 + end + if r.err then + return nil, r.err + end + -- samples + local buf = r.buf + for i = 1, nsmp do + local h = r:slice(80) + if r.err then + return nil, r.err + end + local flags = h:u8() + h:skip(12) + local vol, c4 = h:u8(), h:u16le() + h:skip(2) + local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le() + h:skip(14) + local s = Tracker.newSample(h:fixed(28)) + m.samples[i] = s + s.volume = math.min(vol, 64) + s.c5speed = math.max(1, c4 * 2) + if flags % 4 == 1 and len > 0 then + local bits = if bit32.band(flags, 0x10) ~= 0 then 16 else 8 + if le > ls then + le -= 1 + end + local frames = len + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + local at = r.base + off + if at < r.limit then + local ok, err + if bits == 16 then + local raw, n = delta16(buf, at, frames, r.limit) + ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget) + else + ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget) + end + if not ok then + return nil, err + end + end + if bit32.band(flags, 4) ~= 0 and le > ls then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + s.loopType = if bit32.band(flags, 8) ~= 0 then 2 else 1 + end + end + end + -- patterns (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume) + for p = 1, npat do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + local d = pat.data + if patOff[p] > 0 and patOff[p] < r:size() then + local pr = r:sub(patOff[p]) + local row = 0 + while row < 64 and not pr:eof() do + local b = pr:u8() + if b == 0 then + row += 1 + else + local ch = b % 32 + local q = (row * nch + ch) * 5 + local ok = ch < nch + if bit32.band(b, 0x20) ~= 0 then + local note, ins = pr:u8(), pr:u8() + if note == 254 then + note = 254 + elseif note == 0 or note > 120 then + note = 0 + end + if ok then + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + end + end + if bit32.band(b, 0x40) ~= 0 then + local cmd, param = pr:u8(), pr:u8() + local name + if cmd < 0x10 then + name, param = Load.modCommand(cmd, param) + else + name = EXTRA[cmd - 0x10 + 1] + end + if name == "panning8" then + name, param = "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 + elseif name == "globalvol" then + param = math.min(param, 0x40) * 2 + end + if ok then + if name == "volume" then + if buffer.readu8(d, q + 2) == 0 then + buffer.writeu8(d, q + 2, math.min(param, 64) + 1) + end + else + local fx, fp = Load.itEffect(name, param) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + if bit32.band(b, 0x80) ~= 0 then + local v = pr:u8() + if ok then + buffer.writeu8(d, q + 2, math.min(v, 64) + 1) + end + end + end + end + end + end + m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) } + 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 Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ptm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ptm diff --git a/src/Formats/ops/MusicOps.luau b/src/Formats/ops/MusicOps.luau index 1d1cae0..8afd0d3 100644 --- a/src/Formats/ops/MusicOps.luau +++ b/src/Formats/ops/MusicOps.luau @@ -27,7 +27,8 @@ local function bad(what: string): (nil, Err.Err) end local function isModule(m: any): boolean - return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == true and type(m.patterns) == "table" + -- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four) + return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table" end local function int(v: any, lo: number, hi: number): boolean @@ -243,7 +244,7 @@ function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) local copy = buffer.create(length * channels * 4) buffer.copy(copy, 0, data, 0, length * channels * 4) s.data, s.length, s.channels = copy, length, channels - s.bits = spec.bits or (if m.format == "mod" then 8 else 16) + s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16) if s.bits ~= 8 and s.bits ~= 16 then return bad("addSample: bits must be 8 or 16") end @@ -298,7 +299,7 @@ function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err if not isModule(m) then return bad("addInstrument: needs a tracker Module") end - if m.format ~= "xm" and m.format ~= "it" then + if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)") end if type(spec) ~= "table" then diff --git a/tests/music/ptm.luau b/tests/music/ptm.luau new file mode 100644 index 0000000..b58ccc2 --- /dev/null +++ b/tests/music/ptm.luau @@ -0,0 +1,19 @@ +-- music/ptm tests: generated PolyTracker modules (tools/fixtures/ptm.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 Ptm = require("@formats/music/ptm") +local Cases = require("@tests/gen/ptm_cases") + +local t = T.suite("ptm") + +t:eq(Ptm.name, "ptm", "name") +t:eq(Ptm.category, "music", "category") +t:check(Ptm.caps.decode and not Ptm.caps.encode, "caps") + +local mods = S.against(t, Ptm, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "it") +t:check(mods[1] and mods[1].samples[3].bits == 16 and mods[1].samples[3].loopType == 2, "16-bit ping-pong loop") + +t:fuzz("decode", S.fuzzer(Ptm), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index 2287bc1..320b54d 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -663,3 +663,56 @@ def write_ult(title, samples, orders, patterns, channels, version=4, pans=None, for s in samples: out += s["data"] return bytes(out) + + +def write_ptm(title, samples, orders, patterns, channels, pans=None): + """samples: [{name, data (signed bytes; 16-bit little-endian), bits 8|16, volume, c4spd, loop: (start, end) in + frames | None, pingpong}] (stored delta coded: 8-bit deltas of the byte stream, also for 16-bit); patterns: [[row: + [(note, ins, vol, cmd, param)] * channels] * 64] with note 0 = none, 254 = cut, else our note (1..120); vol None = + none; cmd None = none, else 0..0x16 (MOD effects 0..F, then PolyTracker's G..)""" + head = bytearray(name(title, 28) + bytes([26, 3, 2, 0])) + head += struct.pack(" Date: Sat, 31 Oct 2026 14:34:09 -0500 Subject: [PATCH 06/12] ws-audio2: music/ptm: split the pattern / effect parsing (type checker complexity; baseline 92 kept) --- src/Formats/music/ptm/init.luau | 117 ++++++++++++++++---------------- 1 file changed, 60 insertions(+), 57 deletions(-) diff --git a/src/Formats/music/ptm/init.luau b/src/Formats/music/ptm/init.luau index ad06f91..66818a1 100644 --- a/src/Formats/music/ptm/init.luau +++ b/src/Formats/music/ptm/init.luau @@ -59,6 +59,65 @@ local function delta16(buf: buffer, off: number, frames: number, limit: number): return raw, n end +-- a PolyTracker effect -> name?, param +local function effect(cmd: number, param: number): (string?, number) + if cmd == 0x10 then + return "globalvol", math.min(param, 0x40) * 2 + elseif cmd > 0x10 then + return EXTRA[cmd - 0x10 + 1], param + elseif cmd == 8 then + return "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 -- 8xx pans in 16 steps + end + return Load.modCommand(cmd, param) +end + +-- one pattern (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume) +local function readPattern(pr: Bytes.Reader, d: buffer, nch: number) + local row = 0 + while row < 64 and not pr:eof() do + local b = pr:u8() + if b == 0 then + row += 1 + else + local ch = b % 32 + local q = (row * nch + ch) * 5 + local ok = ch < nch + if bit32.band(b, 0x20) ~= 0 then + local note, ins = pr:u8(), pr:u8() + if note == 254 then + note = 254 + elseif note == 0 or note > 120 then + note = 0 + end + if ok then + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + end + end + if bit32.band(b, 0x40) ~= 0 then + local name, param = effect(pr:u8(), pr:u8()) + if ok then + if name == "volume" then + if buffer.readu8(d, q + 2) == 0 then + buffer.writeu8(d, q + 2, math.min(param, 64) + 1) + end + else + local fx, fp = Load.itEffect(name, param) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + if bit32.band(b, 0x80) ~= 0 then + local v = pr:u8() + if ok then + buffer.writeu8(d, q + 2, math.min(v, 64) + 1) + end + end + end + end +end + function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local budget = { left = opts and opts.maxBytes or 2 ^ 28 } if not validHeader(r) then @@ -140,67 +199,11 @@ function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- patterns (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume) for p = 1, npat do local pat = Tracker.newPattern(64, nch) m.patterns[p] = pat - local d = pat.data if patOff[p] > 0 and patOff[p] < r:size() then - local pr = r:sub(patOff[p]) - local row = 0 - while row < 64 and not pr:eof() do - local b = pr:u8() - if b == 0 then - row += 1 - else - local ch = b % 32 - local q = (row * nch + ch) * 5 - local ok = ch < nch - if bit32.band(b, 0x20) ~= 0 then - local note, ins = pr:u8(), pr:u8() - if note == 254 then - note = 254 - elseif note == 0 or note > 120 then - note = 0 - end - if ok then - buffer.writeu8(d, q, note) - buffer.writeu8(d, q + 1, ins) - end - end - if bit32.band(b, 0x40) ~= 0 then - local cmd, param = pr:u8(), pr:u8() - local name - if cmd < 0x10 then - name, param = Load.modCommand(cmd, param) - else - name = EXTRA[cmd - 0x10 + 1] - end - if name == "panning8" then - name, param = "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 - elseif name == "globalvol" then - param = math.min(param, 0x40) * 2 - end - if ok then - if name == "volume" then - if buffer.readu8(d, q + 2) == 0 then - buffer.writeu8(d, q + 2, math.min(param, 64) + 1) - end - else - local fx, fp = Load.itEffect(name, param) - buffer.writeu8(d, q + 3, fx) - buffer.writeu8(d, q + 4, fp) - end - end - end - if bit32.band(b, 0x80) ~= 0 then - local v = pr:u8() - if ok then - buffer.writeu8(d, q + 2, math.min(v, 64) + 1) - end - end - end - end + readPattern(r:sub(patOff[p]), pat.data, nch) end end m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) } From 6b5e8ec6cf7501f1e1fea62bb498ae575e3c225c Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:36:44 -0500 Subject: [PATCH 07/12] ws-audio2: music/far (Farandole Composer): s3m family with Hz periods (36318 / 1024 Hz per step), auto tone portamento, variable-length patterns with break rows --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/music/far/init.luau | 232 ++++++++++++++++++++++++++++++++ tests/music/far.luau | 19 +++ tools/fixtures/_tracker.py | 33 +++++ tools/fixtures/far.py | 81 +++++++++++ 6 files changed, 378 insertions(+) create mode 100644 src/Formats/music/far/init.luau create mode 100644 tests/music/far.luau create mode 100644 tools/fixtures/far.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index aee90a4..b0c392e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -74,6 +74,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | | subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` | | music | 669 | .669 | yes | - | render: true, channels: 8, 8 | `tests/music/669.luau` | +| music | far | .far | yes | - | render: true, channels: 16, 16 | `tests/music/far.luau` | | 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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d8c97a7..2c8069b 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -842,6 +842,18 @@ local list: { Entry } = { return require("@formats/music/669") end, }, + { + name = "far", + category = "music", + path = "music/far", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, + load = function() + return require("@formats/music/far") + end, + }, { name = "it", category = "music", diff --git a/src/Formats/music/far/init.luau b/src/Formats/music/far/init.luau new file mode 100644 index 0000000..232b758 --- /dev/null +++ b/src/Formats/music/far/init.luau @@ -0,0 +1,232 @@ +--!strict +-- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any +-- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads +-- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods +-- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides, +-- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed +-- tempo OpenMPT uses (80 BPM in tracker terms). +-- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), 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 Far = { + name = "far", + category = "music", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT + +-- ------------------------------------------------------------------------------------------------ sniff +function Far.sniff(r: Bytes.Reader): number + if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and r:peekU8(47) + r:peekU8(48) * 256 >= 98 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +local function effect(e: number): (number, number, number) + local cmd, p = e // 16, e % 16 + if cmd == 1 then + return IT.portaup, 0xF0 + p, 0 + elseif cmd == 2 then + return IT.portadown, 0xF0 + p, 0 + elseif cmd == 3 then + return IT.toneporta, if p ~= 0 then 60 // p else 0, 0 + elseif cmd == 4 then + return IT.retrig, 6 // (1 + p) + 1, 0 + elseif cmd == 5 or cmd == 9 then + return IT.vibrato, p, 0 + elseif cmd == 6 then + return IT.vibrato, p * 8, 0 + elseif cmd == 7 then + return IT.volslide, p * 8, 0 + elseif cmd == 8 then + return IT.volslide, p, 0 + elseif cmd == 0xA then + return 0, 0, p * 4 + 4 + 1 -- volume portamento: a set volume + elseif cmd == 0xB then + return IT.s3mex, 0x80 + p, 0 + elseif cmd == 0xF then + return IT.speed, p, 0 + end + return 0, 0, 0 +end + +function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Far.sniff(r) == 0 then + return nil, Err.new(if r:size() < 98 then Err.TRUNCATED else Err.CORRUPT, "not a Farandole module") + end + r:skip(4) + local title = r:fixed(40) + r:skip(3) + local headerLength, version = r:u16le(), r:u8() + local onOff, pans = {}, {} + for i = 1, 16 do + onOff[i] = r:u8() + end + r:skip(9) + local speed = r:u8() + for i = 1, 16 do + pans[i] = r:u8() + end + r:skip(4) + local msgLen = r:u16le() + local message = r:string(msgLen) + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + local _npat, nord, restart = r:u8(), r:u8(), r:u8() + local sizes = {} + for i = 1, 256 do + sizes[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local m = Tracker.newModule("far", 16, "s3m") + m.title = title + m.meta.message = message + m.speed, m.tempo = if speed > 0 then speed else 4, 80 + m.mixVolume = 32 -- OpenMPT's pre-amp for FAR + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide = "hz", 36318 / 1024 + m.flags.autoTonePorta = true + for i = 1, 16 do + m.channelMute[i] = onOff[i] == 0 + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + for i = 1, nord do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + m.restart = restart + -- patterns: (size - 2) / 64 rows of 16 channels x (note, instrument, volume, effect), after a break row byte + if not r:seek(headerLength) then + return nil, r.err + end + local last = -1 + for p = 0, 255 do + if sizes[p + 1] > 0 then + last = p + end + end + for p = 0, last do + local size = sizes[p + 1] + local rows = math.clamp((size - 2) // 64, 1, 1024) + local pat = Tracker.newPattern(if size > 0 then rows else 64, 16) + m.patterns[p + 1] = pat + if size > 0 then + local pr = r:slice(size) + if r.err then + return nil, r.err + end + local br = pr:u8() + pr:skip(1) + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, 15 do + local note, ins, vol, e = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * 16 + ch) * 5 + if note > 0 and note <= 72 then + buffer.writeu8(d, q, note + 36) + buffer.writeu8(d, q + 1, ins + 1) + end + if vol > 0 and vol <= 16 then + buffer.writeu8(d, q + 2, (vol - 1) * 64 // 15 + 1) + end + local fx, param, setVol = effect(e) + if setVol > 0 then + buffer.writeu8(d, q + 2, setVol) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + end + end + if br > 0 and br < rows - 2 then + Load.writeEffect(m, p, br + 1, IT["break"], 0, "next") + end + end + end + -- samples: a 64-bit map of the stored ones, each a 48-byte header + signed 8 / 16-bit data + local map = {} + for i = 1, 8 do + map[i] = r:u8() + end + r.err = nil + for i = 0, 63 do + if bit32.band(map[i // 8 + 1] or 0, bit32.lshift(1, i % 8)) ~= 0 then + local h = r:slice(48) + if r.err then + break + end + local s = Tracker.newSample(h:fixed(32)) + local len = h:u32le() + h:skip(1) + local vol = h:u8() + local ls, le = h:u32le(), h:u32le() + local typ, loop = h:u8(), h:u8() + local bits = if typ % 2 == 1 then 16 else 8 + local frames = if bits == 16 then len // 2 else len + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.c5speed = 8363 * 2 + s.volume = math.min(vol * 4, 64) + local ok, err = Load.readSample(r.buf, r.pos, frames, { bits = bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + r:skip(math.min(len, r:remaining())) + if bit32.band(loop, 8) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + for k = #m.samples + 1, i do + m.samples[k] = Tracker.newSample() + end + m.samples[i + 1] = s + end + end + m.meta.source = { format = "far", version = version } + 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 Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Far.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Far diff --git a/tests/music/far.luau b/tests/music/far.luau new file mode 100644 index 0000000..f5b1abb --- /dev/null +++ b/tests/music/far.luau @@ -0,0 +1,19 @@ +-- music/far tests: generated Farandole Composer modules (tools/fixtures/far.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 Far = require("@formats/music/far") +local Cases = require("@tests/gen/far_cases") + +local t = T.suite("far") + +t:eq(Far.name, "far", "name") +t:eq(Far.category, "music", "category") +t:check(Far.caps.decode and not Far.caps.encode, "caps") + +local mods = S.against(t, Far, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "s3m") +t:check(mods[1] and mods[1].patterns[2].rows == 48 and mods[1].channelMute[10], "pattern length, muted channel") + +t:fuzz("decode", S.fuzzer(Far), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index 320b54d..10445c2 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -716,3 +716,36 @@ def write_ptm(title, samples, orders, patterns, channels, pans=None): h[76:80] = b"PTMS" body[smp_at + 80 * i:smp_at + 80 * i + 80] = h return bytes(body) + + +def write_far(title, samples, orders, patterns, speed=4, pans=None, breaks=None, message=b"", restart=0, mute=()): + """samples: [{name, data (signed bytes; 16-bit little-endian), bits 8|16, volume 0..15, loop: (start, end) in + frames | None}] (at most 64, stored in order); patterns: [[row: [(note, ins, vol, effect)] * 16] * rows] with note 0 + = none else our note (37..108), ins 1-based, vol 0 = none else 1..16, effect byte (cmd << 4 | param); breaks: the + break-row byte per pattern""" + head = bytearray(b"FAR\xfe" + name(title, 40) + b"\r\n\x1a") + hl_at = len(head) + head += b"\0\0" + bytes([0x10]) + bytes([0 if i in mute else 1 for i in range(16)]) + b"\0" * 9 + bytes([speed]) + head += bytes(list(pans or [(i % 2) * 15 for i in range(16)])) + head += b"\0" * 4 + struct.pack("> 3] |= 1 << (i & 7) + body += smap + for s in samples: + bps = 2 if s.get("bits", 8) == 16 else 1 + ls, le = s.get("loop") or (0, 0) + body += name(s.get("name", ""), 32) + struct.pack("> 4) != 0xF: + row[ch] = (0, 0, 0, 0) + return T.write_far("effects", samples(), [0, 1], [a, b], speed=5, breaks=[0, 30], mute=(9,), + pans=[3, 12, 7, 0, 15, 9, 5, 10, 8, 8, 8, 8, 8, 8, 8, 8], message=b"far test") + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()),): + ref = T.reference(ctx, data, "far") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("far_cases", cases) From 9a5f3796e2beb59642ad45f5e09819a2a062e7b9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:40:13 -0500 Subject: [PATCH 08/12] ws-audio2: music/okt (Oktalyzer): it family with ProTracker periods (PAL), mixed channel pairs and their shared volume, three arpeggios, note slides, sustain loops released by R --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/music/okt/init.luau | 286 ++++++++++++++++++++++++++++++++ tests/music/okt.luau | 19 +++ tools/fixtures/_tracker.py | 32 ++++ tools/fixtures/okt.py | 105 ++++++++++++ 6 files changed, 455 insertions(+) create mode 100644 src/Formats/music/okt/init.luau create mode 100644 tests/music/okt.luau create mode 100644 tools/fixtures/okt.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b0c392e..59b0a1f 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -79,6 +79,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | okt | .okt .okta | yes | - | render: true, channels: 4, 8 | `tests/music/okt.luau` | | music | ptm | .ptm | yes | - | render: true, channels: 1, 32 | `tests/music/ptm.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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 2c8069b..838c950 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -902,6 +902,18 @@ local list: { Entry } = { return require("@formats/music/mtm") end, }, + { + name = "okt", + category = "music", + path = "music/okt", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, + load = function() + return require("@formats/music/okt") + end, + }, { name = "ptm", category = "music", diff --git a/src/Formats/music/okt/init.luau b/src/Formats/music/okt/init.luau new file mode 100644 index 0000000..5aa97dd --- /dev/null +++ b/src/Formats/music/okt/init.luau @@ -0,0 +1,286 @@ +--!strict +-- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can +-- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style +-- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with +-- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample +-- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once: +-- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume. +-- Not supported: the Amiga LED filter (F), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Okt = { + name = "okt", + category = "music", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +local LAYOUT = table.freeze({ bigEndian = true }) :: Chunks.Layout + +-- ------------------------------------------------------------------------------------------------ sniff +function Okt.sniff(r: Bytes.Reader): number + return if r:peek(8) == "OKTASONG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a negative arpeggio offset as the equivalent positive one +local function invert(p: number): number + p %= 16 + if p == 0 then + return 0 + end + return if p <= 12 then 12 - p else 24 - p +end + +-- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off +local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean) + if e == 1 and p > 0 then + return "portaup", p, -1, false -- "portamento down (period)": the period goes down + elseif e == 2 and p > 0 then + return "portadown", p, -1, false + elseif e == 10 and p > 0 then + return "arpeggio", p % 16 + invert(p // 16) * 16, -1, false -- down, original, up + elseif e == 11 and p > 0 then + return "arpeggio", p - p % 16 + invert(p % 16), -1, false -- original, up, original, down + elseif e == 12 and p > 0 then + return "arpeggio", p, -1, false -- up, up, original + elseif e == 13 and p > 0 then + return "noteslidedown", 0x10 + math.min(p, 15), -1, false + elseif e == 30 and p > 0 then + return "noteslideup", 0x10 + math.min(p, 15), -1, false + elseif e == 21 and p > 0 then + return "noteslidedown", 0x50 + math.min(p, 15), -1, false + elseif e == 17 and p > 0 then + return "noteslideup", 0x50 + math.min(p, 15), -1, false + elseif e == 25 then + return "jump", p, -1, false + elseif e == 27 then + return nil, 0, -1, true + elseif e == 28 and p < 0x20 then + return "speed", p, -1, false + elseif e == 31 then + local x, y = p // 16, p % 16 + local slide = if paired then "chanvolslide" else "volslide" + if p <= 0x40 then + if paired then + return "chanvol", p, -1, false + end + return nil, 0, p, false + elseif x == 4 then + return slide, y, -1, false + elseif x == 5 then + return slide, y * 16, -1, false + elseif x == 6 then + return slide, 0xF0 + math.min(y, 0xE), -1, false + elseif x == 7 then + return slide, math.min(y, 0xE) * 16 + 0xF, -1, false + end + end + return nil, 0, -1, false +end + +function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:peek(8) ~= "OKTASONG" then + return nil, Err.new(if r:size() < 8 then Err.TRUNCATED else Err.CORRUPT, "no OKTASONG signature") + end + local buf = r.buf + local list = Chunks.walk(buf, r.base + 8, r.limit, LAYOUT) + local cmod = Chunks.find(list, "CMOD") + if not cmod or cmod.avail < 8 then + return nil, Err.new(Err.CORRUPT, "no channel table (CMOD)") + end + -- channels: each Amiga channel is one channel, or a mixed pair + local paired: { number } = {} -- 1: the first of a pair, -1: the second, 0: a raw Paula channel + local pans: { number } = {} + for ch = 0, 3 do + local pan = if ch == 1 or ch == 2 then 0xC0 else 0x40 + if buffer.readu16(buf, cmod.offset + ch * 2) ~= 0 then + table.insert(paired, 1) + table.insert(pans, pan) + table.insert(paired, -1) + else + table.insert(paired, 0) + end + table.insert(pans, pan) + end + local nch = #paired + local m = Tracker.newModule("okt", nch, "it") + m.linear = false + m.instrumentMode = false + m.tempo = 125 + m.flags.periods, m.flags.amigaLimits, m.flags.fastPortas, m.flags.oktSlides = "amiga", true, true, true + for i = 1, nch do + m.channelPan[i] = pans[i] + end + -- samples: 32-byte headers (name, length, loop start / length in words, volume, type 0 / 1 / 2) + local types: { number } = {} + local samp = Chunks.find(list, "SAMP") + if samp then + for i = 1, math.min(samp.avail // 32, 36) do + local h = Bytes.reader(buf, samp.offset + (i - 1) * 32, 32) + local s = Tracker.newSample(h:fixed(20)) + local len, ls, ll, vol, typ = h:u32be(), h:u16be() * 2, h:u16be() * 2, h:u16be(), h:u16be() + s.c5speed = 8287 + s.volume = math.min(vol, 64) + s.length = len - len % 2 + if ll > 2 and ls + ll <= s.length then + s.susStart, s.susEnd, s.susType = ls, ls + ll, 1 + end + types[i] = typ + m.samples[i] = s + end + end + local spee = Chunks.find(list, "SPEE") + if spee and spee.avail >= 2 then + m.speed = math.clamp(buffer.readu8(buf, spee.offset) * 256 + buffer.readu8(buf, spee.offset + 1), 1, 255) + end + local nord = 0 + local plen = Chunks.find(list, "PLEN") + if plen and plen.avail >= 2 then + nord = buffer.readu8(buf, plen.offset) * 256 + buffer.readu8(buf, plen.offset + 1) + end + local patt = Chunks.find(list, "PATT") + for i = 1, math.min(nord, if patt then patt.avail else 0) do + m.order[i] = buffer.readu8(buf, (patt :: Chunks.Chunk).offset + i - 1) + end + -- patterns (PBOD: rows, then 4 bytes per cell: note 1..36, sample, effect, parameter) + local copies: { [number]: boolean } = {} -- type B samples with a loop also need an unlooped copy (paired channels) + local npat = 0 + for _, c in list do + if c.id == "PBOD" and npat < 256 then + local pr = Bytes.reader(buf, c.offset, c.avail) + local rows = if c.avail >= 2 then math.clamp(pr:u16be(), 1, 1024) else 64 + local pat = Tracker.newPattern(rows, nch) + npat += 1 + m.patterns[npat] = pat + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, nch - 1 do + local note, ins, e, p = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * nch + ch) * 5 + local pair = paired[ch + 1] ~= 0 + if note > 0 and note <= 36 then + local n = note + 36 -- note 13 = C-4 = ProTracker period 428 (OpenMPT keeps MOD notes an octave up) + if pair and n >= 49 + 22 then + n = 49 + 21 -- the mixer's highest note + end + local smp = ins + 1 + local s = m.samples[smp] + if s then + if pair and s.volume < 64 then + buffer.writeu8(d, q + 2, 64 + 1) -- the default volume only works on raw Paula channels + end + local t = types[smp] + if (t == 1 and pair) or (t == 0 and not pair) then + smp += 100 -- a sample of the wrong type stops the channel + elseif t == 2 and pair and s.susType > 0 then + copies[smp] = true + smp += 36 + end + end + buffer.writeu8(d, q, n) + buffer.writeu8(d, q + 1, smp) + end + local name, param, vol, off = effect(e, p, pair) + if off then + buffer.writeu8(d, q, 255) + buffer.writeu8(d, q + 1, 0) + end + if vol >= 0 then + buffer.writeu8(d, q + 2, vol + 1) + end + local fx, fp = Load.itEffect(name, param) + if fx ~= 0 then + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + if name == "chanvol" or name == "chanvolslide" then + -- a mixed pair shares its volume: the other channel gets it too (the second one wins) + local other = ch + paired[ch + 1] + local o2 = (row * nch + other) * 5 + local ofx = buffer.readu8(d, o2 + 3) + if ofx == 0 or ofx == IT.chanvol or ofx == IT.chanvolslide then + buffer.writeu8(d, o2 + 3, fx) + buffer.writeu8(d, o2 + 4, fp) + end + end + end + end + end + end + end + -- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length + local k = 0 + local bodies = {} + for _, c in list do + if c.id == "SBOD" and c.avail > 0 then + table.insert(bodies, c) + end + end + local nsmp = #m.samples + for i = 1, nsmp do + local s = m.samples[i] + if s.length > 0 then + k += 1 + local c = bodies[k] + if not c then + s.length = 0 + continue + end + local ok, err = Load.readSample(buf, c.offset, math.min(s.length, c.avail), { bits = 8, signed = true, limit = c.offset + c.avail }, s, budget) + if not ok then + return nil, err + end + end + end + for i = 1, nsmp do + local s = m.samples[i] + if copies[i] then + local cp = Tracker.newSample(s.name) + cp.c5speed, cp.volume, cp.data, cp.length = s.c5speed, s.volume, s.data, s.length + m.samples[i + 36] = cp + end + end + for i = 1, (if next(copies) then 72 else nsmp) do + if m.samples[i] == nil then + m.samples[i] = Tracker.newSample() + end + end + m.meta.source = { format = "okt", channels = nch } + 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 Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Okt.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Okt diff --git a/tests/music/okt.luau b/tests/music/okt.luau new file mode 100644 index 0000000..b96f51c --- /dev/null +++ b/tests/music/okt.luau @@ -0,0 +1,19 @@ +-- music/okt tests: generated Oktalyzer modules (tools/fixtures/okt.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 Okt = require("@formats/music/okt") +local Cases = require("@tests/gen/okt_cases") + +local t = T.suite("okt") + +t:eq(Okt.name, "okt", "name") +t:eq(Okt.category, "music", "category") +t:check(Okt.caps.decode and not Okt.caps.encode, "caps") + +local mods = S.against(t, Okt, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "it") +t:check(mods[2] and mods[2].channels == 6, "two mixed pairs: 6 channels") + +t:fuzz("decode", S.fuzzer(Okt), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index 10445c2..f321a65 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -749,3 +749,35 @@ def write_far(title, samples, orders, patterns, speed=4, pans=None, breaks=None, 1 if bps == 2 else 0, 8 if s.get("loop") else 0) body += s["data"] return bytes(body) + + +def write_okt(samples, orders, patterns, cmod=(0, 0, 0, 0), speed=6): + """samples: [{name, data (signed bytes, even length), volume 0..64, type 0 paired / 1 raw / 2 both, loop: (start, + length) in bytes (even) | None}]; patterns: [[row: [(note, ins, effect, param)] * channels] * rows] with note 0 = + none else 1..36 (13 = C-5 of the module), ins 1-based; cmod: the four Amiga channels, 1 = a mixed pair""" + def chunk(cid, data): + return cid + struct.pack(">I", len(data)) + data + out = bytearray(b"OKTASONG") + out += chunk(b"CMOD", b"".join(struct.pack(">H", c) for c in cmod)) + sh = bytearray() + for i in range(36): + if i < len(samples): + s = samples[i] + ls, ll = s.get("loop") or (0, 0) + sh += name(s.get("name", ""), 20) + struct.pack(">IHHHH", len(s["data"]), ls // 2, ll // 2, s.get("volume", 64), s.get("type", 2)) + else: + sh += b"\0" * 32 + out += chunk(b"SAMP", bytes(sh)) + out += chunk(b"SPEE", struct.pack(">H", speed)) + out += chunk(b"SLEN", struct.pack(">H", len(patterns))) + out += chunk(b"PLEN", struct.pack(">H", len(orders))) + out += chunk(b"PATT", bytes(orders) + b"\0" * (128 - len(orders))) + for pat in patterns: + pb = bytearray(struct.pack(">H", len(pat))) + for row in pat: + for (note, ins, fx, param) in row: + pb += bytes([note, max(0, ins - 1), fx, param]) + out += chunk(b"PBOD", bytes(pb)) + for s in samples: + out += chunk(b"SBOD", s["data"]) + return bytes(out) diff --git a/tools/fixtures/okt.py b/tools/fixtures/okt.py new file mode 100644 index 0000000..5a22364 --- /dev/null +++ b/tools/fixtures/okt.py @@ -0,0 +1,105 @@ +# OKT fixtures (tools/fixtures.py): generated Oktalyzer modules exercising the effects and the mixed channel pairs, +# rendered by openmpt123. +# tests/gen/okt_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, fx=0, param=0): + p[row][ch] = (note, ins, fx, param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "type": 2, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 44, "type": 1, "loop": (0, 64)}, + {"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "type": 0, "loop": (64, 64)}, + {"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 60, "type": 2}, + {"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "type": 2, "loop": (0, 32)}, + ] + + +def song_raw(keep=None): + """four raw Paula channels: slides, arpeggios, note slides, volume, release""" + a, b = empty(4), empty(4, 48) + mel = [13, 17, 20, 25, 20, 17, 15, 13] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, 2, 0, 0, 0, 10, 0x37) # arpeggio 1 + put(a, 10, 0, 0, 0, 11, 0x37) # arpeggio 2 + put(a, 18, 0, 0, 0, 12, 0x37) # arpeggio 3 + put(a, 0, 1, 1, 2) + put(a, 4, 1, 0, 0, 1, 0x02) # period down (pitch up) + put(a, 12, 1, 0, 0, 2, 0x03) + put(a, 20, 1, 13, 2, 31, 0x20) # volume 0x20 + put(a, 24, 1, 0, 0, 31, 0x43) # slide down + put(a, 28, 1, 0, 0, 31, 0x52) # slide up + put(a, 32, 1, 0, 0, 31, 0x64) # fine down + put(a, 36, 1, 0, 0, 31, 0x76) # fine up + put(a, 40, 1, 8, 2, 30, 0x01) # note slide up every tick + put(a, 44, 1, 0, 0, 13, 0x02) + put(a, 48, 1, 0, 0, 17, 0x03) # once + put(a, 52, 1, 0, 0, 21, 0x05) + for r in range(0, 64, 8): + put(a, r, 3, 13, 4) + put(a, 2, 2, 25, 5) + put(a, 30, 2, 0, 0, 27, 0) # release: the sustain loop ends + put(a, 36, 2, 1, 5) + put(a, 34, 3, 0, 0, 28, 0x04) # speed + put(b, 0, 0, 13, 1) + put(b, 8, 1, 20, 2) + put(b, 16, 2, 13, 3) # a paired-only sample on a raw channel: stops it + put(b, 24, 3, 25, 5, 25, 0x00) # jump to 0 (song end) + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(4): + if ch not in keep and row[ch][2] not in (25, 28): + row[ch] = (0, 0, 0, 0) + return T.write_okt(samples(), [0, 1], [a, b], speed=6) + + +def song_pairs(keep=None): + """two mixed pairs (channels 2 / 3 and 5 / 6) and two raw channels""" + a = empty(6) + for r in range(0, 64, 4): + put(a, r, 0, 13 + (r // 4) % 12, 1) + put(a, r, 1, 1 + (r // 4) % 7, 3) + put(a, r + 2, 2, 20, 1) + put(a, 16, 1, 0, 0, 31, 0x30) # pair volume (shared) + put(a, 32, 2, 0, 0, 31, 0x10) # the second channel's volume wins + put(a, 40, 1, 0, 0, 31, 0x52) # pair volume slide + put(a, 0, 3, 13, 2) + put(a, 8, 4, 25, 4) + put(a, 10, 5, 13, 5) + put(a, 20, 5, 30, 1) # too high on a pair: clamped + put(a, 48, 4, 13, 1, 31, 0x18) + if keep is not None: + for row in a: + for ch in range(6): + if ch not in keep: + row[ch] = (0, 0, 0, 0) + return T.write_okt(samples(), [0], [a], cmod=(1, 0, 1, 0), speed=5) + + +def generate(ctx): + cases = [] + for nm, data in (("raw", song_raw()), ("pairs", song_pairs())): + ref = T.reference(ctx, data, "okt") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("okt_cases", cases) From d418458e2a21108e30c2f3b5b39307c84cd2f5f6 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:40:58 -0500 Subject: [PATCH 09/12] ws-audio2: music/okt: typed chunk list (type baseline 92) --- src/Formats/music/okt/init.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Formats/music/okt/init.luau b/src/Formats/music/okt/init.luau index 5aa97dd..d23eab3 100644 --- a/src/Formats/music/okt/init.luau +++ b/src/Formats/music/okt/init.luau @@ -230,7 +230,7 @@ function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length local k = 0 - local bodies = {} + local bodies: { Chunks.Chunk } = {} for _, c in list do if c.id == "SBOD" and c.avail > 0 then table.insert(bodies, c) From 3d5cf3130ee9dd3e8d3c94e87b12ff4117db8f41 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:51:33 -0500 Subject: [PATCH 10/12] ws-audio2: music/med (MED / OctaMED MMD0..MMD3): xm family with ProTracker periods, MED effects and tempo modes, play sequences, hold / decay envelopes, IFF multi-octave keymaps; engine: EXT tempo > 255, flags.envRowHold Synthetic / hybrid / MIDI instruments are silent (listed in meta.unsupported). --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/audio/Tracker/Player.luau | 13 +- src/Formats/codecs/audio/Tracker/init.luau | 6 +- src/Formats/music/med/init.luau | 661 +++++++++++++++++++ tests/music/med.luau | 22 + tools/fixtures/_tracker.py | 112 ++++ tools/fixtures/med.py | 113 ++++ 8 files changed, 935 insertions(+), 5 deletions(-) create mode 100644 src/Formats/music/med/init.luau create mode 100644 tests/music/med.luau create mode 100644 tools/fixtures/med.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 59b0a1f..3a879ca 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 | 669 | .669 | yes | - | render: true, channels: 8, 8 | `tests/music/669.luau` | | music | far | .far | yes | - | render: true, channels: 16, 16 | `tests/music/far.luau` | | music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` | +| music | med | .med .mmd0 .mmd1 .mmd2 .mmd3 .omed | yes | - | render: true, channels: 1, 64 | `tests/music/med.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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 838c950..b7a0d53 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -866,6 +866,18 @@ local list: { Entry } = { return require("@formats/music/it") end, }, + { + name = "med", + category = "music", + path = "music/med", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, + load = function() + return require("@formats/music/med") + end, + }, { name = "midi", category = "music", diff --git a/src/Formats/codecs/audio/Tracker/Player.luau b/src/Formats/codecs/audio/Tracker/Player.luau index 622fd00..4454d57 100644 --- a/src/Formats/codecs/audio/Tracker/Player.luau +++ b/src/Formats/codecs/audio/Tracker/Player.luau @@ -33,6 +33,7 @@ local EXT = { AUTO_PORTA_UP = 0x44, AUTO_PORTA_DOWN = 0x45, FREQ_ADJUST = 0x46, + TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param) } Player.EXT = EXT @@ -222,6 +223,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any st2Tempo = flags.st2Tempo or false, oktSlides = flags.oktSlides or false, ft2Pan = flags.panLaw == "ft2", + envHold = flags.envRowHold or false, ord = 0, row = 0, tick = 0, @@ -1648,6 +1650,10 @@ local function fxExt(st: any, c: any, tick: number) if tick == 0 then c.hzAdd = param * 80 end + elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then + if tick == 0 then + st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param + end end -- auto slides: every tick (fast portamentos) or every tick but the first if tick > 0 or st.fastPortas then @@ -1806,10 +1812,11 @@ local function updateVoice(st: any, v: any) local envVol, envPan, envPitch = 64, 0, 0 local filterEnv = nil if ins then + local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick local e = ins.volEnv if e and e.enabled and v.volEnvOn then local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) - envVol, v.volEnvPos = val, np + envVol, v.volEnvPos = val, if hold then v.volEnvPos else np if ended and it then if val <= 0 then v.active = false @@ -1821,12 +1828,12 @@ local function updateVoice(st: any, v: any) e = ins.panEnv if e and e.enabled and v.panEnvOn then local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) - envPan, v.panEnvPos = val, np + envPan, v.panEnvPos = val, if hold then v.panEnvPos else np end e = ins.pitchEnv if e and e.enabled and v.pitchEnvOn then local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) - v.pitchEnvPos = np + v.pitchEnvPos = if hold then v.pitchEnvPos else np if e.filter then filterEnv = val else diff --git a/src/Formats/codecs/audio/Tracker/init.luau b/src/Formats/codecs/audio/Tracker/init.luau index 30ee68d..f185acc 100644 --- a/src/Formats/codecs/audio/Tracker/init.luau +++ b/src/Formats/codecs/audio/Tracker/init.luau @@ -27,7 +27,8 @@ -- 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), --- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels) } +-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels), +-- envRowHold (MED: envelopes do not advance on a row's first tick) } -- 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 @@ -39,7 +40,8 @@ -- (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. +-- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)). +-- 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), diff --git a/src/Formats/music/med/init.luau b/src/Formats/music/med/init.luau new file mode 100644 index 0000000..4cc328e --- /dev/null +++ b/src/Formats/music/med/init.luau @@ -0,0 +1,661 @@ +--!strict +-- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks, +-- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song +-- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL +-- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks +-- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop +-- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave +-- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops, +-- default pitch, volume). +-- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and +-- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, 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 Med = { + name = "med", + category = "music", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- IFF multi-octave samples: the sample (0 = the lowest octave stored first... as OpenMPT orders them) and the +-- transpose used per octave of the keyboard, by the number of octaves stored (2..7) +local OCT_SAMPLE = { + { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 2, 2, 1, 1, 0, 0, 0, 0 }, + { 3, 3, 2, 2, 1, 0, 0, 0 }, + { 4, 3, 2, 1, 1, 0, 0, 0 }, + { 5, 4, 3, 2, 1, 0, 0, 0 }, + { 6, 5, 4, 3, 2, 1, 0, 0 }, +} +local OCT_TRANSPOSE = { + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -60, -72 }, +} +local SAMPLES_PER_TYPE = { [0] = 1, 5, 3, 2, 4, 6, 7 } +local TEMPO_8CH = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 52 or r:peek(3) ~= "MMD" then + return false + end + local v = r:peekU8(3) + if v < 0x30 or v > 0x33 then + return false + end + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + return songOff >= 52 and songOff + 63 * 8 + 284 <= r:size() and blockOff >= 52 and (smpOff == 0 or smpOff >= 52) +end + +function Med.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean } + +-- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes) +local function tempoToBpm(tempo: number, ctx: Ctx): number + if ctx.bpm and not ctx.is8Ch then + return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4 + end + if ctx.is8Ch and tempo > 0 then + return TEMPO_8CH[math.min(tempo, 10)] + elseif not ctx.softMix and tempo > 0 and tempo <= 10 then + return 6 * 1773447 / 14500 / tempo -- SoundTracker-compatible tempo + elseif ctx.softMix and tempo < 8 then + return 157.86 + end + return tempo / 0.264 +end + +-- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect) +local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean) + local lo = math.min(p, 15) + if cmd == 1 or cmd == 2 then + return if p > 0 then cmd else 0, p, false + elseif cmd == 4 then + return 4, p - p % 16 + math.min((p % 16) * 2, 15), false -- twice as deep as ProTracker's + elseif cmd == 5 then + return if p > 0 then 5 else 3, p, false + elseif cmd == 6 then + return if p > 0 then 6 else 4, p, false + elseif cmd == 8 or cmd == 0xE or cmd == 0x10 or cmd == 0x1C or cmd == 0x20 or cmd == 0x29 then + return 0, 0, false -- hold / decay (instrument data), synth jump, MIDI, reverse, relative offset + elseif cmd == 9 then + return if p > 0 and p <= 0x20 then 0xF else 0, math.min(p, 0x1F), false + elseif cmd == 0xC then + if not ctx.volHex and p < 0x99 then + return 0xC, (p // 16) * 10 + p % 16, false + elseif ctx.volHex and not ctx.vol7bit then + return 0xC, math.min(p % 128, 64), false + elseif ctx.volHex then + return 0xC, (p % 128 + 1) // 2, false + end + return 0, 0, false + elseif cmd == 0xD then + return if p > 0 then 0xA else 0, p, false + elseif cmd == 0xF then + if p == 0 then + return 0xD, 0, false + elseif p <= 0xF0 then + local bpm = if p < 3 then 0x70 else math.floor(tempoToBpm(p, ctx) + 0.5) + if bpm > 255 then + local ext = Tracker.EXT.TEMPO_256 + math.min(bpm // 256, 3) - 1 -- tempos past 255 (EXT 0x47..0x49) + return ext, math.min(bpm - (ext - Tracker.EXT.TEMPO_256 + 1) * 256, 255), false + end + return 0xF, math.max(bpm, 0x20), false + elseif p == 0xF1 then + return 0xE, 0x93, false + elseif p == 0xF2 then + return 0xE, 0xD3, false + elseif p == 0xF3 then + return 0xE, 0x92, false + elseif p == 0xFF then + return 0, 0, true + end + return 0, 0, false + elseif cmd == 0x11 then + return 0xE, 0x10 + lo, false + elseif cmd == 0x12 then + return 0xE, 0x20 + lo, false + elseif cmd == 0x14 then + return 4, p, false -- ProTracker depth, faster + elseif cmd == 0x15 then + return 0xE, 0x50 + p % 16, false + elseif cmd == 0x16 then + return 0xE, 0x60 + lo, false + elseif cmd == 0x18 then + return 0xE, 0xC0 + lo, false + elseif cmd == 0x19 then + return 9, p, false + elseif cmd == 0x1A then + return 0xE, 0xA0 + lo, false + elseif cmd == 0x1B then + return 0xE, 0xB0 + lo, false + elseif cmd == 0x1D then + return 0xD, Load.bcd(p), false -- pattern break, the row in hex + elseif cmd == 0x1E then + return 0xE, 0xE0 + lo, false + elseif cmd == 0x1F then + if p >= 16 then + return 0xE, 0xD0 + p // 16, false + elseif p > 0 then + return 0xE, 0x90 + p, false + end + return 0, 0, false + elseif cmd == 0x2E then + if p <= 0x10 or p >= 0xF0 then + return 8, math.clamp((bit32.bxor(p, 0x80) - 0x70) * 8, 0, 255), false + end + return 0, 0, false + elseif cmd < 0x10 and (cmd > 0 or p > 0) then + return cmd, p, false -- the remaining ProTracker effects as they are (0, 3, 7, 8, A, B) + end + return 0, 0, false +end + +-- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping) +local function wrapNote(note: number, vol7bit: boolean): number + local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) + if n > 132 and not vol7bit then + n -= 108 + elseif n > 120 then + n -= (n - 109) - (n - 109) % 12 + end + return if n >= 13 then n - 12 else 0 +end + +-- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding +local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean) + local br = r:sub(off) + local ntracks, nrows, info + if version < 1 then + ntracks, nrows, info = br:u8(), br:u8() + 1, 0 + else + ntracks, nrows, info = br:u16be(), br:u16be() + 1, br:u32be() + end + if br.err or nrows > 1024 then + return nil, false + end + local cmdExt: Bytes.Reader? = nil + if version >= 1 and info > 0 then + local ir = r:sub(info, 36) + ir:skip(16) + local ext = ir:u32be() + if not ir.err and ext > 0 then + local p = r:sub(ext, 4):u32be() + if p > 0 then + cmdExt = r:sub(p) + end + end + end + local lctx = table.clone(ctx) + lctx.vol7bit = cmdExt ~= nil + local pat = Tracker.newPattern(nrows, nch) + local d = pat.data + local high = false + local used = math.min(ntracks, nch) + for row = 0, nrows - 1 do + for ch = 0, ntracks - 1 do + local note, ins, cmd, param, cut = 0, 0, 0, 0, false + if version < 1 then + local ni, ic, p = br:u8(), br:u8(), br:u8() + if ni % 64 > 0 then + note = ni % 64 + lctx.transpose + end + ins = ic // 16 + bit32.rshift(bit32.band(ni, 0x80), 3) + bit32.rshift(bit32.band(ni, 0x40), 1) + cmd, param = ic % 16, p + else + local nv, iv, c, p = br:u8(), br:u8(), br:u8(), br:u8() + if nv % 128 > 0 then + note = nv % 128 + lctx.transpose + elseif nv == 0x80 then + cut = true + end + ins, cmd, param = iv % 64, c, p + end + if br.err then + return pat, high + end + if ch < used then + local q = (row * nch + ch) * 5 + if note >= 61 + 24 - 12 then + high = true + end + local n = wrapNote(note, lctx.vol7bit) + if n > 0 then + buffer.writeu8(d, q, n) + elseif cut then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 1, ins) + if cmd ~= 0 or param ~= 0 then + local fx, fp, noteCut = effect(cmd, param, lctx) + if noteCut and n == 0 then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + end + return pat, high +end + +function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 52 then Err.TRUNCATED else Err.CORRUPT, "not a MED module") + end + local version = r:peekU8(3) - 0x30 + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + h:skip(4) + local expOff = h:u32be() + -- the song: 63 sample headers, then the song header + local sh = r:sub(songOff, 63 * 8) + local song = r:sub(songOff + 63 * 8, 284) + local numBlocks, songLength = song:u16be(), song:u16be() + local seq = song:sub(4, 256) + song:skip(256) + local defTempo, playTranspose, flags, flags2, tempo2 = song:u16be(), song:i8(), song:u8(), song:u8(), song:u8() + local trackVol = {} + for i = 1, 16 do + trackVol[i] = song:u8() + end + local masterVol, numSamples = song:u8(), song:u8() + if song.err or numSamples > 63 or numBlocks > 0x7FFF then + return nil, Err.new(Err.CORRUPT, "bad song header") + end + if numSamples > 0 and smpOff == 0 then + return nil, Err.new(Err.CORRUPT, "no sample table") + end + -- channels: the widest block (at least 4) + local nch = 4 + local blockPtr: { number } = {} + for b = 0, numBlocks - 1 do + local p = r:sub(blockOff + b * 4, 4):u32be() + blockPtr[b + 1] = p + if p > 0 and p < r:size() then + local w = if version < 1 then r:peekU8(p) else r:peekU8(p) * 256 + r:peekU8(p + 1) + nch = math.max(nch, w) + end + end + if nch > 64 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " tracks") + end + local m = Tracker.newModule("med", nch, "xm") + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.envRowHold = "amiga", true + local stSlides = bit32.band(flags, 0x20) ~= 0 + m.flags.fastSlides, m.flags.fastPortas = not stSlides, not stSlides + local hardwareMix = version < 2 or bit32.band(flags2, 0x80) == 0 + m.flags.amigaLimits = hardwareMix + -- the expansion data: instrument extras and names, the song name + local ext = { instrExt = 0, instrExtN = 0, instrExtSize = 0, infoOff = 0, infoN = 0, infoSize = 0, nameOff = 0, nameLen = 0, annoOff = 0, annoLen = 0 } + if expOff > 0 then + local e = r:sub(expOff, 80) + e:skip(4) + ext.instrExt, ext.instrExtN, ext.instrExtSize = e:u32be(), e:u16be(), e:u16be() + ext.annoOff, ext.annoLen = e:u32be(), e:u32be() + ext.infoOff, ext.infoN, ext.infoSize = e:u32be(), e:u16be(), e:u16be() + e:skip(16) + ext.nameOff, ext.nameLen = e:u32be(), e:u32be() + if e.err then + ext.instrExt, ext.infoOff, ext.nameOff, ext.annoOff = 0, 0, 0, 0 + end + end + if ext.nameOff > 0 and ext.nameLen > 0 then + m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) + end + -- instruments and samples + local needInstruments = false + local instruments, samples = {}, {} + local unsupported = {} + for ins = 1, numSamples do + local smpHead = sh:sub((ins - 1) * 8, 8) + local loopStart, loopLen = smpHead:u16be() * 2, smpHead:u16be() * 2 + local midiCh, _midiPreset, volume, transpose = smpHead:u8(), smpHead:u8(), smpHead:u8(), smpHead:i8() + local x = { hold = 0, decay = 0, finetune = 0, pitch = 0, flags = 0, loopStart = 0, loopLen = 0, volume = 0 } + local xsize = 0 + if ext.instrExt > 0 and ins <= ext.instrExtN then + xsize = ext.instrExtSize + local xr = r:sub(ext.instrExt + (ins - 1) * xsize, xsize) + x.hold, x.decay = xr:u8(), xr:u8() + xr:skip(1) + x.finetune = xr:i8() + x.pitch, x.flags = xr:u8(), xr:u8() + xr:skip(4) + x.loopStart, x.loopLen = xr:u32be(), xr:u32be() + x.volume = xr:u8() + end + local name = "" + if ext.infoOff > 0 and ins <= ext.infoN then + name = r:sub(ext.infoOff + (ins - 1) * ext.infoSize, math.min(ext.infoSize, 40)):fixed(math.min(ext.infoSize, 40)) + end + local instr = Tracker.newInstrument(name) + instruments[ins] = instr + local iptr = if smpOff > 0 then r:sub(smpOff + (ins - 1) * 4, 4):u32be() else 0 + local length, typ = 0, 0 + if iptr > 0 then + local ih = r:sub(iptr, 6) + length, typ = ih:u32be(), ih:i16be() + if ih.err then + length, typ = 0, 0 + end + end + local isSynth = typ < 0 + local masked = bit32.band(typ % 65536, 0x0F) + local count = if not isSynth then (SAMPLES_PER_TYPE[masked] or 1) else 1 + if isSynth then + table.insert(unsupported, "synth / hybrid instrument " .. ins) + needInstruments = needInstruments or typ == -1 or typ == -2 + end + if midiCh > 0 and midiCh <= 16 then + needInstruments = true + table.insert(unsupported, "MIDI instrument " .. ins) + end + local first = #samples + 1 + -- keymap: one sample per note, multi-octave samples spread over the octaves + for n = 1, 120 do + instr.sampleMap[n] = first + end + if count > 1 then + needInstruments = true + for n = 1, 120 do + local note = n + 11 + transpose -- OpenMPT's keyboard index + if note < 0 then + note = -note % 12 + end + local oct = math.clamp(note // 12 - 4, 0, 7) + instr.sampleMap[n] = first + OCT_SAMPLE[count - 1][oct + 1] + instr.noteMap[n] = math.clamp(1 + note + OCT_TRANSPOSE[count - 1][oct + 1] - 12, 1, 120) + end + transpose = 0 + elseif masked == 7 then + needInstruments = true -- two extra-low octaves + for n = 1, 120 do + instr.noteMap[n] = math.clamp(n - 24, 1, 120) + end + end + if midiCh == 0 then + -- notes past the mixer's range fold down (by octaves) + local top = 61 + (if hardwareMix then 24 else 36) + for n = 1, 120 do + local real = instr.noteMap[n] + 12 + transpose + if real >= top then + instr.noteMap[n] = math.max(1, instr.noteMap[n] - ((real - top + 12) - (real - top + 12) % 12)) + end + end + end + -- sample data + local list = {} + for i = 0, count - 1 do + local s = Tracker.newSample(name) + s.volume = math.min(volume, 64) + s.relativeNote = transpose + list[i + 1] = s + samples[first + i] = s + end + local hasLoop = loopLen > 2 + if not isSynth and iptr > 0 and length > 0 then + local bits = if bit32.band(typ, 0x10) ~= 0 then 16 else 8 + local stereo = bit32.band(typ, 0x20) ~= 0 + local nchs = if stereo then 2 else 1 + local bytes = length * nchs + local frames = length // (bits // 8) + if count > 1 then + frames //= (2 ^ count - 1) + end + local pos = r.base + iptr + 6 + local ls, le = loopStart, loopStart + loopLen + for i = 1, count do + local s = list[i] + local spec = { bits = bits, signed = true, bigEndian = true, channels = nchs, planar = stereo, delta = bit32.band(typ, 0x40) ~= 0, limit = math.min(r.limit, r.base + iptr + 6 + bytes) } + local ok, err = Load.readSample(r.buf, pos, frames, spec, s, budget) + if not ok then + return nil, err + end + pos += frames * nchs * bits // 8 + if hasLoop then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + frames, ls, le = frames * 2, ls * 2, le * 2 + end + end + -- the instrument extras + if xsize > 0 then + if x.hold > 0 and not isSynth then + local env = Tracker.newEnvelope() + env.enabled = true + local fall = x.hold + (if x.decay > 0 then 64 // x.decay else 0) + if x.hold == 1 then + env.ticks, env.values = { 0, fall }, { 64, 0 } + else + env.ticks, env.values = { 0, x.hold - 1, fall }, { 64, 64, 0 } + end + instr.volEnv = env + instr.fadeout = if x.decay > 0 then math.min(x.decay * 512, 65535) else 32767 + needInstruments = true + end + if xsize > 4 and x.pitch ~= 0 then + instr.noteMap[24 - 12 + 1] = math.clamp(x.pitch + 1 + 23 - 12, 1, 120) + needInstruments = true + end + if xsize > 18 then + instr.globalVolume = (x.volume + 1) // 2 * 2 + end + local ls, le = x.loopStart, x.loopStart + x.loopLen + for _, s in list do + s.finetune = math.clamp(x.finetune * 16, -128, 127) + if not isSynth and xsize > 14 then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + ls, le = ls * 2, le * 2 + end + if xsize > 5 then + if not isSynth then + s.loopType = if bit32.band(x.flags, 1) == 0 then 0 elseif bit32.band(x.flags, 8) ~= 0 then 2 else 1 + end + if bit32.band(x.flags, 4) ~= 0 then + s.globalVolume = 0 + end + end + end + end + end + -- the play order: MMD0 / MMD1 a sequence of blocks; MMD2 / MMD3 sections of play sequences (stop / jump commands) + local jumps: { [number]: number } = {} + local preamp = 32 + if version < 2 then + if songLength > 256 then + return nil, Err.new(Err.CORRUPT, "bad song length") + end + for i = 1, songLength do + m.order[i] = seq:u8() + end + for i = 1, nch do + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + if i <= 16 then + m.channelVolume[i] = math.min(trackVol[i], 64) + end + end + else + local s2 = song:sub(4, 256) + local playSeqTable, sectionTable, trackVolsOff = s2:u32be(), s2:u32be(), s2:u32be() + local numTracks, numPlaySeqs = s2:u16be(), s2:u16be() + local trackPanOff, flags3, volAdjust = s2:u32be(), s2:u32be(), s2:u16be() + if numTracks < 1 or numTracks > 64 then + return nil, Err.new(Err.CORRUPT, "bad track count") + end + local freePan = not hardwareMix and bit32.band(flags3, 2) ~= 0 + if volAdjust > 0 then + preamp = (preamp * math.min(volAdjust, 800) + 50) // 100 + end + if freePan then + preamp //= 2 + end + if trackVolsOff > 0 then + for i = 1, nch do + m.channelVolume[i] = math.min(r:sub(trackVolsOff + i - 1, 1):u8(), 64) + end + end + local pans = (freePan or version > 2) and trackPanOff > 0 + for i = 1, nch do + if pans then + m.channelPan[i] = (math.clamp(r:sub(trackPanOff + i - 1, 1):i8(), -16, 16) + 16) * 8 + else + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + end + end + local sections = r:sub(sectionTable, songLength * 2) + for _ = 1, songLength do + local sec = sections:u16be() + if sections.err then + break + end + if sec <= numPlaySeqs then + local ps = r:sub(playSeqTable + sec * 4, 4):u32be() + local pr = r:sub(ps, 42) + pr:skip(32) + local cmdTable = pr:u32be() + pr:skip(4) + local len = pr:u16be() + if not pr.err then + if #m.order > 0 then + table.insert(m.order, 254) + end + local start = #m.order + local er = r:sub(ps + 42, len * 2) + for _ = 1, len do + local b = er:u16be() + if er.err then + break + end + if b < 0x8000 then + table.insert(m.order, math.min(b, 253)) + end + end + if cmdTable > 0 then + local cr = r:sub(cmdTable) + for _ = 1, 4096 do + local off, c, extra = cr:u16be(), cr:u8(), cr:u8() + local arg = if extra >= 2 then cr:sub(cr:tell(), 2):u16be() else 0 + cr:skip(extra) + local at = start + off + 1 + if cr.err or off == 0xFFFF or at > #m.order then + break + end + if c == 1 then + m.order[at] = 255 + elseif c == 2 then + jumps[at] = arg + m.order[at] = 254 + end + end + end + end + end + end + end + m.preamp = preamp + -- tempo, speed, volume, the pattern context + local ctx: Ctx = { + transpose = 36 + playTranspose - (if version > 2 then 24 else 0), + is8Ch = bit32.band(flags, 0x40) ~= 0, + softMix = bit32.band(flags2, 0x80) ~= 0, + bpm = bit32.band(flags2, 0x20) ~= 0, + rowsPerBeat = 1 + bit32.band(flags2, 0x1F), + volHex = bit32.band(flags, 0x10) ~= 0, + vol7bit = false, + } + m.tempo = tempoToBpm(defTempo, ctx) + m.speed = math.clamp(tempo2, 1, 32) + if masterVol > 0 then + m.globalVolume = math.min(masterVol, 64) * 2 + end + -- blocks + for b = 0, numBlocks - 1 do + local p = blockPtr[b + 1] + local pat, high = nil, false + if p and p > 0 then + pat, high = readBlock(r, p, version, ctx, nch) + end + m.patterns[b + 1] = pat or Tracker.newPattern(64, nch) + needInstruments = needInstruments or high + end + -- play-sequence jumps: a jump effect at the end of the block before the command + for at, to in jumps do + local prev = m.order[at - 1] + if prev and prev < 254 and m.patterns[prev + 1] then + -- the block may be played elsewhere: give this order entry its own copy + local src = m.patterns[prev + 1] + local cp = Tracker.newPattern(src.rows, nch) + buffer.copy(cp.data, 0, src.data) + table.insert(m.patterns, cp) + m.order[at - 1] = #m.patterns - 1 + Load.writeEffect(m, #m.patterns - 1, cp.rows - 1, 0xB, math.min(to, 255), "prev") + end + end + m.samples = samples + if needInstruments then + m.instrumentMode = true + m.instruments = instruments + end + if #unsupported > 0 then + m.meta.unsupported = unsupported + end + if ext.annoOff > 0 and ext.annoLen > 1 then + m.meta.message = r:sub(ext.annoOff, ext.annoLen - 1):string(math.min(ext.annoLen - 1, r:size())) + end + m.meta.source = { format = "med", version = "MMD" .. version, instruments = needInstruments } + 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 Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Med.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Med diff --git a/tests/music/med.luau b/tests/music/med.luau new file mode 100644 index 0000000..ef53518 --- /dev/null +++ b/tests/music/med.luau @@ -0,0 +1,22 @@ +-- music/med tests: generated MED / OctaMED modules (tools/fixtures/med.py: MMD0, MMD1 with hold / decay and finetune, +-- MMD2 with a play sequence, an IFF 3-octave sample) 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 Med = require("@formats/music/med") +local Cases = require("@tests/gen/med_cases") + +local t = T.suite("med") + +t:eq(Med.name, "med", "name") +t:eq(Med.category, "music", "category") +t:check(Med.caps.decode and not Med.caps.encode, "caps") + +local mods = S.against(t, Med, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "xm") +t:check(mods[2] and mods[2].instrumentMode and mods[2].instruments[1].volEnv ~= nil, "MMD1 hold / decay: an instrument envelope") +t:check(mods[2] and mods[2].title == "med test", "song name") +t:check(mods[3] and mods[3].channels == 6 and mods[3].meta.source.version == "MMD2", "MMD2") +t:check(mods[4] and mods[4].instrumentMode and #mods[4].samples == 4 and mods[4].samples[3].length == 128, "IFF 3-octave sample") + +t:fuzz("decode", S.fuzzer(Med), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index f321a65..ec54313 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -781,3 +781,115 @@ def write_okt(samples, orders, patterns, cmod=(0, 0, 0, 0), speed=6): for s in samples: out += chunk(b"SBOD", s["data"]) return bytes(out) + + +def write_med(version, samples, blocks, sequence, tempo=125, tempo2=6, flags=0, flags2=0, trackvols=None, + pans=None, master=64, play_transpose=0, sections=None, title=None): + """an MMD0 .. MMD3 module. samples: [{data (signed 8-bit bytes, or big-endian 16-bit with bits 16), bits, volume, + transpose, loop: (start, length) in bytes (even) | None, hold, decay, finetune, octaves (IFF multi-octave count: + data holds the octaves from the lowest, each twice as long)}]; blocks: [[row: [(note, ins, cmd, param)] * tracks] + * rows] with note 0 = none else the MED note (1 = C-1; MMD1+: 0x80 = note off); sequence: block numbers (MMD0 / 1) + or the play sequence (MMD2 / 3; sections: [[playseq numbers]] and playseqs = [sequence])""" + out = bytearray(52) + song_at = 52 + out += b"\0" * (63 * 8 + 284) + need_ext = any(s.get("hold") or s.get("finetune") for s in samples) or title is not None + + def align(): + while len(out) % 4: + out.append(0) + + # blocks + block_ptrs = [] + for blk in blocks: + align() + block_ptrs.append(len(out)) + ntr = len(blk[0]) + if version == 0: + out += bytes([ntr, len(blk) - 1]) + else: + out += struct.pack(">HHI", ntr, len(blk) - 1, 0) + for row in blk: + for (note, ins, cmd, param) in row: + if version == 0: + out += bytes([(note & 0x3F) | ((ins & 0x10) << 3) | ((ins & 0x20) << 1), ((ins & 15) << 4) | (cmd & 15), param]) + else: + out += bytes([note, ins & 0x3F, cmd, param]) + align() + block_arr = len(out) + for p in block_ptrs: + out += struct.pack(">I", p) + # instruments + inst_ptrs = [] + for s in samples: + align() + inst_ptrs.append(len(out)) + oct_ = s.get("octaves", 1) + typ = {1: 0, 5: 1, 3: 2, 2: 3, 4: 4, 6: 5, 7: 6}[oct_] | (0x10 if s.get("bits", 8) == 16 else 0) + out += struct.pack(">Ih", len(s["data"]), typ) + s["data"] + align() + smp_arr = len(out) + for p in inst_ptrs: + out += struct.pack(">I", p) + # play sequences (MMD2 / 3) + seq_info = None + if version >= 2: + align() + psq = [] + for sq in [sequence]: + psq.append(len(out)) + out += name("seq", 32) + struct.pack(">IIH", 0, 0, len(sq)) + b"".join(struct.pack(">H", b) for b in sq) + align() + ps_table = len(out) + for p in psq: + out += struct.pack(">I", p) + sec_table = len(out) + secs = sections or [0] + for sc in secs: + out += struct.pack(">H", sc) + align() + tv = len(out) + out += bytes(trackvols or [64] * len(blocks[0][0])) + tp = 0 + if pans: + tp = len(out) + out += bytes([p & 255 for p in pans]) + seq_info = (ps_table, sec_table, tv, tp, len(secs)) + # expansion: instrument extras + song name + exp = 0 + if need_ext: + align() + ie = len(out) + for s in samples: + ls, ll = s.get("loop") or (0, 0) + out += struct.pack(">BBBbBBHBBIIBBH", s.get("hold", 0), s.get("decay", 0), 0, s.get("finetune", 0), 0, + 1 if s.get("loop") else 0, 0, 0, 0, ls, ll, 127, 0, 0) + nm = (title or "").encode() + b"\0" + na = len(out) + out += nm + align() + exp = len(out) + e = bytearray(80) + struct.pack_into(">IIHH", e, 0, 0, ie, len(samples), 22) + struct.pack_into(">II", e, 44, na, len(nm)) + out += e + # the song header + for i, s in enumerate(samples): + ls, ll = s.get("loop") or (0, 0) + struct.pack_into(">HHBBBb", out, song_at + 8 * i, ls // 2, ll // 2, 0, 0, s.get("volume", 64), s.get("transpose", 0)) + sh = song_at + 63 * 8 + if version < 2: + struct.pack_into(">HH", out, sh, len(blocks), len(sequence)) + out[sh + 4:sh + 4 + len(sequence)] = bytes(sequence) + else: + ps_table, sec_table, tv, tp, nsec = seq_info + struct.pack_into(">HH", out, sh, len(blocks), nsec) + struct.pack_into(">IIIHHIIHH", out, sh + 4, ps_table, sec_table, tv, len(blocks[0][0]), 1, tp, 0, 100, 0) + struct.pack_into(">HbBBB", out, sh + 260, tempo, play_transpose, flags, flags2, tempo2) + out[sh + 266:sh + 282] = bytes((trackvols or [64] * 16)[:16]) + bytes(max(0, 16 - len(trackvols or [0] * 16))) + out[sh + 282] = master + out[sh + 283] = len(samples) + hdr = bytearray(b"MMD" + bytes([0x30 + version])) + hdr += struct.pack(">IIHHIB3sIIII11sB", len(out), song_at, 0, 0, block_arr, 0, b"\0\0\0", smp_arr, 0, exp, 0, b"\0" * 11, 0) + out[0:52] = hdr + return bytes(out) diff --git a/tools/fixtures/med.py b/tools/fixtures/med.py new file mode 100644 index 0000000..7e8a2ea --- /dev/null +++ b/tools/fixtures/med.py @@ -0,0 +1,113 @@ +# MED fixtures (tools/fixtures.py): generated MED / OctaMED modules (MMD0, MMD1 with instrument extras, MMD2 with a play +# sequence) exercising the effects, rendered by openmpt123. +# tests/gen/med_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, cmd=0, param=0): + p[row][ch] = (note, ins, cmd, param) + + +def samples(extras=False): + s = [ + {"data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)}, + {"data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 44, "loop": (0, 64)}, + {"data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64), "transpose": -12}, + {"data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 60}, + {"data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "loop": (0, 32)}, + ] + if extras: + s[0]["hold"], s[0]["decay"] = 6, 4 # hold / decay: a volume envelope + s[1]["finetune"] = 3 + s[4]["hold"], s[4]["decay"] = 2, 0 + return s + + +def song_basic(keep=None, version=0): + a, b = empty(4), empty(4, 32) + mel = [13, 17, 20, 25, 20, 17, 15, 13] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, 2, 0, 0, 0, 0x0, 0x37) # arpeggio + put(a, 0, 1, 1, 2) + put(a, 4, 1, 0, 0, 0x1, 0x02) + put(a, 12, 1, 0, 0, 0x2, 0x03) + put(a, 20, 1, 13, 2, 0xC, 0x32) # volume (decimal: 32) + put(a, 24, 1, 0, 0, 0xD, 0x03) # volume slide down (every tick) + put(a, 28, 1, 0, 0, 0xD, 0x20) + put(a, 32, 1, 8, 2, 0x4, 0x34) # vibrato (twice as deep) + put(a, 40, 1, 13, 2) + put(a, 41, 1, 20, 0, 0x3, 0x10) # tone portamento + put(a, 48, 1, 0, 0, 0x5, 0x01) + for r in range(0, 64, 8): + put(a, r, 3, 13, 4, 0xC, 0x64 - r) + put(a, 2, 2, 25, 3) + put(a, 36, 2, 1, 5, 0xF, 0xF2) # delay note + put(a, 44, 2, 1, 5, 0xF, 0xF1) # play twice + put(a, 34, 3, 0, 0, 0x9, 0x04) # secondary speed + put(a, 50, 3, 0, 0, 0xF, 0x90) # tempo 0x90 (BPM 144 / 0.264...) + put(b, 0, 0, 13, 1) + put(b, 8, 1, 20, 2) + put(b, 16, 2, 13, 3, 0x8, 0x40) # panning (8xx) + put(b, 24, 3, 25, 5, 0xF, 0x00) # pattern break + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(4): + if ch not in keep and row[ch][2] not in (0x9, 0xF): + row[ch] = (0, 0, 0, 0) + return T.write_med(version, samples(version > 0), [a, b], [0, 1, 0], tempo=0x21 if version == 0 else 125, tempo2=6, + flags=0x10 if version > 0 else 0, flags2=0x23 if version > 0 else 0, title="med test" if version > 0 else None) + + +def song_mmd2(): + """MMD2: 6 tracks, a play sequence with a section, ProTracker-style slides, BPM tempo, track volumes""" + a = empty(6, 48) + for r in range(0, 48, 4): + put(a, r, r // 4 % 6, 13 + (r // 4) % 12, 1 + r // 4 % 5) + put(a, 6, 1, 0, 0, 0x1, 0x04) + put(a, 10, 2, 0, 0, 0xD, 0x02) + put(a, 20, 4, 0, 0, 0x16, 0x00) # loop start + put(a, 23, 4, 0, 0, 0x16, 0x01) # loop once + put(a, 30, 5, 0, 0, 0x1F, 0x20) # note delay 2 + put(a, 44, 0, 0, 0, 0x1D, 0x08) # break to row 8 (hex) + b = empty(6, 16) + put(b, 0, 0, 25, 2, 0x0C, 0x20) + put(b, 8, 3, 30, 4) + return T.write_med(2, samples(), [a, b], [0, 1], tempo=120, tempo2=5, flags=0x20 | 0x10, flags2=0x20 | 3, + trackvols=[64, 48, 64, 32, 64, 64]) + + +def song_octaves(): + """MMD1 with an IFF 3-octave sample (three copies of a waveform, each twice as long as the last): a keymap""" + w = T.s8(T.synth("saw", 32, 32, 0.7)) + T.s8(T.synth("saw", 64, 64, 0.7)) + T.s8(T.synth("saw", 128, 128, 0.7)) + smp = [{"data": w, "volume": 64, "octaves": 3, "loop": (0, 32)}, samples()[0]] + a = empty(2, 48) + for i, n in enumerate([1, 8, 13, 20, 25, 32, 37, 30, 18, 6, 13, 25]): + put(a, i * 4, 0, n, 1) + put(a, i * 4 + 2, 1, n, 2, 0xC, 0x20) + return T.write_med(1, smp, [a], [0], tempo=125, tempo2=6, flags=0x10, flags2=0x23) + + +def generate(ctx): + cases = [] + for nm, data in (("mmd0", song_basic()), ("mmd1", song_basic(version=1)), ("mmd2", song_mmd2()), ("octaves", song_octaves())): + ref = T.reference(ctx, data, "med") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("med_cases", cases) From 26fa88737062cce836bbc1c618d8c7b8c0fb2b56 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:54:54 -0500 Subject: [PATCH 11/12] ws-audio2: music/umx (Unreal music packages): the package tables parsed, the music export's module handed to a new api hook opts.decodeModule(buf, format?) src/Formats/init.luau: withHooks adds opts.decodeModule (F.load of the bytes as music) next to decodeImage / openAudio, so a format never requires another; docs/API.md lists it. Backward compatible (a new optional hook). --- docs/API.md | 2 + docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/init.luau | 11 +- src/Formats/music/umx/init.luau | 222 ++++++++++++++++++++++++++++++++ tests/music/umx.luau | 51 ++++++++ tools/fixtures/_tracker.py | 36 ++++++ tools/fixtures/umx.py | 34 +++++ 8 files changed, 368 insertions(+), 1 deletion(-) create mode 100644 src/Formats/music/umx/init.luau create mode 100644 tests/music/umx.luau create mode 100644 tools/fixtures/umx.py diff --git a/docs/API.md b/docs/API.md index 7077b3d..9560c6b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -84,6 +84,8 @@ A format never requires another format, so the api passes these to decoders / en - `opts.decodeImage(buf) -> Image | nil, Err` and `opts.encodeImage(img, format) -> buffer | nil, Err`: images inside other files (ICO PNG entries, PSD / glTF / 3MF textures, MJPEG frames, ...). +- `opts.decodeModule(buf, format?) -> Module | nil, Err`: tracker modules inside other files (the module of an Unreal + `.umx` package), loaded as music. - `opts.openAudio(demuxer, track) -> Decoder | nil, Err`: audio tracks of video containers (wrapped by `containers/AudioWrap` and opened as the matching audio format). - `opts.plugins` (default `F.plugins`): injected optional dependencies, e.g. `F.plugins.brep` (a B-rep kernel for diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 3a879ca..55996a1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -86,6 +86,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | | music | stm | .stm | yes | - | render: true, channels: 4, 4 | `tests/music/stm.luau` | | music | ult | .ult | yes | - | render: true, channels: 1, 32 | `tests/music/ult.luau` | +| music | umx | .umx | yes | - | render: true, container: true | `tests/music/umx.luau` | | music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index b7a0d53..2bea083 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -986,6 +986,18 @@ local list: { Entry } = { return require("@formats/music/ult") end, }, + { + name = "umx", + category = "music", + path = "music/umx", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, + load = function() + return require("@formats/music/umx") + end, + }, { name = "xm", category = "music", diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 5774bf3..a1970da 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -276,6 +276,9 @@ end -- the embedded parts) when called directly. -- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. -- +-- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded +-- as music (sniffed, or as the given format). +-- -- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets -- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / -- FLAC as they are), opened through F.open with that format. @@ -299,7 +302,7 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?) end local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil then + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then return o end local c = table.clone(o) @@ -319,6 +322,12 @@ local function withHooks(o: Options): Options return F.save(img, nil, { format = format, category = "image" }) end end + if c.decodeModule == nil then + -- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format + c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?) + return F.load(b, { category = "music", format = format }) + end + end return c end diff --git a/src/Formats/music/umx/init.luau b/src/Formats/music/umx/init.luau new file mode 100644 index 0000000..47b3640 --- /dev/null +++ b/src/Formats/music/umx/init.luau @@ -0,0 +1,222 @@ +--!strict +-- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package +-- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): +-- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each +-- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first +-- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and +-- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is +-- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it. +-- Not supported: Unreal Engine 2+ packages (sounds, .uax), 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") + +-- ------------------------------------------------------------------------------------------------ contract +local Umx = { + name = "umx", + category = "music", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, +} + +export type DecodeOptions = { + decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, -- loads the inner module (the api passes it) + index: number?, -- which music export to load (1-based, default 1) +} + +export type Entry = { name: string, data: buffer, format: string? } + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "\xC1\x83\x2A\x9E" + +-- ------------------------------------------------------------------------------------------------ sniff +type Header = { version: number, nameCount: number, nameOffset: number, exportCount: number, exportOffset: number, importCount: number, importOffset: number } + +local function header(r: Bytes.Reader): Header? + if r:size() < 36 or r:peek(4) ~= MAGIC then + return nil + end + local h = r:sub(4, 32) + local version = h:u16le() + h:skip(6) + local hd: Header = { + version = version, + nameCount = h:u32le(), + nameOffset = h:u32le(), + exportCount = h:u32le(), + exportOffset = h:u32le(), + importCount = h:u32le(), + importOffset = h:u32le(), + } + if h.err or hd.nameOffset < 36 or hd.exportOffset < 36 or hd.importOffset < 36 then + return nil + end + if hd.nameCount == 0 or hd.exportCount == 0 or hd.importCount == 0 or hd.nameCount > 2 ^ 20 or hd.exportCount > 2 ^ 20 or hd.importCount > 2 ^ 20 then + return nil + end + return hd +end + +-- a compact index: sign and 6 bits, then 7 bits per byte while the continue bits are set +local function index(r: Bytes.Reader): number + local b = r:u8() + local neg = b >= 0x80 + local v = b % 64 + if bit32.band(b, 0x40) ~= 0 then + local shift = 6 + repeat + b = r:u8() + v += (b % 128) * 2 ^ shift + shift += 7 + until b < 0x80 or shift >= 32 + end + return if neg then -v else v +end + +-- the name table (lower case) +local function names(r: Bytes.Reader, h: Header): { string } + local list = {} + local nr = r:sub(h.nameOffset) + for _ = 1, math.min(h.nameCount, 65536) do + if nr:remaining() < 5 then + break + end + if h.version >= 64 then + index(nr) + end + table.insert(list, string.lower(nr:cstring(1024))) + nr:skip(4) + end + return list +end + +function Umx.sniff(r: Bytes.Reader): number + local h = header(r) + if not h then + return 0 + end + return if table.find(names(r, h), "music") then 1 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format: +-- a guess from the inner module's signature: "it", "s3m", "xm", "mod") +function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local h = header(r) + if not h then + return nil, Err.new(if r:size() < 36 then Err.TRUNCATED else Err.CORRUPT, "not an Unreal package") + end + local nm = names(r, h) + -- imports: the class names objects refer to + local classes = {} + local ir = r:sub(h.importOffset) + for _ = 1, math.min(h.importCount, 65536) do + if ir:remaining() < 4 then + break + end + index(ir) + index(ir) + if h.version >= 60 then + ir:skip(4) + else + index(ir) + end + local obj = index(ir) + if obj >= 0 and obj < #nm then + table.insert(classes, obj) + end + end + local out: { Entry } = {} + local er = r:sub(h.exportOffset) + for _ = 1, math.min(h.exportCount, 65536) do + if er:remaining() < 8 then + break + end + local cls = -index(er) - 1 -- ~index: the import the class is + index(er) + if h.version >= 60 then + er:skip(4) + end + local objName = index(er) + er:skip(4) + local size, offset = index(er), index(er) + if er.err then + break + end + if cls >= 0 and cls < #classes and nm[classes[cls + 1] + 1] == "music" and size > 0 and offset > 36 then + local c = r:sub(offset, size) + if h.version < 40 then + c:skip(8) + end + if h.version < 60 then + c:skip(16) + end + index(c) -- the property list's "none" + if h.version >= 120 then + index(c) + c:skip(8) + elseif h.version >= 100 then + c:skip(4) + index(c) + c:skip(4) + elseif h.version >= 62 then + index(c) + c:skip(4) + else + index(c) + end + local len = index(c) + if not c.err and len > 0 and len <= c:remaining() then + local data = c:bytes(len) + local sig = Bytes.reader(data) + local fmt = if sig:peek(4) == "IMPM" then "it" elseif sig:peek(4, 44) == "SCRM" then "s3m" elseif sig:peek(17) == "Extended Module: " then "xm" elseif buffer.len(data) >= 1084 then "mod" else nil + table.insert(out, { name = nm[objName + 1] or "", data = data, format = fmt }) + end + end + end + return out, nil +end + +function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, err = Umx.extract(r) + if not list then + return nil, err + end + local i = opts and opts.index or 1 + local e = list[i] + if not e then + return nil, Err.new(Err.CORRUPT, "no music export" .. (if i > 1 then " " .. i else "")) + end + local hook = opts and opts.decodeModule + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded " .. (e.format or "tracker") .. " module needs opts.decodeModule (F.load passes it; Umx.extract gives the bytes)") + end + local m, merr = hook(e.data, nil) + if not m then + return nil, merr + end + if type(m) ~= "table" or m.kind ~= "music" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded module is not a tracker module") + end + local h = header(r) :: Header + m.meta = if type(m.meta) == "table" then m.meta else {} + m.meta.container = { format = "umx", name = e.name, version = h.version, count = #list } + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Umx.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Umx diff --git a/tests/music/umx.luau b/tests/music/umx.luau new file mode 100644 index 0000000..edb61f6 --- /dev/null +++ b/tests/music/umx.luau @@ -0,0 +1,51 @@ +-- music/umx tests: Unreal packages wrapping generated S3M / IT modules (tools/fixtures/umx.py): the export found and +-- unwrapped (bytes equal to the module put in), loaded through the api's decodeModule hook and rendered like +-- openmpt123 renders the package, UNSUPPORTED without the hook, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local F = require("@formats") +local Umx = require("@formats/music/umx") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/umx_cases") + +local t = T.suite("umx") + +t:eq(Umx.name, "umx", "name") +t:eq(Umx.category, "music", "category") +t:check(Umx.caps.decode and not Umx.caps.encode, "caps") + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } +local function hook(b: buffer, format: string?): (any, any) + return F.load(b, { category = "music", format = format }) +end + +for _, c in Cases do + local r = Bytes.reader(buffer.fromstring(c.data)) + t:check(Umx.sniff(r) == 1, c.name .. ": sniff") + local list = Umx.extract(r) + t:check(list and #list == 1 and list[1].name == string.lower(c.name) and list[1].format == c.format, c.name .. ": extract") + t:eq(list and buffer.tostring(list[1].data), c.inner, c.name .. ": the embedded module's bytes") + local _, err = Umx.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(err and err.code == F.Err.UNSUPPORTED, c.name .. ": no hook: UNSUPPORTED") + local m, merr = Umx.decode(Bytes.reader(buffer.fromstring(c.data)), { decodeModule = hook }) + t:check(m and m.format == c.format and m.meta.container.format == "umx", c.name .. ": decode " .. tostring(merr)) + local viaApi = F.load(c.data) + t:check(viaApi and viaApi.kind == "music" and viaApi.meta.container and viaApi.meta.container.name == string.lower(c.name), c.name .. ": F.load") + t:eq(F.detect(c.data), "umx", c.name .. ": F.detect") + local dec = m:render({ sampleRate = S.SR }) + 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 res = S.compare(S.features(buf, frames), c.ref) + t:note("%-10s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, res.gainDb, res.envErr, res.spectral, res.balance, dec.duration) + t:check(math.abs(res.gainDb) < THRESH.gainDb and res.envErr < THRESH.envErr, c.name .. ": loudness") + t:check(res.spectral > THRESH.spectral and res.balance < THRESH.balance, c.name .. ": spectrum, balance") + local d2 = F.open(c.data) + t:check(d2 and d2.channels == 2, c.name .. ": F.open renders") +end + +t:fuzz("decode", function(b: buffer) + local m = Umx.decode(Bytes.reader(b), { decodeModule = hook }) + Umx.extract(Bytes.reader(b)) + return m +end, S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index ec54313..bc53d6c 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -893,3 +893,39 @@ def write_med(version, samples, blocks, sequence, tempo=125, tempo2=6, flags=0, hdr += struct.pack(">IIHHIB3sIIII11sB", len(out), song_at, 0, 0, block_arr, 0, b"\0\0\0", smp_arr, 0, exp, 0, b"\0" * 11, 0) out[0:52] = hdr return bytes(out) + + +def umx_index(v): + """an Unreal compact index""" + neg, v = v < 0, abs(v) + out = bytearray([(0x80 if neg else 0) | (v & 0x3F) | (0x40 if v > 0x3F else 0)]) + v >>= 6 + while v: + out.append((v & 0x7F) | (0x80 if v > 0x7F else 0)) + v >>= 7 + return bytes(out) + + +def write_umx(modules, version=69): + """an Unreal package (UT99-era, package version 61..99) whose exports are Music objects: modules = [(object + name, module bytes)]""" + names = ["None", "Music", "Core", "Class"] + [n for n, _ in modules] + out = bytearray(36) + name_at = len(out) + for n in names: + b = n.encode() + b"\0" + out += (umx_index(len(b)) if version >= 64 else b"") + b + struct.pack(" Date: Sat, 31 Oct 2026 14:58:37 -0500 Subject: [PATCH 12/12] ws-audio2: docs/guide/music.md: the other tracker formats (table rows, Module.engine, More tracker formats with tested snippets; docs_av inputs mtm / med / umx); bench: render 669 / med --- docs/guide/music.md | 51 +++++++++++++++++++++++++++++++++++++-- tools/bench.luau | 26 ++++++++++++++++++++ tools/fixtures/docs_av.py | 15 +++++++++--- 3 files changed, 87 insertions(+), 5 deletions(-) diff --git a/docs/guide/music.md b/docs/guide/music.md index 369929d..b156c9f 100644 --- a/docs/guide/music.md +++ b/docs/guide/music.md @@ -1,6 +1,7 @@ # Music -Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT) load as a **Module**: +Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT, and the +[other trackers](#more-tracker-formats): MTM, 669, STM, ULT, OKT, MED, PTM, FAR, UMX) load as a **Module**: the patterns, the order list, the samples and the instruments. Standard MIDI files load as a **Midi**: tracks of timed events. Both render to the standard audio [Decoder](audio.md#decoder), so every music file can also be played, analysed or saved as audio. MIDI renders through a SoundFont 2 bank, or through a small built-in set of @@ -26,7 +27,8 @@ assert(audio.channels == 2 and audio.sampleRate == 44100) | Field | Type | Meaning | |---|---|---| | `kind` | `"music"` | | -| `format` | string | `"mod"`, `"s3m"`, `"xm"` or `"it"`: the effect family the engine plays | +| `format` | string | the format it was read from: `"mod"`, `"s3m"`, `"xm"`, `"it"`, `"mtm"`, `"669"`, `"med"`, ... | +| `engine` | string? | the effect family the engine plays (`"mod"`, `"s3m"`, `"xm"`, `"it"`); absent: the same as `format`. Set by the [other trackers](#more-tracker-formats) | | `title` | string | | | `channels` | number | pattern channels | | `speed`, `tempo` | number | initial ticks per row, and BPM (a tick lasts `2.5 / tempo` seconds) | @@ -312,9 +314,52 @@ assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead") | s3m, it | yes | - | Module | | midi (.mid, .kar, RMID) | yes | yes (SMF) | Midi | | sf2 | yes | - | SoundFont | +| mtm (MultiTracker) | yes | - | Module (xm family) | +| 669 (Composer 669, UNIS 669) | yes | - | Module (s3m family) | +| stm (Scream Tracker 2) | yes | - | Module (s3m family) | +| ult (UltraTracker) | yes | - | Module (it family) | +| okt (Oktalyzer) | yes | - | Module (it family) | +| med (MED / OctaMED MMD0..MMD3) | yes | - | Module (xm family) | +| ptm (PolyTracker) | yes | - | Module (it family) | +| far (Farandole Composer) | yes | - | Module (s3m family) | +| umx (Unreal package) | yes | - | the embedded IT / S3M / XM / MOD Module | See [FORMATS.md](../FORMATS.md) for each format's capabilities. +### More tracker formats + +MultiTracker, Composer 669, Scream Tracker 2, UltraTracker, Oktalyzer, MED / OctaMED, PolyTracker and Farandole +modules load as Modules too (ported from OpenMPT's loaders). Each keeps its own `format` name and plays through one of +the four effect families (`engine`), with the format's quirks in `flags`: 669 and Farandole slide in Hz, Scream +Tracker 2 has its own tempo byte, MED its tempo modes and hold / decay, Oktalyzer its mixed channel pairs. Their +cells use the family's effect coding (an MTM cell reads like an XM cell, an OKT cell like an IT cell); a few effects +of these formats have no family equivalent and use the engine's extension codes (0x40 and up: note slides, auto +portamentos, ...). + +```luau +local song = assert(F.music.load(mtmBytes)) +assert(song.format == "mtm" and song.engine == "xm" and song.channels == 6) +local med = assert(F.music.load(medBytes)) +assert(med.format == "med" and med.meta.source.version == "MMD1" and med.instrumentMode) -- hold / decay: instruments +local audio = assert(F.ops.audio.toAudio(med:render({ sampleRate = 22050 }))) +assert(audio.frames > 0) +``` + +An Unreal `.umx` package holds a module (usually IT, S3M or XM). `F.load` unwraps it and returns that module, with +the package in `meta.container`; `F.format("umx").extract` lists the embedded modules without loading them. + +```luau +local m = assert(F.music.load(umxBytes)) +assert(m.format == "s3m" and m.meta.container.format == "umx" and m.meta.container.name == "theme") +local list = assert(F.format("umx").extract(F.Bytes.reader(umxBytes))) +assert(#list == 1 and list[1].format == "s3m") +local dec = assert(F.open(umxBytes)) -- rendered, like any module +assert(dec.channels == 2) +``` + +These formats are read only. Their Modules render to audio like any other (`F.save(song, nil, { format = "wav" })`), +and the module of an UMX keeps its own format, so `F.save(m)` works when that format has a writer (MOD, XM). + ## Gotchas - Saving music to an audio format renders it with the options in `opts`: `F.save(song, nil, { format = "wav", @@ -325,4 +370,6 @@ See [FORMATS.md](../FORMATS.md) for each format's capabilities. - Without a SoundFont, MIDI plays on simple built-in waveforms, which is fine for testing but not General MIDI. SF3 banks (Ogg-compressed samples) are not supported. - Pattern cells keep the file's own effect numbering, which differs between MOD / XM (0..35) and S3M / IT (1..26). + The other tracker formats use their engine family's numbering (`m.engine`), not their file's. +- A Module's `meta.unsupported` lists what was read but plays silent (MED synth / hybrid / MIDI instruments). - A module's `duration` is one pass. `render({ loop = true })` keeps playing past it. diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..d2af7b0 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,29 @@ do jitTune(false) end end +-- ws-audio2: trackers +do + -- the other tracker loaders on the shared engine: a 669 (Hz periods, auto slides) and an MMD1 (hold / decay + -- envelopes, instruments) from tools/fixtures/{669,med}.py, decoded and rendered at 44.1 kHz + local Six69 = require("@formats/music/669") + local Med = require("@formats/music/med") + local songs = { { Six69, require("@tests/gen/669_cases")[1].data }, { Med, require("@tests/gen/med_cases")[2].data } } + local best, frames = math.huge, 0 + local out = buffer.create(4096 * 8) + for _ = 1, 3 do + frames = 0 + local t0 = os.clock() + for _, s in songs do + local dec = (s[1].decode(Bytes.reader(buffer.fromstring(s[2]))) :: any):render() + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, "render 669 / med", best * 1000, frames / 44100 / best)) +end diff --git a/tools/fixtures/docs_av.py b/tools/fixtures/docs_av.py index 8019408..dc4c004 100644 --- a/tools/fixtures/docs_av.py +++ b/tools/fixtures/docs_av.py @@ -1,12 +1,13 @@ # Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them): # tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG + # PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of -# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT / -# ASS subtitles. +# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), MultiTracker / MED +# modules and an Unreal package (tools/fixtures/mtm.py, med.py, s3m.py), and SRT / WebVTT / ASS subtitles. # tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } } import importlib.util, os, struct, tempfile -INPUTS = ["tools/docs_check.py", "tools/fixtures/sf2.py", "tools/fixtures/mod.py"] +INPUTS = ["tools/docs_check.py", "tools/fixtures/sf2.py", "tools/fixtures/mod.py", "tools/fixtures/mtm.py", + "tools/fixtures/med.py", "tools/fixtures/s3m.py", "tools/fixtures/_tracker.py"] def load(ctx, name): @@ -100,6 +101,11 @@ def generate(ctx): files["bank.sf2"] = sf2.build_sf2(False)[0] mod = load(ctx, "fixtures/mod") files["song.mod"] = mod.song_basic() + # ws-audio2: more tracker formats (tools/fixtures/mtm.py, med.py; an Unreal package around an S3M) + files["song.mtm"] = load(ctx, "fixtures/mtm").song_effects() + files["song.med"] = load(ctx, "fixtures/med").song_basic(version=1) + tracker = load(ctx, "fixtures/_tracker") + files["music.umx"] = tracker.write_umx([("Theme", load(ctx, "fixtures/s3m").song_mono())]) files["subs.srt"] = SRT files["subs.vtt"] = VTT files["subs.ass"] = ASS @@ -110,6 +116,9 @@ def generate(ctx): "midiBytes": "tune.mid", "sf2Bytes": "bank.sf2", "modBytes": "song.mod", + "mtmBytes": "song.mtm", + "medBytes": "song.med", + "umxBytes": "music.umx", "srtText": "subs.srt", "vttText": "subs.vtt", "assText": "subs.ass",