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)