ws-music: codecs/Tracker engine (player, mixer, pcm, tables) + music/mod read/write/render, tested against openmpt123

This commit is contained in:
4DBug committed 2026-10-31 08:47:40 -05:00
1 parent cdcb5b0b77
commit da534ce507
12 files changed
+4020

No files matched your search

+2
View File
@@ -6,7 +6,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
+12
View File
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "mod",
category = "music",
path = "music/mod",
extensions = { "mod", "m15", "stk", "nst" },
mime = { "audio/x-mod", "audio/mod" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/mod")
end,
},
}
return list
+173
View File
@@ -0,0 +1,173 @@
--!strict
--!native
-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole
-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code).
--
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker)
-- validates the sample buffers' sizes.
local floor, ceil, min = math.floor, math.ceil, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
local Mixer = {}
-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance)
local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number)
local data: buffer = v.data
local nch = v.nch
local inc = v.inc
if not (inc > 0 and inc < 1e6) then
return
end
local len = v.len
local hi = len - 1
local i = 0
local guard = 0
while i < n do
guard += 1
if guard > n + 64 then
return
end
local s, e, t
if v.keyOn and v.susT > 0 then
s, e, t = v.susS, v.susE, v.susT
elseif v.loopT > 0 then
s, e, t = v.loopS, v.loopE, v.loopT
else
s, e, t = 0, len, 0
end
local p = v.p
local dir = v.dir
local count
if dir > 0 then
local lim = if t == 2 then e - 1 else e
if p >= lim then
if t == 0 then
v.active = false
return
elseif t == 1 then
p = s + (p - e) % (e - s)
else
p = 2 * (e - 1) - p
if p < s then
p = s
end
v.dir = -1
end
v.p = p
continue
end
count = ceil((lim - p) / inc)
else
if p < s then
p = 2 * s - p
if p > e - 1 then
p = e - 1
end
v.p = p
v.dir = 1
continue
end
count = floor((p - s) / inc) + 1
end
if count < 1 then
count = 1
end
local m = min(n - i, count)
local step = inc * dir
if out == nil then
v.p = p + step * m
i += m
continue
end
local wrapJ = if t == 1 then s else e - 1
local gl, gr = v.gl, v.gr
local rl = v.rampN
local dl, dr = 0, 0
local tl, tr = v.tl, v.tr
if rl > 0 then
dl, dr = (tl - gl) / rl, (tr - gr) / rl
end
local fOn = v.fOn
local fa, fb0, fb1 = v.fa, v.fb0, v.fb1
local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r
local o = (off + i) * 8
for _ = 1, m do
local idx = floor(p)
if idx > hi then
idx = hi
elseif idx < 0 then
idx = 0
end
local j = idx + 1
if j >= e then
j = wrapJ
end
if j > hi then
j = hi
end
local xl, xr
if nch == 1 then
local a = readf32(data, idx * 4)
if linear then
local b = readf32(data, j * 4)
xl = a + (b - a) * (p - idx)
else
xl = a
end
if fOn then
local y = xl * fa + y1l * fb0 + y2l * fb1
y2l, y1l = y1l, y
xl = y
end
xr = xl
else
local al = readf32(data, idx * 8)
local ar = readf32(data, idx * 8 + 4)
if linear then
local f = p - idx
xl = al + (readf32(data, j * 8) - al) * f
xr = ar + (readf32(data, j * 8 + 4) - ar) * f
else
xl, xr = al, ar
end
if fOn then
local y = xl * fa + y1l * fb0 + y2l * fb1
y2l, y1l = y1l, y
xl = y
y = xr * fa + y1r * fb0 + y2r * fb1
y2r, y1r = y1r, y
xr = y
end
end
if rl > 0 then
gl += dl
gr += dr
rl -= 1
if rl == 0 then
gl, gr = tl, tr
end
end
writef32(out, o, readf32(out, o) + xl * gl)
writef32(out, o + 4, readf32(out, o + 4) + xr * gr)
o += 8
p += step
end
v.p = p
v.gl, v.gr, v.rampN = gl, gr, rl
v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r
i += m
end
local _ = ramp
end
-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions
function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean)
for _, v in st.voices do
if v.active and v.data then
mixVoice(v, out, off, n, linear, 0)
end
end
end
return Mixer
+132
View File
@@ -0,0 +1,132 @@
--!strict
--!native
-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back.
--
-- Never throws: reads past the source are refused up front (decode returns nil).
local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16
local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16
local floor = math.floor
local Pcm = {}
export type Spec = {
bits: number, -- 8 | 16
signed: boolean,
delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag)
channels: number?, -- 1 (default) | 2
planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved
bigEndian: boolean?,
}
-- bytes(frames, spec) -> the size of the raw data
function Pcm.bytes(frames: number, spec: Spec): number
return frames * (spec.channels or 1) * (spec.bits // 8)
end
-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short
function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer?
local nch = spec.channels or 1
local bps = spec.bits // 8
local total = frames * nch
if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then
return nil
end
local out = buffer.create(total * 4)
local planar = spec.planar and nch == 2
for c = 0, nch - 1 do
local acc = 0
for i = 0, frames - 1 do
local k = if planar then c * frames + i else i * nch + c
local v
if bps == 1 then
if spec.signed then
v = readi8(buf, off + k)
else
v = readu8(buf, off + k) - 128
end
if spec.delta then
acc = (acc + v + 128) % 256 - 128
v = acc
end
writef32(out, (i * nch + c) * 4, v / 128)
else
local p = off + k * 2
if spec.bigEndian then
v = readu8(buf, p) * 256 + readu8(buf, p + 1)
if spec.signed and v >= 32768 then
v -= 65536
end
elseif spec.signed then
v = readi16(buf, p)
else
v = readu16(buf, p)
end
if not spec.signed then
v -= 32768
end
if spec.delta then
acc = (acc + v + 32768) % 65536 - 32768
v = acc
end
writef32(out, (i * nch + c) * 4, v / 32768)
end
end
end
return out
end
-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar)
function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer
local nch = spec.channels or 1
local bps = spec.bits // 8
local out = buffer.create(frames * nch * bps)
local planar = spec.planar and nch == 2
local avail = buffer.len(samples) // 4
for c = 0, nch - 1 do
local prev = 0
for i = 0, frames - 1 do
local si = i * nch + c
local x = if si < avail then readf32(samples, si * 4) else 0
local k = if planar then c * frames + i else i * nch + c
if bps == 1 then
local v = math.clamp(floor(x * 128 + 0.5), -128, 127)
local w = v
if spec.delta then
w = (v - prev) % 256
prev = v
else
w = if spec.signed then v % 256 else v + 128
end
writeu8(out, k, w)
else
local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767)
local w = v
if spec.delta then
w = (v - prev + 32768) % 65536 - 32768
prev = v
elseif not spec.signed then
w = v + 32768
if w >= 32768 then
w -= 65536
end
end
writei16(out, k * 2, w)
end
end
end
return out
end
-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16
function Pcm.bitsNeeded(samples: buffer): number
for i = 0, buffer.len(samples) // 4 - 1 do
local x = readf32(samples, i * 4) * 128
if x ~= floor(x) then
return 16
end
end
return 8
end
return Pcm
File diff suppressed because it is too large. Load diff
+113
View File
@@ -0,0 +1,113 @@
--!strict
--!native
-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M
-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker
-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
local Tables = {}
-- the ProTracker half-sine (32 steps, 0..255)
local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 }
-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic)
local RANDOM: { number } = {}
do
local s = 12345
for i = 1, 64 do
s = (s * 1103515245 + 12345) % 2147483648
RANDOM[i] = (s // 65536) % 511 - 255
end
end
function Tables.wave64(kind: number, pos: number): number
local p = pos % 64
if kind == 1 then
return 255 - p * 8
elseif kind == 2 then
return if p < 32 then 255 else -255
elseif kind == 3 then
return RANDOM[p + 1]
end
local v = SINE32[(p % 32) + 1]
return if p >= 32 then -v else v
end
-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up.
-- IT: 0 sine, 1 ramp down, 2 square, 3 random.
local SINE256: { number } = {}
for i = 0, 255 do
SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5)
end
function Tables.autoWave(kind: number, pos: number, it: boolean): number
local p = pos % 256
if it then
if kind == 1 then
return 64 - (p + 1) // 2
elseif kind == 2 then
return if p < 128 then 64 else -64
elseif kind == 3 then
return RANDOM[(p % 64) + 1] // 4
end
return SINE256[p + 1]
end
if kind == 1 then
return if p < 128 then 64 else -64
elseif kind == 2 then
return 64 - (p + 1) // 2
elseif kind == 3 then
return (p + 1) // 2 - 64
end
return SINE256[p + 1]
end
-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers:
-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at
-- its base rate (8363 Hz).
local PERIODS = {
3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812,
1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453,
428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226,
214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113,
107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56,
}
Tables.PERIODS = PERIODS
Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1)
-- periodToNote(period) -> note (1..120), 0 for period 0
function Tables.periodToNote(period: number): number
if period <= 0 then
return 0
end
-- exact match first, then the nearest note on a log scale
for i = 1, #PERIODS do
if PERIODS[i] == period then
return i + Tables.PERIOD_FIRST_NOTE - 1
end
end
local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5)
return math.clamp(n, 1, 120)
end
-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends
function Tables.noteToPeriod(note: number): number
local i = note - Tables.PERIOD_FIRST_NOTE + 1
if i >= 1 and i <= #PERIODS then
return PERIODS[i]
end
return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5))
end
-- IT volume column "g" (tone portamento) speeds
Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 }
-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value
Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 }
Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 }
-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate
-- (FT2 / ST3 period units, 4x ProTracker's)
Tables.AMIGA = 8363 * 1712
-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz)
Tables.AMIGA_PAL = 7093789.2 / 2 * 4
return Tables
+513
View File
@@ -0,0 +1,513 @@
--!strict
-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
--
-- local Tracker = require("@formats/codecs/Tracker")
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
--
-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file):
-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks
-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s)
-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume)
-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index)
-- linear linear frequency slides (XM / IT flag) or Amiga periods
-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column
-- is a sample number (MOD, S3M, IT sample mode)
-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) }
-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width,
-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool }
-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels
-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 =
-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5
-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the
-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored;
-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1
-- (0 = none). Tracker.cell / Tracker.setCell read and write cells.
-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16,
-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong),
-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil),
-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth /
-- vibRate (IT auto-vibrato) }
-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note },
-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut,
-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off,
-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre),
-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) }
-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart,
-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) }
--
-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768).
-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add
-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT:
-- base = c5speed, ref 61.
--
-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects
-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Player = require("@formats/codecs/Tracker/Player")
local Mixer = require("@formats/codecs/Tracker/Mixer")
local Pcm = require("@formats/codecs/Tracker/Pcm")
local Tables = require("@formats/codecs/Tracker/Tables")
local Tracker = {}
Tracker.Pcm = Pcm
Tracker.Tables = Tables
export type Envelope = {
enabled: boolean,
ticks: { number },
values: { number },
loop: boolean,
loopStart: number,
loopEnd: number,
sustain: boolean,
susStart: number,
susEnd: number,
carry: boolean?,
filter: boolean?,
}
export type Pattern = { rows: number, data: buffer }
export type RenderOptions = {
sampleRate: number?, -- default 44100
interpolation: ("linear" | "none")?, -- default "linear"
stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre)
loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false
maxDuration: number?, -- seconds; the render stops there (default 3600)
}
local CELL = 5
-- ------------------------------------------------------------------------------------------------ constructors
-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults
function Tracker.newModule(format: string, channels: number): any
local m = {
kind = "music",
format = format,
title = "",
channels = channels,
speed = 6,
tempo = 125,
globalVolume = 128,
mixVolume = 48,
order = {},
restart = 0,
linear = format == "xm" or format == "it",
instrumentMode = format == "xm" or format == "it",
flags = {},
channelPan = {},
channelVolume = {},
channelMute = {},
patterns = {},
instruments = {},
samples = {},
meta = {},
render = Tracker.renderMethod,
}
for i = 1, channels do
m.channelVolume[i] = 64
if format == "mod" then
local k = (i - 1) % 4
m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width
else
m.channelPan[i] = 128
end
end
return m
end
-- newPattern(rows, channels) -> an empty Pattern
function Tracker.newPattern(rows: number, channels: number): Pattern
return { rows = rows, data = buffer.create(rows * channels * CELL) }
end
-- newSample() -> an empty Sample
function Tracker.newSample(name: string?): any
return {
name = name or "",
data = buffer.create(0),
length = 0,
channels = 1,
bits = 8,
loopStart = 0,
loopEnd = 0,
loopType = 0,
susStart = 0,
susEnd = 0,
susType = 0,
volume = 64,
globalVolume = 64,
pan = nil :: number?,
c5speed = 8363,
relativeNote = 0,
finetune = 0,
vibType = 0,
vibSweep = 0,
vibDepth = 0,
vibRate = 0,
}
end
function Tracker.newEnvelope(): Envelope
return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 }
end
-- newInstrument() -> an Instrument mapping every note to sample 0 (none)
function Tracker.newInstrument(name: string?): any
local sm, nm = table.create(120, 0), table.create(120, 0)
for i = 1, 120 do
nm[i] = i
end
return {
name = name or "",
sampleMap = sm,
noteMap = nm,
volEnv = nil :: Envelope?,
panEnv = nil :: Envelope?,
pitchEnv = nil :: Envelope?,
fadeout = 0,
nna = 0,
dct = 0,
dca = 0,
globalVolume = 128,
pan = nil :: number?,
pps = 0,
ppc = 60,
cutoff = nil :: number?,
resonance = nil :: number?,
vibType = 0,
vibSweep = 0,
vibDepth = 0,
vibRate = 0,
}
end
-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based,
-- channel 1-based); nil when out of range
function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number)
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
return nil, 0, 0, 0, 0
end
local o = (row * m.channels + channel - 1) * CELL
local d = p.data
return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
end
-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range)
function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
return false
end
local o = (row * m.channels + channel - 1) * CELL
local d = p.data
buffer.writeu8(d, o, note % 256)
buffer.writeu8(d, o + 1, ins % 256)
buffer.writeu8(d, o + 2, vol % 256)
buffer.writeu8(d, o + 3, fx % 256)
buffer.writeu8(d, o + 4, param % 256)
return true
end
-- ------------------------------------------------------------------------------------------------ validation
local function num(v: any, lo: number, hi: number): boolean
return type(v) == "number" and v == v and v >= lo and v <= hi
end
local function fixEnvelope(e: any): (any, string?)
if e == nil then
return nil
end
if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then
return nil, "bad envelope"
end
local n = math.min(#e.ticks, #e.values)
local last = -1
for i = 1, n do
local t, v = e.ticks[i], e.values[i]
if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then
-- points must go forward: keep the valid prefix
n = i - 1
break
end
last = t
end
for i = #e.ticks, n + 1, -1 do
e.ticks[i] = nil
end
for i = #e.values, n + 1, -1 do
e.values[i] = nil
end
if n == 0 then
e.enabled = false
end
local function idx(v: any): number
return if num(v, 1, math.max(1, n)) then math.floor(v) else 1
end
e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd)
e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd)
if e.loopEnd < e.loopStart then
e.loop = false
end
if e.susEnd < e.susStart then
e.sustain = false
end
return e
end
local function fixLoop(s: number, e: number, t: number, len: number): (number, number, number)
if not num(t, 0, 2) or t == 0 then
return 0, 0, 0
end
s, e = math.floor(math.clamp(s, 0, len)), math.floor(math.clamp(e, 0, len))
if e - s < 1 then
return 0, 0, 0
end
if t == 2 and e - s < 2 then
t = 1
end
return s, e, t
end
-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and
-- numbers into range (in place)
function Tracker.validate(m: any): (boolean?, Err.Err?)
if type(m) ~= "table" then
return nil, Err.new(Err.ARG, "not a module")
end
if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then
return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format))
end
if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then
return nil, Err.new(Err.ARG, "bad channel count")
end
if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then
return nil, Err.new(Err.ARG, "module without order / patterns / samples")
end
m.instruments = if type(m.instruments) == "table" then m.instruments else {}
m.flags = if type(m.flags) == "table" then m.flags else {}
m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {}
m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {}
m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {}
for i = 1, m.channels do
local p = m.channelPan[i]
if p ~= 512 and not num(p, 0, 256) then
m.channelPan[i] = 128
end
if not num(m.channelVolume[i], 0, 64) then
m.channelVolume[i] = 64
end
end
m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6
m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125
m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128
m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48
m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0
for i, o in m.order do
if not num(o, 0, 255) then
return nil, Err.new(Err.ARG, "bad order entry " .. i)
end
end
for i, p in m.patterns do
if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then
return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1))
end
end
for i, s in m.samples do
if type(s) ~= "table" then
return nil, Err.new(Err.ARG, "bad sample " .. i)
end
local nch = if s.channels == 2 then 2 else 1
s.channels = nch
if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then
return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length")
end
s.length = math.floor(s.length)
s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length)
s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length)
s.volume = if num(s.volume, 0, 64) then s.volume else 64
s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64
if s.pan ~= nil and not num(s.pan, 0, 256) then
s.pan = nil
end
s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363
s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0
s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0
end
for i, ins in m.instruments do
if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then
return nil, Err.new(Err.ARG, "bad instrument " .. i)
end
for n = 1, 120 do
if not num(ins.sampleMap[n], 0, 1e6) then
ins.sampleMap[n] = 0
end
if not num(ins.noteMap[n], 1, 120) then
ins.noteMap[n] = n
end
end
local err
ins.volEnv, err = fixEnvelope(ins.volEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.panEnv, err = fixEnvelope(ins.panEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.pitchEnv, err = fixEnvelope(ins.pitchEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0
ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128
if ins.pan ~= nil and not num(ins.pan, 0, 256) then
ins.pan = nil
end
if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then
ins.cutoff = nil
end
if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then
ins.resonance = nil
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ rendering
local Decoder = {}
Decoder.__index = Decoder
-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err
function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?)
local ok, err = Tracker.validate(m)
if not ok then
return nil, err
end
local sr = opts and opts.sampleRate or 44100
local maxFrames = (opts and opts.maxDuration or 3600) * sr
local st = Player.new(m, sr, { stereoSeparation = 100 })
local frames = 0
while frames < maxFrames do
local f = Player.tick(st)
if f == 0 and st.ended then
break
end
frames += f
end
return math.min(frames, maxFrames) / sr
end
local function newPlayer(self: any)
self.st = Player.new(self.module, self.sampleRate, self.opts)
self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015))
self.left = 0
self.pos = 0
end
-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err
function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
local o: RenderOptions = opts or {}
local sr = o.sampleRate or 44100
if type(sr) ~= "number" or sr < 1000 or sr > 384000 then
return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000")
end
local seconds, err = Tracker.duration(m, o)
if not seconds then
return nil, err
end
local frames = math.floor(seconds * sr + 0.5)
local self = setmetatable({
sampleRate = sr,
channels = 2,
frames = frames,
duration = frames / sr,
bitrate = 0,
tags = { title = m.title or "" },
module = m,
opts = o,
linear = o.interpolation ~= "none",
maxFrames = (o.maxDuration or 3600) * sr,
st = nil :: any,
left = 0,
pos = 0,
}, Decoder)
newPlayer(self)
return self :: any, nil
end
-- the Module method: module:render(opts)
function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder
local dec = Tracker.render(self, opts)
return dec :: any
end
-- run(self, out?, n) -> frames produced (out nil: advance without mixing)
local function run(self: any, out: buffer?, n: number): number
local st = self.st
local done = 0
while done < n do
if self.left <= 0 then
if self.pos + done >= self.maxFrames then
break
end
local f = Player.tick(st)
if f == 0 and st.ended then
break
end
self.left = f
if f == 0 then
continue
end
end
local k = math.min(self.left, n - done)
Mixer.mix(st, out, done, k, self.linear)
self.left -= k
done += k
end
self.pos += done
return done
end
-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end)
function Decoder.read(self: any, n: number, out: buffer?): (buffer, number)
n = math.max(0, math.floor(tonumber(n) or 0))
local o = out
if o == nil or buffer.len(o) < n * 8 then
o = buffer.create(n * 8)
else
buffer.fill(o, 0, 0, n * 8)
end
local got = run(self, o, n)
return o :: buffer, got
end
-- seek(seconds): replays the song silently up to the position (sample positions included)
function Decoder.seek(self: any, seconds: number)
local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate))
newPlayer(self)
local chunk = 65536
while self.pos < target do
local got = run(self, nil, math.min(chunk, target - self.pos))
if got == 0 then
break
end
end
-- the gains ramp in from silence after a seek
for _, v in self.st.voices do
v.gl, v.gr = 0, 0
end
end
function Decoder.position(self: any): number
return self.pos / self.sampleRate
end
return Tracker
+361
View File
@@ -0,0 +1,361 @@
--!strict
-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4,
-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or
-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through
-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod"
-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns).
-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter
-- (E0x), PowerPacker-packed files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/Tracker")
-- ------------------------------------------------------------------------------------------------ contract
local Mod = {
name = "mod",
category = "music",
extensions = { "mod", "m15", "stk", "nst" },
mime = { "audio/x-mod", "audio/mod" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 32 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples)
}
export type EncodeOptions = {}
-- ------------------------------------------------------------------------------------------------ constants
local Pcm = Tracker.Pcm
local Tables = Tracker.Tables
local FIXED: { [string]: number } = {
["M.K."] = 4,
["M!K!"] = 4,
["M&K!"] = 4,
["N.T."] = 4,
["FLT4"] = 4,
["FLT8"] = 8,
["CD81"] = 8,
["OKTA"] = 8,
["OCTA"] = 8,
["EXO4"] = 4,
["EXO8"] = 8,
}
-- channels from the 4-byte signature at 1080, or nil
local function signatureChannels(sig: string): number?
local fixed = FIXED[sig]
if fixed then
return fixed
end
local d = string.match(sig, "^(%d)CHN$")
if d then
local n = tonumber(d) :: number
return if n >= 1 then n else nil
end
local dd = string.match(sig, "^(%d%d)C[HN]$")
if dd then
local n = tonumber(dd) :: number
return if n >= 1 and n <= 32 then n else nil
end
local t = string.match(sig, "^TDZ(%d)$")
if t then
local n = tonumber(t) :: number
return if n >= 1 then n else nil
end
return nil
end
-- ------------------------------------------------------------------------------------------------ sniff
function Mod.sniff(r: Bytes.Reader): number
if r:size() < 1084 then
return 0
end
local sig = r:peek(4, 1080)
if signatureChannels(sig) then
return 0.8
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
local size = r:size()
local sig = if size >= 1084 then r:peek(4, 1080) else ""
local channels = signatureChannels(sig)
local nsamples = 31
if not channels then
-- a 15-sample Soundtracker module (no signature): only when the header is plausible
nsamples, channels = 15, 4
end
local nch = channels :: number
local m = Tracker.newModule("mod", nch)
m.title = r:fixed(20)
local lengths: { number } = {}
for i = 1, nsamples do
local s = Tracker.newSample(r:fixed(22))
local len = r:u16be() * 2
local ft = r:u8() % 16
local vol = r:u8()
local ls = r:u16be() * 2
local ll = r:u16be() * 2
if r.err then
return nil, r.err
end
if nsamples == 15 and (vol > 64 or ft ~= 0) then
return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)")
end
s.finetune = (if ft >= 8 then ft - 16 else ft) * 16
s.volume = math.min(vol, 64)
s.bits = 8
if ll > 2 then
s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1
end
lengths[i] = len
m.samples[i] = s
end
local songLength = r:u8()
local restart = r:u8()
local order: { number } = {}
local maxPat = 0
for i = 1, 128 do
local p = r:u8()
order[i] = p
maxPat = math.max(maxPat, p)
end
if r.err then
return nil, r.err
end
if songLength == 0 or songLength > 128 or maxPat >= 128 then
return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)")
end
if nsamples == 31 then
r:skip(4)
end
for i = 1, songLength do
m.order[i] = order[i]
end
m.restart = if restart < songLength then restart else 0
m.meta.signature = if nsamples == 31 then sig else nil
m.flags.amigaLimits = nch == 4
-- patterns
local npat = maxPat + 1
local patBytes = 64 * nch * 4
if not r:need(npat * patBytes) then
return nil, r.err
end
local buf = r.buf
for p = 0, npat - 1 do
local pat = Tracker.newPattern(64, nch)
local base = r.pos + p * patBytes
local d = pat.data
for i = 0, 64 * nch - 1 do
local o = base + i * 4
local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3)
local period = (b0 % 16) * 256 + b1
local ins = (b0 // 16) * 16 + b2 // 16
local q = i * 5
buffer.writeu8(d, q, Tables.periodToNote(period))
buffer.writeu8(d, q + 1, ins)
buffer.writeu8(d, q + 3, b2 % 16)
buffer.writeu8(d, q + 4, b3)
end
m.patterns[p + 1] = pat
end
r:skip(npat * patBytes)
-- sample data (8-bit signed; the last samples of a truncated file are cut short)
local total = 0
for i = 1, nsamples do
local s = m.samples[i]
local len = math.min(lengths[i], r:remaining())
total += len * 4
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
end
local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true })
if not data then
return nil, Err.new(Err.TRUNCATED, "sample data", r.pos)
end
r:skip(len)
s.data, s.length = data, len
if s.loopEnd > len then
s.loopEnd = len
if s.loopEnd - s.loopStart < 2 then
s.loopType, s.loopStart, s.loopEnd = 0, 0, 0
end
end
end
m.meta.source = { format = "mod", samples = nsamples }
m.render = Tracker.renderMethod
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
-- ------------------------------------------------------------------------------------------------ encode
local function writeName(w: Bytes.Writer, s: string, n: number)
local t = string.sub(s or "", 1, n)
w:string(t)
w:fill(0, n - #t)
end
-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to
-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F.
function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?)
local ok, verr = Tracker.validate(m)
if not ok then
return nil, verr
end
if m.format ~= "mod" and m.format ~= "xm" then
return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format")
end
local nch = m.channels
if nch > 32 then
return nil, Err.new(Err.ARG, "MOD holds at most 32 channels")
end
-- the sample for each instrument number
local smpOf: { any } = {}
if m.format == "xm" then
for i, ins in m.instruments do
local first = 0
for n = 1, 120 do
local s = ins.sampleMap[n]
if s ~= 0 then
if first ~= 0 and s ~= first then
return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples")
end
first = s
end
end
smpOf[i] = m.samples[first] or Tracker.newSample(ins.name)
end
else
for i, s in m.samples do
smpOf[i] = s
end
end
if #smpOf > 31 then
return nil, Err.new(Err.ARG, "MOD holds at most 31 samples")
end
local order: { number } = {}
for _, o in m.order do
if o == 255 then
break
elseif o ~= 254 then
table.insert(order, o)
end
end
if #order == 0 or #order > 128 then
return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries")
end
local npat = #m.patterns
if npat > 100 then
return nil, Err.new(Err.ARG, "too many patterns for MOD")
end
for p, pat in m.patterns do
if pat.rows ~= 64 then
return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)")
end
end
local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536)
writeName(w, m.title or "", 20)
local datas: { buffer } = {}
for i = 1, 31 do
local s = smpOf[i]
if s then
local len = math.min(s.length, 131070)
local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 })
if s.channels == 2 then
-- mix stereo samples down
local mono = buffer.create(len * 4)
for k = 0, len - 1 do
buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2)
end
pcm = Pcm.encode(mono, len, { bits = 8, signed = true })
end
local even = len + len % 2
local padded = buffer.create(even)
buffer.copy(padded, 0, pcm, 0, len)
datas[i] = padded
writeName(w, s.name or "", 22)
w:u16be(even // 2)
local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7)
w:u8(ft % 16)
w:u8(math.clamp(math.floor(s.volume), 0, 64))
if s.loopType > 0 and s.loopEnd <= even then
w:u16be(s.loopStart // 2)
w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2))
else
w:u16be(0)
w:u16be(1)
end
else
w:fill(0, 22)
w:u16be(0)
w:u8(0)
w:u8(0)
w:u16be(0)
w:u16be(1)
end
end
w:u8(#order)
w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127)
for i = 1, 128 do
w:u8(order[i] or 0)
end
local sig
if nch == 4 then
sig = if npat > 64 then "M!K!" else "M.K."
elseif nch < 10 then
sig = nch .. "CHN"
else
sig = nch .. "CH"
end
w:string(sig)
for p = 1, npat do
local d = m.patterns[p].data
for i = 0, 64 * nch - 1 do
local q = i * 5
local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4)
local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0
if period > 4095 then
period = 0
end
if fx > 15 then
fx, param = 0, 0
end
if ins > 31 then
ins = 0
end
w:u8((ins // 16) * 16 + period // 256)
w:u8(period % 256)
w:u8((ins % 16) * 16 + fx)
w:u8(param)
end
end
for i = 1, 31 do
if datas[i] then
w:bytes(datas[i])
end
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Mod.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Mod
+201
View File
@@ -0,0 +1,201 @@
-- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and
-- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left,
-- right and mid, and 20 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides.
local S = {}
local SR, HOP, BANDS = 44100, 2048, 20
local F_LO, F_HI = 100, 16000
S.SR = SR
local WINDOW = table.create(HOP, 0)
for i = 0, HOP - 1 do
WINDOW[i + 1] = 0.5 - 0.5 * math.cos(2 * math.pi * i / HOP)
end
local BAND_OF = table.create(HOP // 2, -1)
for b = 1, HOP // 2 - 1 do
local f = b * SR / HOP
if f >= F_LO and f < F_HI then
BAND_OF[b + 1] = math.min(BANDS - 1, math.floor(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS))
end
end
local function fft(re: { number }, im: { number }, n: number)
local j = 0
for i = 1, n - 1 do
local bit = n // 2
while bit > 0 and j >= bit and (j // bit) % 2 == 1 do
j -= bit
bit //= 2
end
j += bit
if i < j then
re[i + 1], re[j + 1] = re[j + 1], re[i + 1]
im[i + 1], im[j + 1] = im[j + 1], im[i + 1]
end
end
local size = 2
while size <= n do
local ang = -2 * math.pi / size
local wr, wi = math.cos(ang), math.sin(ang)
local half = size // 2
for start = 0, n - 1, size do
local cr, ci = 1, 0
for k = 0, half - 1 do
local a, b = start + k + 1, start + k + half + 1
local tr = re[b] * cr - im[b] * ci
local ti = re[b] * ci + im[b] * cr
re[b], im[b] = re[a] - tr, im[a] - ti
re[a], im[a] = re[a] + tr, im[a] + ti
cr, ci = cr * wr - ci * wi, cr * wi + ci * wr
end
end
size *= 2
end
end
-- features(samples (interleaved stereo f32 buffer), frames) -> { frames, rmsL, rmsR, rmsM, bands }
function S.features(buf: buffer, frames: number): any
local n = frames // HOP
local out = { frames = n, rmsL = {}, rmsR = {}, rmsM = {}, bands = {} }
local re, im = table.create(HOP, 0), table.create(HOP, 0)
for k = 0, n - 1 do
local sl, sr, sm = 0, 0, 0
for i = 0, HOP - 1 do
local o = ((k * HOP + i) * 2) * 4
local l, r = buffer.readf32(buf, o), buffer.readf32(buf, o + 4)
local m = (l + r) / 2
sl += l * l
sr += r * r
sm += m * m
re[i + 1] = m * WINDOW[i + 1]
im[i + 1] = 0
end
table.insert(out.rmsL, math.sqrt(sl / HOP))
table.insert(out.rmsR, math.sqrt(sr / HOP))
table.insert(out.rmsM, math.sqrt(sm / HOP))
fft(re, im, HOP)
local e = table.create(BANDS, 0)
for b = 1, HOP // 2 - 1 do
local j = BAND_OF[b + 1]
if j >= 0 then
e[j + 1] += re[b + 1] * re[b + 1] + im[b + 1] * im[b + 1]
end
end
for j = 1, BANDS do
table.insert(out.bands, math.sqrt(e[j]))
end
end
return out
end
-- renderAll(decoder, maxFrames) -> interleaved buffer, frames
function S.renderAll(dec: any, maxFrames: number): (buffer, number)
local total = math.min(dec.frames, maxFrames)
local out = buffer.create(math.max(1, total) * 8)
local pos = 0
local chunk = buffer.create(4096 * 8)
while pos < total do
local _, n = dec:read(math.min(4096, total - pos), chunk)
if n == 0 then
break
end
buffer.copy(out, pos * 8, chunk, 0, n * 8)
pos += n
end
return out, pos
end
local function db(x: number): number
return 20 * math.log10(x + 1e-6)
end
-- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames:
-- gainDb total mid energy ratio in dB (ours / ref)
-- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either)
-- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB)
-- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks)
function S.compare(a: any, b: any): any
local n = math.min(a.frames, b.frames)
local ea, eb = 0, 0
for k = 1, n do
ea += a.rmsM[k] ^ 2
eb += b.rmsM[k] ^ 2
end
local gainDb = 10 * math.log10((ea + 1e-12) / (eb + 1e-12))
local xs, ys = {}, {}
for k = 1, n do
local x, y = db(a.rmsM[k]), db(b.rmsM[k])
if x > -60 or y > -60 then
table.insert(xs, x)
table.insert(ys, y)
end
end
local mx, my = 0, 0
for i = 1, #xs do
mx += xs[i]
my += ys[i]
end
mx /= math.max(1, #xs)
my /= math.max(1, #ys)
local sxy, sxx, syy = 0, 0, 0
for i = 1, #xs do
sxy += (xs[i] - mx) * (ys[i] - my)
sxx += (xs[i] - mx) ^ 2
syy += (ys[i] - my) ^ 2
end
local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1
local cs, cn = 0, 0
local bal, bn = 0, 0
for k = 1, n do
if db(b.rmsM[k]) > -50 then
local dot, na, nb = 0, 0, 0
for j = 1, BANDS do
local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j]
dot += x * y
na += x * x
nb += y * y
end
cs += if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0
cn += 1
end
local la, ra, lb, rb = a.rmsL[k], a.rmsR[k], b.rmsL[k], b.rmsR[k]
if lb + rb > 0.01 then
bal += math.abs((la - ra) / (la + ra + 1e-9) - (lb - rb) / (lb + rb))
bn += 1
end
end
return {
gainDb = gainDb,
envCorr = envCorr,
spectral = if cn > 0 then cs / cn else 1,
balance = if bn > 0 then bal / bn else 0,
frames = n,
}
end
-- worst(ours, ref, count) -> the blocks with the lowest spectral similarity (for debugging): { {block, sim} }
function S.worst(a: any, b: any, count: number): { { number } }
local list = {}
for k = 1, math.min(a.frames, b.frames) do
if db(b.rmsM[k]) > -50 then
local dot, na, nb = 0, 0, 0
for j = 1, BANDS do
local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j]
dot += x * y
na += x * x
nb += y * y
end
table.insert(list, { k, if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0, db(a.rmsM[k]), db(b.rmsM[k]) })
end
end
table.sort(list, function(x, y)
return x[2] < y[2]
end)
local out = {}
for i = 1, math.min(count, #list) do
out[i] = list[i]
end
return out
end
return S
+77
View File
@@ -0,0 +1,77 @@
-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's
-- round trip, the contract, and the fuzz no-throw pass.
local T = require("@tests/T")
local S = require("@tests/music/_similar")
local Mod = require("@formats/music/mod")
local Tracker = require("@formats/codecs/Tracker")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/mod_cases")
local t = T.suite("mod")
t:eq(Mod.name, "mod", "name")
t:eq(Mod.category, "music", "category")
t:check(Mod.caps.decode and Mod.caps.encode, "caps")
local function load(data: string): any
return Mod.decode(Bytes.reader(buffer.fromstring(data)))
end
local THRESH = { gainDb = 1.5, envCorr = 0.95, spectral = 0.93, balance = 0.05, duration = 0.01 }
for _, c in Cases do
local m, err = load(c.data)
t:check(m, c.name .. ": " .. tostring(err))
t:check(Mod.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
local dec = m:render({ sampleRate = S.SR })
t:check(dec, c.name .. ": render")
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 r = S.compare(S.features(buf, frames), c.ref)
t:note("%-6s gain %+.2f dB, envelope r %.3f, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envCorr, r.spectral, r.balance, dec.duration)
if r.spectral < THRESH.spectral or r.envCorr < THRESH.envCorr then
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
end
end
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
t:check(r.envCorr > THRESH.envCorr, c.name .. ": loudness envelope")
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
-- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files)
local out, werr = Mod.encode(m)
t:check(out, c.name .. ": encode " .. tostring(werr))
local m2 = Mod.decode(Bytes.reader(out :: buffer))
t:check(m2, c.name .. ": re-decode")
t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes")
end
-- seek: the position after a seek and the output continuing
do
local m = load(Cases[1].data)
local dec = m:render()
dec:seek(2)
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
local _, n = dec:read(1000)
t:eq(n, 1000, "read after seek")
t:check(Tracker.duration(m) == dec.duration, "duration()")
end
-- the fuzz pass: decode, and a short render of whatever decodes
local samples = {}
for _, c in Cases do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
local m = Mod.decode(Bytes.reader(b))
if m then
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
if dec then
dec:read(4000)
end
end
return m
end, samples, { mutations = 30 })
t:done()
+495
View File
@@ -0,0 +1,495 @@
# Tracker fixture helpers (used by tools/fixtures/{mod,s3m,xm,it}.py): small writers for MOD, S3M, XM and IT
# (including IT 2.14 / 2.15 sample compression), synthesized samples, reference renders through openmpt123 (nix
# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 20 log-spaced band
# magnitudes of the mid signal), computed the same way in tests/music/_similar.luau. Every module is generated here
# (no third-party files), so the fixtures carry no licence.
import json, math, os, struct, subprocess, tempfile
SR = 44100
HOP = 2048
BANDS = 20
F_LO, F_HI = 100.0, 16000.0
# ---------------------------------------------------------------------------------------------- samples
def synth(kind, n, period, amp=0.9, seed=1, decay=None):
"""float samples in [-1, 1]: sine / square / saw / tri / noise / pluck"""
out = []
s = seed
for i in range(n):
ph = (i % period) / period
if kind == "sine":
v = math.sin(2 * math.pi * ph)
elif kind == "square":
v = 1.0 if ph < 0.5 else -1.0
elif kind == "saw":
v = 2 * ph - 1
elif kind == "tri":
v = 4 * ph - 1 if ph < 0.5 else 3 - 4 * ph
else: # noise
s = (s * 1103515245 + 12345) % 2147483648
v = (s / 2147483648) * 2 - 1
if decay:
v *= math.exp(-i / decay)
out.append(v * amp)
return out
def s8(xs):
return bytes((max(-128, min(127, int(round(x * 127)))) & 255) for x in xs)
def u8(xs):
return bytes(max(0, min(255, int(round(x * 127)) + 128)) for x in xs)
def s16(xs):
return b"".join(struct.pack("<h", max(-32768, min(32767, int(round(x * 32767))))) for x in xs)
def delta8(raw):
out, prev = bytearray(), 0
for b in raw:
v = b - 256 if b >= 128 else b
out.append((v - prev) & 255)
prev = v
return bytes(out)
def delta16(raw):
out, prev = bytearray(), 0
for i in range(0, len(raw), 2):
v = struct.unpack_from("<h", raw, i)[0]
out += struct.pack("<H", (v - prev) & 0xFFFF)
prev = v
return bytes(out)
def name(s, n):
b = s.encode()[:n]
return b + b"\0" * (n - len(b))
# ---------------------------------------------------------------------------------------------- MOD
PERIODS = [1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453,
428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226,
214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113]
def mod_period(note): # note 1 = C-0; 49 = ProTracker C-2 (428)
return PERIODS[note - 25] if note else 0
def write_mod(title, samples, orders, patterns, channels=4, restart=127):
"""samples: [{name, data (s8 bytes, even length), volume, finetune (-8..7), loop: (start, length) | None}];
patterns: [[row: [(note, ins, fx, param)] * channels] * 64]"""
out = bytearray(name(title, 20))
for i in range(31):
if i < len(samples):
s = samples[i]
ls, ll = s.get("loop") or (0, 2)
out += name(s.get("name", ""), 22) + struct.pack(">HBBHH", len(s["data"]) // 2, s.get("finetune", 0) & 15,
s.get("volume", 64), ls // 2, ll // 2)
else:
out += b"\0" * 22 + struct.pack(">HBBHH", 0, 0, 0, 0, 1)
out += bytes([len(orders), restart]) + bytes(orders) + b"\0" * (128 - len(orders))
out += b"M.K." if channels == 4 else (b"%dCHN" % channels if channels < 10 else b"%dCH" % channels)
for pat in patterns:
for row in pat:
for (note, ins, fx, param) in row:
p = mod_period(note)
out += bytes([(ins & 0xF0) | (p >> 8), p & 255, ((ins & 15) << 4) | fx, param])
for s in samples:
out += s["data"]
return bytes(out)
# ---------------------------------------------------------------------------------------------- S3M
def write_s3m(title, samples, orders, patterns, channels, speed=6, tempo=125, gvol=64, mvol=48 | 128, pans=None,
flags=0, cwt=0x1320, chanset=None):
"""samples: [{name, data (u8 bytes), volume, c2spd, loop: (start, end) | None}];
patterns: [[row: [(note, ins, vol, cmd, info)] * channels] * 64] with note 0 = none, 254 = cut, else S3M byte
(octave << 4 | semitone); vol None = none; cmd 0 = none (A = 1)."""
ordn = list(orders) + [255]
if len(ordn) % 2:
ordn.append(255)
nins, npat = len(samples), len(patterns)
head = bytearray(name(title, 28) + bytes([0x1A, 16, 0, 0]))
head += struct.pack("<HHHHHH", len(ordn), nins, npat, flags, cwt, 2) + b"SCRM"
head += bytes([gvol, speed, tempo, mvol, 16, 252 if pans else 0]) + b"\0" * 8 + struct.pack("<H", 0)
cs = chanset or [(i % 2) * 8 + i // 2 if i < channels else 255 for i in range(32)]
head += bytes(cs[:32] + [255] * (32 - len(cs)))
head += bytes(ordn)
ptr_at = len(head)
head += b"\0" * (2 * (nins + npat))
if pans:
head += bytes([(0x20 | (p & 15)) for p in pans] + [0] * (32 - len(pans)))
body = bytearray(head)
def align():
while len(body) % 16:
body.append(0)
ins_ptrs, pat_ptrs, ins_at = [], [], []
for s in samples:
align()
ins_ptrs.append(len(body) // 16)
ins_at.append(len(body))
body += b"\0" * 80
for pat in patterns:
align()
pat_ptrs.append(len(body) // 16)
pk = bytearray()
for row in pat:
for ch, (note, ins, vol, cmd, info) in enumerate(row):
what = 0
if note or ins:
what |= 0x20
if vol is not None:
what |= 0x40
if cmd:
what |= 0x80
if what:
pk.append(what | ch)
if what & 0x20:
pk += bytes([note if note else 255, ins])
if what & 0x40:
pk.append(vol)
if what & 0x80:
pk += bytes([cmd, info])
pk.append(0)
body += struct.pack("<H", len(pk) + 2) + pk
for i, s in enumerate(samples):
align()
seg = len(body) // 16
body += s["data"]
ls, le = s.get("loop") or (0, 0)
h = bytearray(80)
h[0] = 1
h[1:13] = name(s.get("name", "") + ".smp", 12)
h[13] = seg >> 16
struct.pack_into("<H", h, 14, seg & 0xFFFF)
struct.pack_into("<IIIBBBB", h, 16, len(s["data"]), ls, le, s.get("volume", 64), 0, 0, 1 if s.get("loop") else 0)
struct.pack_into("<I", h, 32, s.get("c2spd", 8363))
h[48:76] = name(s.get("name", ""), 28)
h[76:80] = b"SCRS"
body[ins_at[i]:ins_at[i] + 80] = h
for k, p in enumerate(ins_ptrs + pat_ptrs):
struct.pack_into("<H", body, ptr_at + 2 * k, p)
return bytes(body)
def s3m_note(note):
"""our note number (1 = C-0, 61 = C-5 IT = S3M C-4) -> the S3M note byte"""
n = note - 13
return (n // 12) << 4 | (n % 12)
# ---------------------------------------------------------------------------------------------- XM
def env_bytes(points):
b = bytearray()
for (x, y) in points[:12]:
b += struct.pack("<HH", x, y)
return bytes(b + b"\0" * (48 - len(b)))
def write_xm(title, instruments, orders, patterns, channels, speed=6, tempo=125, linear=True, restart=0):
"""instruments: [{name, samples: [{name, data (raw bytes, not delta), bits 8|16, volume, finetune, pan, relnote,
loop: (start, length, type 1|2) | None}], keymap: [96 sample indexes] | None, volenv: {points, sustain, loop:
(s, e)} | None, panenv: ..., fadeout, vib: (type, sweep, depth, rate)}];
patterns: [[row: [(note, ins, vol, fx, param)] * channels]] (note 97 = key off; vol = raw volume byte)"""
out = bytearray(b"Extended Module: " + name(title, 20) + b"\x1a" + name("formats-luau fixtures", 20))
out += struct.pack("<HIHHHHHHHH", 0x0104, 276, len(orders), restart, channels, len(patterns), len(instruments),
1 if linear else 0, speed, tempo)
out += bytes(orders) + b"\0" * (256 - len(orders))
for pat in patterns:
pk = bytearray()
for row in pat:
for (note, ins, vol, fx, param) in row:
flags = 0x80 | (1 if note else 0) | (2 if ins else 0) | (4 if vol else 0) | (8 if fx else 0) | (16 if param else 0)
pk.append(flags)
for bit, v in ((1, note), (2, ins), (4, vol), (8, fx), (16, param)):
if flags & bit:
pk.append(v)
out += struct.pack("<IBHH", 9, 0, len(pat), len(pk)) + pk
for ins in instruments:
smps = ins.get("samples", [])
if not smps:
out += struct.pack("<I", 29) + name(ins.get("name", ""), 22) + struct.pack("<BH", 0, 0)
continue
h = bytearray(struct.pack("<I", 263) + name(ins.get("name", ""), 22) + struct.pack("<BHI", 0, len(smps), 40))
h += bytes(ins.get("keymap") or [0] * 96)
ve, pe = ins.get("volenv"), ins.get("panenv")
h += env_bytes(ve["points"] if ve else []) + env_bytes(pe["points"] if pe else [])
h += bytes([len(ve["points"]) if ve else 0, len(pe["points"]) if pe else 0])
for e in (ve, pe):
if e:
ls, le = e.get("loop") or (0, 0)
h += bytes([e.get("sustain", 0) or 0, ls, le])
else:
h += b"\0\0\0"
for e in (ve, pe):
t = 0
if e:
t = 1 | (2 if e.get("sustain") is not None else 0) | (4 if e.get("loop") else 0)
h.append(t)
vt, vs, vd, vr = ins.get("vib", (0, 0, 0, 0))
h += bytes([vt, vs, vd, vr]) + struct.pack("<H", ins.get("fadeout", 0)) + b"\0" * 22
out += h
for s in smps:
bpsm = 2 if s.get("bits", 8) == 16 else 1
ls, ll, lt = s.get("loop") or (0, 0, 0)
t = lt | (16 if bpsm == 2 else 0)
out += struct.pack("<IIIBbBBbB", len(s["data"]), ls * bpsm, ll * bpsm, s.get("volume", 64), s.get("finetune", 0),
t, s.get("pan", 128), s.get("relnote", 0), 0) + name(s.get("name", ""), 22)
for s in smps:
out += delta16(s["data"]) if s.get("bits", 8) == 16 else delta8(s["data"])
return bytes(out)
# ---------------------------------------------------------------------------------------------- IT
def it_compress(raw, bits, it215):
"""IT 2.14 / 2.15 compression with a constant bit width (9 for 8-bit, 17 for 16-bit): valid for every decoder,
no width changes"""
width = 9 if bits == 8 else 17
block = 0x8000 if bits == 8 else 0x4000
if bits == 8:
vals = [b - 256 if b >= 128 else b for b in raw]
else:
vals = [struct.unpack_from("<h", raw, i)[0] for i in range(0, len(raw), 2)]
mask = (1 << (bits)) - 1
out = bytearray()
for start in range(0, len(vals), block):
chunk = vals[start:start + block]
acc, nbits, data = 0, 0, bytearray()
d1 = d2 = 0
for v in chunk:
if it215:
nd1 = v - d2 # second-order: the decoder does d1 += x; d2 += d1; out d2
x = nd1 - d1
d1, d2 = nd1, v
else:
x = v - d1
d1 = v
acc |= (x & mask) << nbits
nbits += width
while nbits >= 8:
data.append(acc & 255)
acc >>= 8
nbits -= 8
if nbits:
data.append(acc & 255)
out += struct.pack("<H", len(data)) + data
return bytes(out)
def it_env(e):
b = bytearray(82)
if e:
flags = 1 | (2 if e.get("loop") else 0) | (4 if e.get("sustain") else 0) | (128 if e.get("filter") else 0)
b[0] = flags
b[1] = len(e["points"])
ls, le = e.get("loop") or (0, 0)
ss, se = e.get("sustain") or (0, 0)
b[2], b[3], b[4], b[5] = ls, le, ss, se
for i, (x, y) in enumerate(e["points"][:25]):
struct.pack_into("<bH", b, 6 + i * 3, y, x)
return bytes(b)
def write_it(title, samples, instruments, orders, patterns, channels, speed=6, tempo=125, gv=128, mv=48, linear=True,
old=False, compat=False, pans=None, vols=None, msg=None):
"""samples: [{name, data (raw signed bytes), bits, stereo, volume, gv, pan (0..64) | None, c5, loop: (s, e, ping),
sus: (s, e, ping), compress: None | 214 | 215, vib: (speed, depth, rate, type)}];
instruments: None (sample mode) or [{name, nna, dct, dca, fadeout, gbv, pan | None, pps, ppc, ifc, ifr,
keymap: [(note, sample)] * 120, volenv / panenv / pitchenv: {points [(tick, value)], loop, sustain, filter}}];
patterns: [[row: [(note, ins, vol, cmd, param)] * channels]] with note 0 = none else IT note + 1 (1 = C-0) or
255 / 254 / 253; vol None or the raw volume byte; cmd 0 = none (A = 1)."""
ins_list = instruments or []
ordn = list(orders) + [255]
flags = 1 | (4 if instruments else 0) | (8 if linear else 0) | (16 if old else 0) | (32 if compat else 0)
head = bytearray(b"IMPM" + name(title, 26) + struct.pack("<H", 0x1004))
head += struct.pack("<HHHHHHHH", len(ordn), len(ins_list), len(samples), len(patterns), 0x0214, 0x0214, flags, 0)
head += bytes([gv, mv, speed, tempo, 128, 0]) + struct.pack("<HII", 0, 0, 0)
cp = [(pans[i] if pans and i < len(pans) else 32) if i < channels else 32 + 128 for i in range(64)]
head += bytes(cp) + bytes([(vols[i] if vols and i < len(vols) else 64) for i in range(64)])
head += bytes(ordn)
ptr_at = len(head)
head += b"\0" * (4 * (len(ins_list) + len(samples) + len(patterns)))
body = bytearray(head)
ptrs = []
for ins in ins_list:
ptrs.append(len(body))
b = bytearray(554)
b[0:4] = b"IMPI"
b[17], b[18], b[19] = ins.get("nna", 0), ins.get("dct", 0), ins.get("dca", 0)
struct.pack_into("<H", b, 20, ins.get("fadeout", 0))
struct.pack_into("<bB", b, 22, ins.get("pps", 0), ins.get("ppc", 60))
b[24] = ins.get("gbv", 128)
b[25] = ins["pan"] if ins.get("pan") is not None else 128 + 32
b[32:58] = name(ins.get("name", ""), 26)
b[58] = ins.get("ifc", 0)
b[59] = ins.get("ifr", 0)
km = ins["keymap"]
for n in range(120):
b[64 + 2 * n], b[65 + 2 * n] = km[n]
for k, key in enumerate(("volenv", "panenv", "pitchenv")):
b[304 + 82 * k:386 + 82 * k] = it_env(ins.get(key))
body += b
smp_at = []
for s in samples:
ptrs.append(len(body))
smp_at.append(len(body))
body += b"\0" * 80
for pat in patterns:
ptrs.append(len(body))
pk = bytearray()
for row in pat:
for ch, (note, ins, vol, cmd, param) in enumerate(row):
mask = (1 if note else 0) | (2 if ins else 0) | (4 if vol is not None else 0) | (8 if cmd else 0)
if mask:
pk += bytes([(ch + 1) | 128, mask])
if note:
pk.append(note - 1 if note < 253 else note)
if ins:
pk.append(ins)
if vol is not None:
pk.append(vol)
if cmd:
pk += bytes([cmd, param])
pk.append(0)
body += struct.pack("<HHI", len(pk), len(pat), 0) + pk
for i, s in enumerate(samples):
raw = s["data"]
stereo = s.get("stereo", False)
bps = 2 if s.get("bits", 8) == 16 else 1
frames = len(raw) // bps // (2 if stereo else 1)
comp = s.get("compress")
if comp:
if stereo:
half = len(raw) // 2
data = it_compress(raw[:half], s.get("bits", 8), comp == 215) + it_compress(raw[half:], s.get("bits", 8), comp == 215)
else:
data = it_compress(raw, s.get("bits", 8), comp == 215)
else:
data = raw
ptr = len(body)
body += data
h = bytearray(80)
h[0:4] = b"IMPS"
fl = 1 | (2 if bps == 2 else 0) | (4 if stereo else 0) | (8 if comp else 0)
lp, sp = s.get("loop"), s.get("sus")
if lp:
fl |= 16 | (64 if lp[2] else 0)
if sp:
fl |= 32 | (128 if sp[2] else 0)
h[17], h[18], h[19] = s.get("gv", 64), fl, s.get("volume", 64)
h[20:46] = name(s.get("name", ""), 26)
h[46] = 1 | (4 if comp == 215 else 0)
h[47] = (s["pan"] | 128) if s.get("pan") is not None else 32
struct.pack_into("<IIIIIII", h, 48, frames, lp[0] if lp else 0, lp[1] if lp else 0, s.get("c5", 8363),
sp[0] if sp else 0, sp[1] if sp else 0, ptr)
vs, vd, vr, vt = s.get("vib", (0, 0, 0, 0))
h[76], h[77], h[78], h[79] = vs, vd, vr, vt
body[smp_at[i]:smp_at[i] + 80] = h
for k, p in enumerate(ptrs):
struct.pack_into("<I", body, ptr_at + 4 * k, p)
return bytes(body)
# ---------------------------------------------------------------------------------------------- reference render
def openmpt(ctx, data, ext, extra=()):
"""the module rendered by openmpt123 (linear interpolation, no Amiga resampler): (left, right) float lists"""
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "song." + ext)
with open(p, "wb") as f:
f.write(data)
raw = ctx.nix("libopenmpt", ["openmpt123", "--batch", "--quiet", "--stdout", "--samplerate", str(SR),
"--channels", "2", "--float", "--filter", "2", "--stereo", "100",
"--ctl", "render.resampler.emulate_amiga=0", *extra, p])
import array
a = array.array("f")
a.frombytes(raw[: len(raw) // 8 * 8])
return a[0::2], a[1::2]
def fft(re, im):
n = len(re)
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
re[i], re[j] = re[j], re[i]
im[i], im[j] = im[j], im[i]
size = 2
while size <= n:
ang = -2 * math.pi / size
wr, wi = math.cos(ang), math.sin(ang)
for start in range(0, n, size):
cr, ci = 1.0, 0.0
half = size // 2
for k in range(half):
a, b = start + k, start + k + half
tr = re[b] * cr - im[b] * ci
ti = re[b] * ci + im[b] * cr
re[b], im[b] = re[a] - tr, im[a] - ti
re[a], im[a] = re[a] + tr, im[a] + ti
cr, ci = cr * wr - ci * wi, cr * wi + ci * wr
size *= 2
EDGES = [F_LO * (F_HI / F_LO) ** (j / BANDS) for j in range(BANDS + 1)]
WINDOW = [0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) for i in range(HOP)]
def features(left, right):
"""{frames, rmsL, rmsR, rmsM, bands (frames * BANDS magnitudes)} of a stereo signal"""
n = len(left) // HOP
out = {"frames": n, "rmsL": [], "rmsR": [], "rmsM": [], "bands": []}
for k in range(n):
o = k * HOP
L, R = left[o:o + HOP], right[o:o + HOP]
M = [(a + b) / 2 for a, b in zip(L, R)]
out["rmsL"].append(math.sqrt(sum(x * x for x in L) / HOP))
out["rmsR"].append(math.sqrt(sum(x * x for x in R) / HOP))
out["rmsM"].append(math.sqrt(sum(x * x for x in M) / HOP))
re = [M[i] * WINDOW[i] for i in range(HOP)]
im = [0.0] * HOP
fft(re, im)
e = [0.0] * BANDS
for b in range(1, HOP // 2):
f = b * SR / HOP
if f < F_LO or f >= F_HI:
continue
j = min(BANDS - 1, int(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS))
e[j] += re[b] * re[b] + im[b] * im[b]
out["bands"] += [math.sqrt(x) for x in e]
return out
def duration(ctx, data, ext):
"""openmpt123 --info's song length in seconds"""
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "song." + ext)
with open(p, "wb") as f:
f.write(data)
info = ctx.nix("libopenmpt", ["openmpt123", "--info", p]).decode(errors="replace")
for line in info.splitlines():
if line.startswith("Duration"):
secs = 0.0
for part in line.split(":", 1)[1].strip().split(":"):
secs = secs * 60 + float(part)
return secs
raise RuntimeError("openmpt123 --info: no duration")
def reference(ctx, data, ext, extra=()):
left, right = openmpt(ctx, data, ext, extra)
f = features(left, right)
f["duration"] = duration(ctx, data, ext)
return f
+104
View File
@@ -0,0 +1,104 @@
# MOD fixtures (tools/fixtures.py): generated ProTracker modules exercising the effects, rendered by openmpt123.
# tests/gen/mod_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
# duration (openmpt's song length) }
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _tracker as T # noqa: E402
INPUTS = ["tools/fixtures/_tracker.py"]
def empty(ch):
return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(64)]
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, "loop": (0, 64)},
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "loop": (0, 64)},
{"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64)},
{"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 64},
{"name": "tri ft", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 56, "finetune": 3, "loop": (0, 32)},
]
def song_basic():
a, b = empty(4), empty(4)
mel = [49, 53, 56, 61, 56, 53, 51, 49]
for i in range(16):
put(a, i * 4, 0, mel[i % 8], 1)
put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0)
put(a, 0, 2, 49, 3, 0x1, 0x02)
put(a, 16, 2, 0, 0, 0x2, 0x03)
put(a, 32, 2, 61, 3, 0xC, 0x30)
put(a, 33, 2, 0, 0, 0xA, 0x02)
put(a, 48, 2, 0, 0, 0xA, 0x40)
for r in range(0, 64, 8):
put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2)
put(a, 60, 3, 61, 4, 0xE, 0xC2)
# pattern b: portamento, vibrato, tremolo, offsets, retrig, delay, fine slides, speed change, break
put(b, 0, 0, 49, 1)
put(b, 4, 0, 61, 0, 0x3, 0x08)
put(b, 8, 0, 0, 0, 0x3, 0x00)
put(b, 12, 0, 49, 0, 0x5, 0x02)
put(b, 16, 0, 56, 5, 0x4, 0x46)
put(b, 20, 0, 0, 0, 0x6, 0x01)
put(b, 24, 0, 0, 0, 0x4, 0x8F)
put(b, 0, 1, 37, 2, 0x7, 0x48)
put(b, 8, 1, 0, 0, 0x7, 0x00)
put(b, 16, 1, 44, 2, 0xE, 0x12)
put(b, 17, 1, 0, 0, 0xE, 0x12)
put(b, 20, 1, 0, 0, 0xE, 0x24)
put(b, 24, 1, 0, 0, 0xE, 0xB8)
put(b, 28, 1, 0, 0, 0xE, 0xA4)
put(b, 0, 3, 49, 4, 0x9, 0x08)
put(b, 8, 3, 49, 4, 0xE, 0x93)
put(b, 16, 3, 56, 4, 0xE, 0xD3)
put(b, 24, 2, 49, 3, 0xF, 0x03)
put(b, 32, 2, 51, 3, 0xF, 0x90)
put(b, 40, 2, 53, 3, 0xF, 0x06)
put(b, 40, 3, 61, 4, 0x9, 0x04)
put(b, 44, 0, 49, 5, 0xE, 0x53)
put(b, 48, 0, 0, 0, 0xD, 0x00)
return T.write_mod("basic", samples(), [0, 1], [a, b])
def song_loops():
a, b, c = empty(4), empty(4), empty(4)
put(a, 0, 0, 49, 1, 0xF, 0x04)
put(a, 4, 0, 0, 0, 0xE, 0x60)
put(a, 5, 1, 61, 2)
put(a, 8, 0, 53, 1, 0xE, 0x62)
put(a, 16, 0, 56, 1, 0xE, 0xE3)
put(a, 17, 2, 37, 3, 0xA, 0x01)
put(a, 32, 0, 0, 0, 0xD, 0x16)
put(b, 16, 0, 61, 1)
put(b, 20, 3, 49, 4, 0xF, 0x70)
put(b, 24, 0, 0, 0, 0xB, 0x02)
put(c, 0, 1, 50, 5)
put(c, 4, 1, 0, 0, 0xB, 0x01)
return T.write_mod("loops", samples(), [0, 1, 2], [a, b, c])
def song_8ch():
a = empty(8)
for ch in range(8):
put(a, ch * 2, ch, 37 + ch * 5, 1 + ch % 3, 0x8, ch * 32)
put(a, 32, 0, 61, 5, 0xE, 0x84)
put(a, 32, 7, 49, 4, 0x8, 0xFF)
put(a, 63, 0, 0, 0, 0xF, 0x00)
return T.write_mod("eight", samples(), [0], [a], channels=8)
def generate(ctx):
cases = []
for nm, data in (("basic", song_basic()), ("loops", song_loops()), ("8ch", song_8ch())):
ref = T.reference(ctx, data, "mod")
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
ctx.emit("mod_cases", cases)