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).
This commit is contained in:
4DBug committed 2026-10-31 14:54:54 -05:00
1 parent 3d5cf3130e
commit 26fa887370
8 files changed
+368 -1

No files matched your search

+2
View File
@@ -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
+1
View File
@@ -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` |
+12
View File
@@ -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",
+10 -1
View File
@@ -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
+222
View File
@@ -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
+51
View File
@@ -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()
+36
View File
@@ -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("<I", 0x04070010)
imp_at = len(out)
out += umx_index(names.index("Core")) + umx_index(names.index("Class")) + struct.pack("<i", 0) + umx_index(names.index("Music"))
bodies = []
for i, (n, data) in enumerate(modules):
bodies.append(len(out))
out += umx_index(0) + umx_index(0) + struct.pack("<I", 0) + umx_index(len(data)) + data
exp_at = len(out)
for i, (n, data) in enumerate(modules):
size = len(umx_index(0)) * 2 + 4 + len(umx_index(len(data))) + len(data)
out += umx_index(-1) + umx_index(0) + struct.pack("<i", 0) + umx_index(names.index(n)) + struct.pack("<I", 0x70004)
out += umx_index(size) + umx_index(bodies[i])
hdr = b"\xc1\x83\x2a\x9e" + struct.pack("<HHIIIIIII", version, 0, 1, len(names), name_at, len(modules), exp_at, 1, imp_at)
out[0:36] = hdr
return bytes(out)
+34
View File
@@ -0,0 +1,34 @@
# UMX fixtures (tools/fixtures.py): Unreal music packages wrapping generated modules (an S3M from tools/fixtures/s3m.py,
# an IT from tools/fixtures/it.py), rendered by openmpt123 (which unwraps the package itself).
# tests/gen/umx_cases.luau { name, data (the package), inner (the embedded module), format (its format), ref
# (features of openmpt's render, tools/fixtures/_tracker.py), duration }
import importlib.util, 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:
_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", "tools/fixtures/s3m.py", "tools/fixtures/it.py"]
def sibling(name):
spec = importlib.util.spec_from_file_location("umx_" + name, os.path.join(os.path.dirname(os.path.abspath(__file__)), name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
s3m = sibling("s3m").song_mono()
it = sibling("it").song_effects()
cases = []
items = [("s3m", "Mono_Theme", s3m, 69), ("it", "Effects", it, 63)]
for fmt, nm, data, ver in items:
pkg = T.write_umx([(nm, data)], version=ver)
ref = T.reference(ctx, pkg, "umx")
cases.append({"name": nm, "data": pkg, "inner": data, "format": fmt, "ref": ref, "duration": ref["duration"]})
ctx.emit("umx_cases", cases)