codecs/audio: comments to specs only

This commit is contained in:
4DBug committed 2026-11-01 01:55:39 -05:00
1 parent 0bd7b87d2b
commit 6dcce481bb
69 files changed
+523 -1604

No files matched your search

+9 -24
View File
@@ -1,10 +1,7 @@
--!strict
-- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the
-- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders
-- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter
-- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers
-- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence,
-- licenses/openmpt-LICENSE.txt), reduced to what the engine plays.
-- codecs/audio/Tracker/Load: helpers mapping other tracker formats' effects onto the engine's S3M / IT or MOD / XM families.
-- Ported from OpenMPT's ModCommand helpers (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight,
-- CPattern::WriteEffect; BSD licence, licenses/openmpt-LICENSE.txt).
local Err = require("@rosetta/core/Err")
local Player = require("@rosetta/codecs/audio/Tracker/Player")
local Pcm = require("@rosetta/codecs/audio/Tracker/Pcm")
@@ -14,7 +11,6 @@ local Load = {}
local EXT = Player.EXT
-- the S3M / IT letter code of each effect name (engine extension effects included)
local IT: { [string]: number } = {
speed = 1,
jump = 2,
@@ -67,7 +63,7 @@ end
local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true }
-- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand)
-- OpenMPT's IsGlobalCommand
function Load.isGlobal(name: string?, param: number): boolean
if name == nil then
return false
@@ -84,7 +80,7 @@ function Load.isGlobal(name: string?, param: number): boolean
return false
end
-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand)
-- OpenMPT's ConvertModCommand
local MODFX: { [number]: string } = {
[0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol",
[6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump",
@@ -104,8 +100,7 @@ function Load.modCommand(cmd: number, param: number): (string?, number)
return n, param
end
-- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there,
-- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision)
-- OpenMPT's ConvertToVolCommand (force: fit with some loss of precision)
function Load.itVolume(name: string?, param: number, force: boolean): number?
if name == "volume" then
return math.min(param, 64) + 1
@@ -159,8 +154,6 @@ function Load.itVolume(name: string?, param: number, force: boolean): number?
return nil
end
-- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's
-- extended E commands become their S3M equivalents)
function Load.itEffect(name: string?, param: number): (number, number)
if name == nil then
return 0, 0
@@ -191,9 +184,7 @@ function Load.itEffect(name: string?, param: number): (number, number)
return code, param
end
-- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param,
-- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the
-- heavier one when both cannot fit (OpenMPT's FillInTwoCommands)
-- OpenMPT's FillInTwoCommands
function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number)
if e1 ~= nil and e1 == e2 then
e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification)
@@ -215,10 +206,7 @@ function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number
return 0, e2, p2, e1, p1
end
-- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect
-- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or
-- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's
-- CPattern::WriteEffect).
-- OpenMPT's CPattern::WriteEffect
function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean
local p = m.patterns[pattern + 1]
if not p then
@@ -261,9 +249,6 @@ function Load.writeEffect(m: any, pattern: number, row: number, fx: number, para
return false
end
-- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm
-- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames
-- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes).
function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?)
local nch = spec.channels or 1
local bps = spec.bits // 8
@@ -282,7 +267,7 @@ function Load.readSample(buf: buffer, offset: number, frames: number, spec: any,
return true, nil
end
-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99)
-- S3M / MOD pattern breaks store the row as two decimal digits
function Load.bcd(n: number): number
n = math.clamp(math.floor(n), 0, 99)
return (n // 10) * 16 + n % 10
+2 -8
View File
@@ -1,17 +1,12 @@
--!strict
--!native
-- codecs/audio/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/audio/Tracker)
-- validates the sample buffers' sizes.
-- codecs/audio/Tracker/Mixer: tracker voice mixing (loops, IT sustain loops, IT two-pole resonant filter, click ramps).
-- No third-party code.
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
@@ -161,7 +156,6 @@ local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: bo
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
+4 -10
View File
@@ -1,9 +1,7 @@
--!strict
--!native
-- codecs/audio/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).
-- codecs/audio/Tracker/Pcm: raw 8 / 16-bit tracker sample data (signed / unsigned, XM / IT 2.15 delta coding,
-- interleaved or planar stereo) <-> f32.
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
@@ -11,20 +9,18 @@ local floor = math.floor
local Pcm = {}
export type Spec = {
bits: number, -- 8 | 16
bits: number,
signed: boolean,
delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag)
channels: number?, -- 1 (default) | 2
channels: number?,
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
@@ -76,7 +72,6 @@ function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffe
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
@@ -118,7 +113,6 @@ function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer
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
+13 -53
View File
@@ -1,14 +1,8 @@
--!strict
--!native
-- codecs/audio/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders,
-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric
-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes,
-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song
-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes,
-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/audio/Tracker/Mixer.
--
-- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is
-- guarded.
-- codecs/audio/Tracker/Player: the tracker sequencer for the MOD, S3M, XM and IT effect families.
-- Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, ST3 TECH.DOC, ITTECH.TXT);
-- no third-party code.
local Tables = require("@rosetta/codecs/audio/Tracker/Tables")
local wave64, autoWave = Tables.wave64, Tables.autoWave
@@ -23,8 +17,6 @@ local MOD, S3M, XM, IT = 1, 2, 3, 4
Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT
local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT }
-- engine extension effects: format-specific commands of the other tracker formats, in any family (see
-- codecs/audio/Tracker)
local EXT = {
NOTE_SLIDE_UP = 0x40,
NOTE_SLIDE_DOWN = 0x41,
@@ -37,9 +29,8 @@ local EXT = {
}
Player.EXT = EXT
local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions
local BG_VOICES = 64
-- ------------------------------------------------------------------------------------------------ state
local function newVoice(): any
return {
active = false,
@@ -100,8 +91,8 @@ local function newVoice(): any
tremorMute = false,
surround = false,
rampN = 0,
owner = 0, -- the channel whose foreground voice this is (0: free or background)
order = 0, -- allocation age
owner = 0,
order = 0,
}
end
@@ -126,7 +117,6 @@ local function newChannel(i: number, pan: number, vol: number): any
fx = 0,
param = 0,
vcmd = 0,
-- memories
mPortaUp = 0,
mPortaDn = 0,
mFineUp = 0,
@@ -186,15 +176,14 @@ local function newChannel(i: number, pan: number, vol: number): any
muted = false,
triggered = false,
autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down
autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running
autoTone = false,
hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669)
slideCount = 0, -- note slides: ticks to the next step
slideCount = 0,
mNoteSlide = 0,
tonePortaRow = false,
}
end
-- new(module, opts) -> player state (module validated by the caller)
function Player.new(m: any, sampleRate: number, opts: any): any
local fmt = FAMILY[m.engine or m.format] or MOD
local flags = m.flags
@@ -213,8 +202,8 @@ function Player.new(m: any, sampleRate: number, opts: any): any
compatG = m.flags.compatGxx or false,
fastSlides = flags.fastSlides or false,
amigaLimits = flags.amigaLimits or false,
ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock)
hz = flags.periods == "hz", -- periods are frequencies in Hz
ptPeriods = ptPeriods,
hz = flags.periods == "hz",
hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1,
hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1,
fastPortas = flags.fastPortas or false,
@@ -286,8 +275,6 @@ function Player.masterGain(m: any, fmt: number): number
return 2 / clamp(m.channels, 2, 8)
end
-- ------------------------------------------------------------------------------------------------ orders and rows
-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended
function Player.startOrder(st: any, ord: number, row: number)
local m = st.m
local order = m.order
@@ -357,8 +344,6 @@ local function advanceRow(st: any)
end
end
-- ------------------------------------------------------------------------------------------------ pitch
-- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces)
local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number)
local base, ref, tr
if st.fmt == MOD or st.fmt == XM then
@@ -412,8 +397,7 @@ local function clampPeriod(st: any, c: any)
end
end
-- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency
-- moves units * hzSlide Hz the other way
-- pitch slides in period units (positive: down; 4 per effect unit); in Hz mode the frequency moves units * hzSlide Hz the other way
local function slide(st: any, c: any, units: number)
if st.hz then
c.period -= units * st.hzScale
@@ -423,7 +407,6 @@ local function slide(st: any, c: any, units: number)
clampPeriod(st, c)
end
-- ------------------------------------------------------------------------------------------------ voices
local function allocVoice(st: any): any
local best, bestScore = nil, math.huge
for _, v in st.voices do
@@ -441,7 +424,6 @@ local function allocVoice(st: any): any
best.active = false
return best
end
-- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway
for _, v in st.voices do
if not v.active then
local c = st.chans[v.owner]
@@ -451,7 +433,7 @@ local function allocVoice(st: any): any
return v
end
end
return st.voices[1] -- unreachable: there are more voices than channels
return st.voices[1]
end
local function keyOff(st: any, v: any)
@@ -492,7 +474,6 @@ local function cutVoice(v: any)
end
end
-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c
local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any)
local v = c.voice
if v == nil or v.bg then
@@ -541,7 +522,6 @@ end
-- IT new note actions on the channel's current voice (and duplicate checks on all its voices)
local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number)
-- duplicate check: voices of this channel playing the same instrument
if ins and ins.dct and ins.dct > 0 then
for _, u in st.voices do
if u.active and u.chan == c.idx and u.insIdx == insIdx then
@@ -582,7 +562,6 @@ local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: nu
end
end
-- ------------------------------------------------------------------------------------------------ triggering
local function isPorta(st: any, fx: number, vcmd: number): boolean
local f = st.fmt
if f == MOD then
@@ -594,7 +573,6 @@ local function isPorta(st: any, fx: number, vcmd: number): boolean
return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203)
end
-- the sample and real note for an instrument number + note
local function resolve(st: any, insIdx: number, note: number): (any, number, any, number)
local m = st.m
if st.insMode then
@@ -668,7 +646,6 @@ local function sampleOffset(st: any, c: any, v: any)
end
end
-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell
local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number)
local f = st.fmt
local m = st.m
@@ -802,7 +779,6 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb
end
end
-- ------------------------------------------------------------------------------------------------ effect helpers
local function volSlideMod(c: any, param: number)
local x, y = param // 16, param % 16
if x > 0 then
@@ -858,8 +834,7 @@ local function retrigVolume(c: any, x: number)
c.vol = clamp(c.vol, 0, 64)
end
-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks;
-- fast: normal parts on tick 0 too)
-- S3M / IT D-style slide: fine parts only on tick 0, normal parts on other ticks (fast: normal parts on tick 0 too)
local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number
local x, y = param // 16, param % 16
if y == 0xF and x > 0 then
@@ -884,7 +859,6 @@ local function dSlide(value: number, param: number, tick: number, fast: boolean,
return value
end
-- ------------------------------------------------------------------------------------------------ MOD / XM effects
local function fxModXm(st: any, c: any, tick: number)
local fx, param = c.fx, c.param
local xm = st.fmt == XM
@@ -1198,7 +1172,6 @@ local function volColXm(st: any, c: any, tick: number)
end
end
-- ------------------------------------------------------------------------------------------------ S3M / IT effects
-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects
local function mem(st: any, c: any, field: string, param: number): number
if st.fmt == S3M then
@@ -1606,8 +1579,6 @@ local function volColIt(st: any, c: any, tick: number)
end
end
-- ------------------------------------------------------------------------------------------------ extension effects
-- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family
local function fxExt(st: any, c: any, tick: number)
local fx, param = c.fx, c.param
if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then
@@ -1666,7 +1637,6 @@ local function fxExt(st: any, c: any, tick: number)
end
end
-- ------------------------------------------------------------------------------------------------ rows and ticks
local function noteDelayOf(st: any, fx: number, param: number): number
if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then
return param % 16
@@ -1764,7 +1734,6 @@ local function processRow(st: any)
end
local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean)
-- returns value, next position, ended
local ticks, values = env.ticks, env.values
local n = #ticks
if n == 0 then
@@ -1805,7 +1774,6 @@ local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean
return value, nextPos, ended
end
-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter
local function updateVoice(st: any, v: any)
local ins = v.ins
local it = st.fmt == IT
@@ -1876,7 +1844,6 @@ local function updateVoice(st: any, v: any)
end
v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256
end
-- frequency
local P = v.periodOut + avDelta
local freq
if st.hz then
@@ -1890,7 +1857,6 @@ local function updateVoice(st: any, v: any)
freq *= 2 ^ (envPitch / 24)
end
v.inc = freq / st.sr
-- volume
local smp = v.smp
local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128
-- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader,
@@ -1899,7 +1865,6 @@ local function updateVoice(st: any, v: any)
if v.tremorMute then
vol = 0
end
-- panning
local pan = v.pan
if it and ins and (ins.pps or 0) ~= 0 then
pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256)
@@ -1921,7 +1886,6 @@ local function updateVoice(st: any, v: any)
v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256
end
v.rampN = st.ramp
-- IT resonant filter
local cutoff = v.cutoff
if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then
local cc = cutoff
@@ -1946,7 +1910,6 @@ local function updateVoice(st: any, v: any)
end
end
-- tick(st) -> frames to mix for this tick (0 when the song ended)
function Player.tick(st: any): number
if st.ended then
return 0
@@ -1959,7 +1922,6 @@ function Player.tick(st: any): number
return 0
end
if st.visited[key] then
-- looping on: forget the song so far, keep playing
table.clear(st.visited)
end
st.fineDelay = 0
@@ -1983,7 +1945,6 @@ function Player.tick(st: any): number
if st.ended then
return 0
end
-- channel -> foreground voice
for i = 1, st.nch do
local c = st.chans[i]
local v = c.voice
@@ -2009,7 +1970,6 @@ function Player.tick(st: any): number
end
-- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does)
local frames = floor(st.sr * 2.5 / max(1, st.tempo))
-- advance
st.tick += 1
if st.tick >= st.speed + st.fineDelay then
st.tick = 0
+5 -17
View File
@@ -1,15 +1,12 @@
--!strict
--!native
-- codecs/audio/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).
-- codecs/audio/Tracker/Tables: tracker lookup tables, 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
@@ -31,8 +28,6 @@ function Tables.wave64(kind: number, pos: number): number
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)
@@ -59,9 +54,7 @@ function Tables.autoWave(kind: number, pos: number, it: boolean): number
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).
-- ProTracker periods, finetune 0, C-0 .. B-4; note 1 = C-0 (FT2 numbering), C-2 (428) = note 49 plays at 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,
@@ -73,12 +66,10 @@ local PERIODS = {
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
@@ -88,7 +79,6 @@ function Tables.periodToNote(period: number): number
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
@@ -104,14 +94,12 @@ Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 }
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)
-- frequency = AMIGA / period; period 1712 plays an 8363 Hz sample at its base rate (FT2 / ST3 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
-- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor)
-- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM)
-- Scream Tracker 2 tempo byte as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at 23863 Hz, as a fractional BPM)
local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 }
function Tables.st2Tempo(byte: number): (number, number)
local hi, lo = byte // 16, byte % 16
+18 -90
View File
@@ -1,67 +1,18 @@
--!strict
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders
-- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in
-- codecs/audio/Tracker/Load). The 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.
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, s3m, xm and it, and the formats mapped onto them.
-- Written 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("@rosetta/codecs/audio/Tracker")
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
-- Pattern cells are 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. 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). Extension effects (Tracker.EXT): 0x40 / 0x41 note
-- slide up / down, 0x42 / 0x43 with retrigger (param = ticks per step << 4 | semitones), 0x44 / 0x45 auto portamento
-- up / down (669), 0x46 frequency adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED).
--
-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file):
-- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from
-- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four
-- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm",
-- music/669: "s3m", ...) and set the quirks they need in flags.
-- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family
-- 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: also on tick 0; any family),
-- amigaLimits (MOD), and the quirks of the other formats (any family):
-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in
-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta),
-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows),
-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo),
-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels),
-- envRowHold (MED: envelopes do not advance on a row's first tick) }
-- 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). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note
-- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones;
-- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency
-- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)).
-- 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.
-- Pitch: linear P = (ref - note) * 64 - transpose, 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.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Player = require("@rosetta/codecs/audio/Tracker/Player")
@@ -86,38 +37,32 @@ export type Envelope = {
susEnd: number,
carry: boolean?,
filter: boolean?,
raw: any?, -- format-specific fields kept for a faithful re-save (XM)
raw: any?,
}
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)
sampleRate: number?,
interpolation: ("linear" | "none")?,
stereoSeparation: number?,
loop: boolean?,
maxDuration: number?,
}
local CELL = 5
-- engine extension effects (see the Module notes above)
Tracker.EXT = Player.EXT
-- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte
Tracker.st2Tempo = Tables.st2Tempo
local FAMILIES = { mod = true, s3m = true, xm = true, it = true }
-- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as
function Tracker.family(m: any): string?
local f = m.engine or m.format
return if type(f) == "string" and FAMILIES[f] then f else nil
end
-- ------------------------------------------------------------------------------------------------ constructors
-- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family
-- (engine, default format)
function Tracker.newModule(format: string, channels: number, engine: string?): any
local fam = engine or format
local m = {
@@ -156,12 +101,10 @@ function Tracker.newModule(format: string, channels: number, engine: string?): a
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 "",
@@ -192,7 +135,6 @@ 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
@@ -222,8 +164,6 @@ function Tracker.newInstrument(name: string?): any
}
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
@@ -234,7 +174,6 @@ function Tracker.cell(m: any, pattern: number, row: number, channel: number): (n
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
@@ -250,7 +189,6 @@ function Tracker.setCell(m: any, pattern: number, row: number, channel: number,
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
@@ -312,8 +250,6 @@ local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number,
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")
@@ -420,11 +356,9 @@ function Tracker.validate(m: any): (boolean?, Err.Err?)
return true, nil
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
@@ -451,7 +385,6 @@ local function newPlayer(self: any)
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
@@ -482,13 +415,11 @@ function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?
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
@@ -515,7 +446,6 @@ local function run(self: any, out: buffer?, n: number): number
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
@@ -528,7 +458,6 @@ function Decoder.read(self: any, n: number, out: buffer?): (buffer, number)
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)
@@ -539,7 +468,6 @@ function Decoder.seek(self: any, seconds: number)
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