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

+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