ws-audio2: api renderMusic uses a Module's own render method for non-tracker engines (AHX / HVL); docs/guide/music.md: AHX / HVL and MIDI variants section, Formats rows (docs inputs: tools/fixtures/docs_chip.py)

src/Formats/init.luau: renderMusic: a kind "music" value whose format is not mod/s3m/xm/it and that has a render
method renders through it (a failed render's .err becomes the error). Backward compatible.
This commit is contained in:
4DBug committed 2026-10-31 14:32:05 -05:00
1 parent 71bb89763e
commit d3ea84bb57
4 files changed
+126 -1

No files matched your search

+56
View File
@@ -312,9 +312,65 @@ 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 |
| ahx (AHX / THX), hvl (HivelyTracker) | yes | - | Module (own synth engine) |
| mus (Doom), xmi (Miles XMIDI), hmp (HMP, HMI) | yes | - (save as midi) | Midi |
See [FORMATS.md](../FORMATS.md) for each format's capabilities.
### AHX / HVL and MIDI variants
AHX and HivelyTracker modules carry no samples: their instruments are small synth programs (waveforms, filter and
pulse-width sweeps, a performance list). They load as a Module-shaped value (`format` `"ahx"` / `"hvl"`; `patterns` are
the tracks, 6 bytes per row: note, instrument, effect, parameter, second effect, parameter; `positions` hold each
channel's track and transpose; `subsongs`) and render through their own replayer, a port of HivelyTracker's, which gives
hvl2wav's samples exactly. Render options: `sampleRate`, `subsong` (0 = the main song), `loop`, `maxDuration` (default
600 s) and, for AHX, `stereo` 0..4 (0 mono as hvl2wav renders by default, 4 the Amiga's hard L R R L panning); HVL files
store their own panning and gain.
```luau
local song = assert(F.music.load(ahxBytes))
assert(song.format == "ahx" and song.channels == 4 and song.title == "demo")
local dec = song:render({ stereo = 4 }) -- a Decoder, stereo f32 at 44100 Hz
assert(dec.channels == 2 and dec.duration > 1)
local hvl = assert(F.music.load(hvlBytes))
assert(hvl.format == "hvl" and hvl.channels == 6 and #hvl.subsongs == 1)
local intro = hvl:render({ subsong = 1, sampleRate = 22050 })
local wav = assert(F.save(intro, nil, { format = "wav" }))
assert(F.detect(wav) == "wav" and F.detect(hvlBytes) == "hvl")
```
Doom MUS, Miles XMIDI and HMI's HMP / HMI files load as a **Midi**, so they play through the SoundFont synth and save
as a Standard MIDI File. MUS runs at 140 ticks per second (`rate` option), XMIDI at a fixed 120 (note durations become
note-offs; `track` picks the song of a multi-song file, `meta.source.songs` counts them), HMP / HMI at the rate in
their header.
```luau
local doom = assert(F.music.load(musBytes))
assert(doom.kind == "midi" and doom.meta.source.format == "mus")
local audio = assert(F.ops.audio.toAudio(doom:render({ soundfont = sf2Bytes, tail = 0.2 })))
assert(audio.channels == 2)
local xmi = assert(F.music.load(xmiBytes, { track = 2 })) -- the second song
assert(xmi.meta.source.songs == 2 and xmi.meta.source.song == 2)
local smf = assert(F.save(xmi, nil, { format = "midi" })) -- as a .mid
assert(F.detect(smf) == "midi")
local hmp = assert(F.music.load(hmpBytes))
assert(hmp.meta.source.format == "hmp" and #hmp.tracks == 3)
```
Karaoke `.kar` files are MIDI files with the lyrics in text events: `meta.lyrics` lists them with their time
(`{ time, tick, text }`; a leading `\` starts a new paragraph, `/` a new line), the `@` headers land in
`meta.karaoke` (`T` = title lines, `L` language, `I` info, ...) and `meta.tags`.
```luau
local kar = assert(F.music.load(karBytes))
assert(kar.meta.tags.title == "Little Song" and kar.meta.tags.artist == "The Docs")
local line = {}
for _, l in kar.meta.lyrics do
table.insert(line, l.text)
end
assert(table.concat(line) == "\\Hello /karaoke" and kar.meta.lyrics[2].time == 0.5)
```
## Gotchas
- Saving music to an audio format renders it with the options in `opts`: `F.save(song, nil, { format = "wav",
+10 -1
View File
@@ -479,8 +479,10 @@ local function videoToImage(v: any, o: Options): (any, Err.Err?)
return img, nil
end
-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker) or a Midi (music/midi render) |
-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker, or the Module's own render method
-- for other engines) or a Midi (music/midi render) |
-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ...
local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true }
local function renderMusic(value: any, o: Options): (any, Err.Err?)
local ok, dec, err
if value.kind == "midi" then
@@ -489,6 +491,13 @@ local function renderMusic(value: any, o: Options): (any, Err.Err?)
return nil, merr
end
ok, dec, err = pcall(m.render, value, o)
elseif TRACKER_FAMILY[value.format] == nil and type(value.render) == "function" then
-- a Module with its own engine (AHX / HVL: codecs/audio/Hively): its render method (a failed render is an
-- empty Decoder carrying .err)
ok, dec = pcall(value.render, value, o)
if ok and type(dec) == "table" and dec.err then
return nil, dec.err
end
else
local Tracker: any = require("@formats/codecs/audio/Tracker")
ok, dec, err = pcall(Tracker.render, value, o)
+11
View File
@@ -54,6 +54,17 @@ t:eq(code(string.sub(Cases[1].data, 1, 60)), Err.TRUNCATED, "truncated")
local song = assert(Ahx.decode(Bytes.reader(buffer.fromstring(Cases[1].data))))
t:check(song:render({ subsong = 9 }).err ~= nil, "subsong out of range")
-- through the api: a Module saved as audio renders through its own engine
do
local F = require("@formats")
local wav, err = F.save(song, nil, { format = "wav", sampleRate = 22050 })
t:check(wav, "F.save as wav: " .. tostring(err))
t:eq(F.detect(wav :: buffer), "wav", "F.save as wav")
t:eq(F.detect(buffer.fromstring(Cases[1].data)), "ahx", "F.detect")
local _, e2 = F.save(song, nil, { format = "wav", subsong = 7 })
t:check(e2 ~= nil, "F.save: a failed render is an error")
end
t:fuzz("decode", function(b: buffer)
return Ahx.decode(Bytes.reader(b))
end, samples)
+49
View File
@@ -0,0 +1,49 @@
# Docs inputs for the AHX / HVL / MIDI-variant section of docs/guide/music.md (tools/fixtures.py; tools/docs_check.py
# reads them): the demo songs of tools/fixtures/_hively.py, small MUS / XMI / HMP files from tools/fixtures/_midivar.py
# and a .kar karaoke file written here.
# tests/gen/docs_chip.luau { files = { [name] = bytes }, vars = { ahxBytes = "demo.ahx", ... } }
import importlib.util, os, random, struct
INPUTS = ["tools/docs_check.py", "tools/fixtures/_hively.py", "tools/fixtures/_midivar.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_chip_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def kar(V):
"""SMF 1 with a melody track and a "Words" track: @ headers, then syllables with \\ / line markers"""
def trk(events):
body = b"".join(V.vlq(dt) + data for dt, data in events) + b"\x00\xff\x2f\x00"
return b"MTrk" + struct.pack(">I", len(body)) + body
def text(s, kind=1):
s = s.encode()
return bytes([0xFF, kind]) + V.vlq(len(s)) + s
melody = [(0, b"\xff\x51\x03\x07\xa1\x20"), (0, b"\xc0\x00")]
for n in (60, 62, 64, 65):
melody += [(0, bytes([0x90, n, 100])), (480, bytes([0x80, n, 0]))]
words = [(0, text("Words", 3)), (0, text("@KMIDI KARAOKE FILE")), (0, text("@TLittle Song")), (0, text("@TThe Docs")),
(0, text("\\Hel")), (480, text("lo ")), (480, text("/kar")), (480, text("aoke"))]
return b"MThd" + struct.pack(">IHHh", 6, 1, 2, 480) + trk(melody) + trk(words)
def generate(ctx):
dc = load(ctx, "docs_check")
H = load(ctx, "fixtures/_hively")
V = load(ctx, "fixtures/_midivar")
rng = random.Random(5)
files = {
"demo.ahx": H.write_ahx(H.demo_song(False)),
"demo.hvl": H.write_hvl(H.demo_song(True)),
"e1m1.mus": V.random_mus(rng, n=40),
"song.xmi": V.write_xmi([V.random_xmi_song(rng, n=30, tempo=500000), V.random_xmi_song(rng, n=10, tempo=500000)]),
"song.hmp": V.write_hmp(V.random_hmp_tracks(rng, ntracks=3, n=20, running=False)),
"song.kar": kar(V),
}
dc.emit_inputs(ctx, files, {"ahxBytes": "demo.ahx", "hvlBytes": "demo.hvl", "musBytes": "e1m1.mus",
"xmiBytes": "song.xmi", "hmpBytes": "song.hmp", "karBytes": "song.kar"})