From 9a5f3796e2beb59642ad45f5e09819a2a062e7b9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:40:13 -0500 Subject: [PATCH] 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)