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

This commit is contained in:
4DBug committed 2026-10-31 14:36:44 -05:00
1 parent bac37fb157
commit 6b5e8ec6cf
6 files changed
+378

No files matched your search

+1
View File
@@ -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` |
+12
View File
@@ -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",
+232
View File
@@ -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
+19
View File
@@ -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()
+33
View File
@@ -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("<H", len(message)) + message
head += bytes(orders) + b"\xff" * (256 - len(orders)) + bytes([len(patterns), len(orders), restart])
sizes = [2 + len(p) * 64 for p in patterns] + [0] * (256 - len(patterns))
head += b"".join(struct.pack("<H", s) for s in sizes)
struct.pack_into("<H", head, hl_at, len(head))
body = head
for k, pat in enumerate(patterns):
body += bytes([(breaks or [0] * len(patterns))[k], 0])
for row in pat:
for (note, ins, vol, eff) in row:
body += bytes([note - 36 if note else 0, max(0, ins - 1), vol, eff])
smap = bytearray(8)
for i in range(len(samples)):
smap[i >> 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("<IBBIIBB", len(s["data"]), 0, s.get("volume", 15), ls * bps, le * bps,
1 if bps == 2 else 0, 8 if s.get("loop") else 0)
body += s["data"]
return bytes(body)
+81
View File
@@ -0,0 +1,81 @@
# FAR fixtures (tools/fixtures.py): generated Farandole Composer modules exercising the effects, rendered by openmpt123.
# tests/gen/far_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(rows=64):
return [[(0, 0, 0, 0) for _ in range(16)] for _ in range(rows)]
def put(p, row, ch, note=0, ins=0, vol=0, cmd=None, param=0):
p[row][ch] = (note, ins, vol, 0 if cmd is None else (cmd << 4) | param)
def samples():
return [
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 15, "loop": (0, 64)},
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 11, "loop": (0, 64)},
{"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 15, "loop": (0, 200)},
{"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 14},
{"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 12, "loop": (0, 50)},
]
def song_effects(keep=None):
a, b = empty(), empty(48)
mel = [61, 65, 68, 73, 68, 65, 63, 61]
for i in range(16):
put(a, i * 4, 0, mel[i % 8], 1, 16 - i % 4)
put(a, 0, 1, 49, 2, 12)
put(a, 4, 1, 0, 0, 0, 0x1, 0x3) # fine porta up
put(a, 8, 1, 0, 0, 0, 0x2, 0x5)
put(a, 12, 1, 0, 0, 0, 0x8, 0x2) # volume slide down
put(a, 16, 1, 51, 2, 14, 0x7, 0x1) # up
put(a, 20, 1, 0, 0, 0, 0x5, 0x4) # vibrato depth
put(a, 21, 1, 0, 0, 0, 0x6, 0x2) # vibrato speed
put(a, 28, 1, 56, 2, 14)
put(a, 32, 1, 61, 2, 0, 0x3, 0x4) # tone portamento (keeps going)
put(a, 40, 1, 49, 2, 0, 0x3, 0x2)
put(a, 48, 1, 0, 0, 0, 0xA, 0x8) # volume portamento
for r in range(0, 64, 8):
put(a, r, 3, 61, 4, 16 - r // 8)
put(a, 36, 3, 61, 4, 16, 0x4, 0x2) # retrigger
put(a, 4, 2, 37, 3, 12)
put(a, 2, 4, 73, 5, 10, 0xB, 0x2) # panning
put(a, 30, 4, 0, 0, 0, 0xB, 0xD)
put(a, 10, 5, 56, 1, 12)
put(a, 24, 5, 0, 0, 0, 0xF, 0x3) # speed
put(b, 0, 0, 49, 1, 16)
put(b, 8, 0, 61, 1, 16, 0x2, 0x8)
put(b, 0, 2, 37, 3, 12)
put(b, 16, 2, 44, 3, 10, 0x9, 0x3)
put(b, 20, 6, 68, 5, 16)
put(b, 24, 9, 56, 2, 16) # a muted channel
if keep is not None:
for p in (a, b):
for row in p:
for ch in range(16):
if ch not in keep and (row[ch][3] >> 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)