ws-audio2: merge ws/audio2-tracker (MTM, 669, STM, ULT, OKT, MED, PTM, FAR, UMX; Tracker engine families)

This commit is contained in:
4DBug committed 2026-10-31 15:19:31 -05:00
commit 270eccab0f
43 files changed
+4907 -65

No files matched your search

+108
View File
@@ -950,6 +950,18 @@ local list: { Entry } = {
return require("@formats/subtitle/vtt")
end,
},
{
name = "669",
category = "music",
path = "music/669",
extensions = { "669" },
mime = { "audio/x-669" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 8, 8 } },
load = function()
return require("@formats/music/669")
end,
},
{
name = "ahx",
category = "music",
@@ -962,6 +974,18 @@ local list: { Entry } = {
return require("@formats/music/ahx")
end,
},
{
name = "far",
category = "music",
path = "music/far",
extensions = { "far" },
mime = { "audio/x-far" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 16, 16 } },
load = function()
return require("@formats/music/far")
end,
},
{
name = "hmp",
category = "music",
@@ -998,6 +1022,18 @@ local list: { Entry } = {
return require("@formats/music/it")
end,
},
{
name = "med",
category = "music",
path = "music/med",
extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" },
mime = { "audio/x-med" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 64 } },
load = function()
return require("@formats/music/med")
end,
},
{
name = "midi",
category = "music",
@@ -1022,6 +1058,18 @@ local list: { Entry } = {
return require("@formats/music/mod")
end,
},
{
name = "mtm",
category = "music",
path = "music/mtm",
extensions = { "mtm" },
mime = { "audio/x-mtm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/mtm")
end,
},
{
name = "mus",
category = "music",
@@ -1034,6 +1082,30 @@ local list: { Entry } = {
return require("@formats/music/mus")
end,
},
{
name = "okt",
category = "music",
path = "music/okt",
extensions = { "okt", "okta" },
mime = { "audio/x-okt" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 4, 8 } },
load = function()
return require("@formats/music/okt")
end,
},
{
name = "ptm",
category = "music",
path = "music/ptm",
extensions = { "ptm" },
mime = { "audio/x-ptm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/ptm")
end,
},
{
name = "s3m",
category = "music",
@@ -1058,6 +1130,42 @@ local list: { Entry } = {
return require("@formats/music/sf2")
end,
},
{
name = "stm",
category = "music",
path = "music/stm",
extensions = { "stm" },
mime = { "audio/x-stm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 4, 4 } },
load = function()
return require("@formats/music/stm")
end,
},
{
name = "ult",
category = "music",
path = "music/ult",
extensions = { "ult" },
mime = { "audio/x-ult" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/ult")
end,
},
{
name = "umx",
category = "music",
path = "music/umx",
extensions = { "umx" },
mime = { "audio/x-umx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
caps = { decode = true, encode = false, render = true, container = true },
load = function()
return require("@formats/music/umx")
end,
},
{
name = "xm",
category = "music",
+291
View File
@@ -0,0 +1,291 @@
--!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.
local Err = require("@formats/core/Err")
local Player = require("@formats/codecs/audio/Tracker/Player")
local Pcm = require("@formats/codecs/audio/Tracker/Pcm")
local Tables = require("@formats/codecs/audio/Tracker/Tables")
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,
["break"] = 3,
volslide = 4,
portadown = 5,
portaup = 6,
toneporta = 7,
vibrato = 8,
tremor = 9,
arpeggio = 10,
vibratovol = 11,
toneportavol = 12,
chanvol = 13,
chanvolslide = 14,
offset = 15,
panslide = 16,
retrig = 17,
tremolo = 18,
s3mex = 19,
tempo = 20,
finevibrato = 21,
globalvol = 22,
globalvolslide = 23,
panning8 = 24,
panbrello = 25,
noteslideup = EXT.NOTE_SLIDE_UP,
noteslidedown = EXT.NOTE_SLIDE_DOWN,
noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG,
noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG,
autoportaup = EXT.AUTO_PORTA_UP,
autoportadown = EXT.AUTO_PORTA_DOWN,
freqadjust = EXT.FREQ_ADJUST,
}
Load.IT = IT
-- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits
local WEIGHT: { [string]: number } = {}
for i, n in
{
"none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8",
"noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup",
"portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig",
"arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo",
"speed", "jump", "break",
}
do
WEIGHT[n] = i
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)
function Load.isGlobal(name: string?, param: number): boolean
if name == nil then
return false
end
if GLOBAL[name] then
return true
end
local x = param // 16
if name == "modex" then
return x == 0 or x == 6 or x == 0xE
elseif name == "s3mex" then
return x == 6 or x == 0xB or x == 0xE
end
return false
end
-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (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",
[12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide",
[20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor",
}
function Load.modCommand(cmd: number, param: number): (string?, number)
if cmd == 0 and param == 0 then
return nil, 0
elseif cmd == 0xF and param < 0x20 then
return "speed", param
end
local n = MODFX[cmd]
if n == "break" then
param = (param // 16) * 10 + param % 16
end
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)
function Load.itVolume(name: string?, param: number, force: boolean): number?
if name == "volume" then
return math.min(param, 64) + 1
elseif name == "volume8" then
if not force and param % 4 ~= 0 then
return nil
end
return (param + 3) // 4 + 1
elseif name == "portaup" or name == "portadown" then
if not force and (param % 4 ~= 0 or param >= 0xE0) then
return nil
end
return (if name == "portaup" then 115 else 105) + math.min(param // 4, 9) + 1
elseif name == "toneporta" then
if param >= 0xF0 then
return 193 + 9 + 1
end
for n = 0, 9 do
local v = Tables.IT_VOLPORTA[n + 1]
if (force and param <= v) or param == v then
return 193 + n + 1
end
end
return nil
elseif name == "vibrato" then
if force then
param = math.min(param % 16, 9)
elseif param % 16 > 9 or param >= 16 then
return nil
end
return 203 + param % 16 + 1
elseif name == "panning8" then
return 128 + (if param == 255 then 64 else param // 4) + 1
elseif name == "volslide" then
local x, y = param // 16, param % 16
if param == 0 then
return nil
elseif y == 0 then
return 85 + math.min(x, 9) + 1
elseif x == 0 then
return 95 + math.min(y, 9) + 1
elseif y == 0xF then
return 65 + math.min(x, 9) + 1
elseif x == 0xF then
return 75 + math.min(y, 9) + 1
end
return nil
elseif name == "s3mex" and param // 16 == 8 then
return 128 + (param % 16) * 4 + 2 + 1
end
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
end
if name == "modex" then
local x, y = param // 16, param % 16
if x == 1 then
return IT.portaup, 0xF0 + y
elseif x == 2 then
return IT.portadown, 0xF0 + y
elseif x == 9 then
return IT.retrig, y
elseif x == 0xA then
return IT.volslide, y * 16 + 0xF
elseif x == 0xB then
return IT.volslide, 0xF0 + y
end
local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x]
if s then
return IT.s3mex, s * 16 + y
end
return 0, 0
end
local code = IT[name]
if code == nil then
return 0, 0
end
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)
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)
end
for n = 0, 3 do
local v = Load.itVolume(e1, p1, n > 1)
if e1 == nil or v then
if v == nil and (e2 == "volume" or e2 == "volume8") then
-- the engine's IT family sets volumes in the volume column only
return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0
end
return v or 0, e2, p2, nil, 0
end
e1, p1, e2, p2 = e2, p2, e1, p1
end
if (WEIGHT[e1 :: string] or 0) > (WEIGHT[e2 :: string] or 0) then
e1, p1, e2, p2 = e2, p2, e1, p1
end
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).
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
return false
end
local fam = m.engine or m.format
local modLike = fam == "mod" or fam == "xm"
local nch = m.channels
local d = p.data
local guard = 0
while row >= 0 and row < p.rows and guard < 1024 do
guard += 1
local c0, c1 = 1, nch
if channel then
c0, c1 = channel, channel
end
for c = c0, c1 do
local o = (row * nch + c - 1) * 5
if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then
return true
end
end
for c = c0, c1 do
local o = (row * nch + c - 1) * 5
local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
if f == 0 and (not modLike or q == 0) then
buffer.writeu8(d, o + 3, fx)
buffer.writeu8(d, o + 4, param)
return true
end
end
if retry == "next" then
row += 1
elseif retry == "prev" then
row -= 1
else
return false
end
end
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
local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf))
local avail = math.max(0, limit - offset) // (nch * bps)
local n = math.max(0, math.min(math.floor(frames), avail))
budget.left -= n * nch * 4
if budget.left < 0 then
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
end
local data = Pcm.decode(buf, offset, n, spec)
if not data then
return nil, Err.new(Err.TRUNCATED, "sample data", offset)
end
s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch
return true, nil
end
-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99)
function Load.bcd(n: number): number
n = math.clamp(math.floor(n), 0, 99)
return (n // 10) * 16 + n % 10
end
return Load
+179 -43
View File
@@ -23,6 +23,20 @@ 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,
NOTE_SLIDE_UP_RETRIG = 0x42,
NOTE_SLIDE_DOWN_RETRIG = 0x43,
AUTO_PORTA_UP = 0x44,
AUTO_PORTA_DOWN = 0x45,
FREQ_ADJUST = 0x46,
TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param)
}
Player.EXT = EXT
local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions
-- ------------------------------------------------------------------------------------------------ state
@@ -171,12 +185,20 @@ local function newChannel(i: number, pan: number, vol: number): any
pitchEnvOn = true,
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
hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669)
slideCount = 0, -- note slides: ticks to the next step
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.format] or MOD
local fmt = FAMILY[m.engine or m.format] or MOD
local flags = m.flags
local ptPeriods = fmt == MOD or flags.periods == "amiga"
local st: any = {
m = m,
fmt = fmt,
@@ -189,8 +211,19 @@ function Player.new(m: any, sampleRate: number, opts: any): any
insMode = m.instrumentMode and #m.instruments > 0,
oldFx = m.flags.oldEffects or false,
compatG = m.flags.compatGxx or false,
fastSlides = m.flags.fastSlides or false,
amigaLimits = m.flags.amigaLimits 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
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,
autoTonePorta = flags.autoTonePorta or false,
autoReset = flags.autoReset or false,
st2Tempo = flags.st2Tempo or false,
oktSlides = flags.oktSlides or false,
ft2Pan = flags.panLaw == "ft2",
envHold = flags.envRowHold or false,
ord = 0,
row = 0,
tick = 0,
@@ -214,7 +247,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any
master = 1,
rows = 0,
ramp = 64,
amiga = if fmt == MOD then AMIGA_PAL else AMIGA,
amiga = if ptPeriods then AMIGA_PAL else AMIGA,
loopAllowed = opts and opts.loop or false,
}
for i = 1, m.channels do
@@ -240,6 +273,9 @@ end
-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at
-- volume 64 on one centred channel)
function Player.masterGain(m: any, fmt: number): number
if type(m.preamp) == "number" then
return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader
end
if fmt == IT or fmt == S3M then
return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5
end
@@ -335,10 +371,15 @@ local function notePeriod(st: any, note: number, smp: any, ft: number?): (number
end
end
local plin = (ref - note) * 64 - tr
if st.fmt == MOD then
if st.hz then
-- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5
return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base
end
if st.ptPeriods then
-- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded)
local ftp = (ft or smp.finetune or 0) / 16
return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base
local n = note + (if st.fmt == MOD or st.fmt == XM then smp.relativeNote or 0 else 0)
return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base
end
if st.linear then
return plin, base
@@ -350,6 +391,9 @@ local function arpPeriod(st: any, period: number, semis: number): number
if semis == 0 then
return period
end
if st.hz then
return period * 2 ^ (semis / 12)
end
if st.linear then
return period - semis * 64
end
@@ -357,7 +401,9 @@ local function arpPeriod(st: any, period: number, semis: number): number
end
local function clampPeriod(st: any, c: any)
if st.linear then
if st.hz then
c.period = clamp(c.period, 1, 1e6)
elseif st.linear then
c.period = clamp(c.period, -6000, 6000)
elseif st.amigaLimits then
c.period = clamp(c.period, 113 * 4, 856 * 4)
@@ -366,6 +412,17 @@ 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
local function slide(st: any, c: any, units: number)
if st.hz then
c.period -= units * st.hzScale
else
c.period += units
end
clampPeriod(st, c)
end
-- ------------------------------------------------------------------------------------------------ voices
local function allocVoice(st: any): any
local best, bestScore = nil, math.huge
@@ -674,6 +731,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb
keep = if c.voice.ins == ins then true else "release"
end
c.triggered = true
c.hzAdd = 0
c.tremorOn = true
c.retrigCount = 0
v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep)
@@ -758,6 +816,9 @@ local function tonePorta(st: any, c: any, speed: number)
if c.period == c.target then
return
end
if st.hz then
speed *= st.hzScale * st.hzTone
end
if c.period < c.target then
c.period = min(c.period + speed, c.target)
else
@@ -837,23 +898,21 @@ local function fxModXm(st: any, c: any, tick: number)
if xm and param > 0 then
c.mPortaUp = param
end
if tick > 0 then
c.period -= (if xm then c.mPortaUp else param) * 4
clampPeriod(st, c)
if tick > 0 or st.fastPortas then
slide(st, c, -(if xm then c.mPortaUp else param) * 4)
end
elseif fx == 2 then
if xm and param > 0 then
c.mPortaDn = param
end
if tick > 0 then
c.period += (if xm then c.mPortaDn else param) * 4
clampPeriod(st, c)
if tick > 0 or st.fastPortas then
slide(st, c, (if xm then c.mPortaDn else param) * 4)
end
elseif fx == 3 or fx == 5 then
if fx == 3 and param > 0 then
c.portaSpeed = param
end
if tick > 0 then
if tick > 0 or st.fastPortas then
tonePorta(st, c, c.portaSpeed * 4)
end
elseif fx == 4 or fx == 6 then
@@ -909,16 +968,14 @@ local function fxModXm(st: any, c: any, tick: number)
c.mFineUp = y
end
if tick == 0 then
c.period -= (if xm then c.mFineUp else y) * 4
clampPeriod(st, c)
slide(st, c, -(if xm then c.mFineUp else y) * 4)
end
elseif x == 2 then
if xm and y > 0 then
c.mFineDn = y
end
if tick == 0 then
c.period += (if xm then c.mFineDn else y) * 4
clampPeriod(st, c)
slide(st, c, (if xm then c.mFineDn else y) * 4)
end
elseif x == 4 then
c.vibWave = y % 8
@@ -1054,16 +1111,14 @@ local function fxModXm(st: any, c: any, tick: number)
c.mXFineUp = y
end
if tick == 0 then
c.period -= c.mXFineUp
clampPeriod(st, c)
slide(st, c, -c.mXFineUp)
end
elseif x == 2 then
if y > 0 then
c.mXFineDn = y
end
if tick == 0 then
c.period += c.mXFineDn
clampPeriod(st, c)
slide(st, c, c.mXFineDn)
end
end
end
@@ -1073,10 +1128,10 @@ local function fxModXm(st: any, c: any, tick: number)
if param > 0 then
c.mVolSlide = param
end
if tick > 0 then
if tick > 0 or st.fastSlides then
volSlideMod(c, c.mVolSlide)
end
elseif tick > 0 then
elseif tick > 0 or st.fastSlides then
volSlideMod(c, param)
end
end
@@ -1161,16 +1216,15 @@ end
local function portaS3m(st: any, c: any, p: number, tick: number, sign: number)
if p >= 0xF0 then
if tick == 0 then
c.period += sign * (p % 16) * 4
slide(st, c, sign * (p % 16) * 4)
end
elseif p >= 0xE0 then
if tick == 0 then
c.period += sign * (p % 16)
slide(st, c, sign * (p % 16))
end
elseif tick > 0 then
c.period += sign * p * 4
elseif tick > 0 or st.fastPortas then
slide(st, c, sign * p * 4)
end
clampPeriod(st, c)
end
local function fxS3mIt(st: any, c: any, tick: number)
@@ -1178,7 +1232,11 @@ local function fxS3mIt(st: any, c: any, tick: number)
local it = st.fmt == IT
if fx == 1 then -- A speed
if tick == 0 and param > 0 then
st.speed = param
if st.st2Tempo then
st.speed, st.tempo = Tables.st2Tempo(param)
else
st.speed = param
end
end
elseif fx == 2 then -- B jump
if tick == 0 then
@@ -1446,7 +1504,7 @@ local function fxS3mIt(st: any, c: any, tick: number)
c.portaSpeed = c.mEF
end
end
if tick > 0 then
if tick > 0 or st.fastPortas then
tonePorta(st, c, c.portaSpeed * 4)
end
end
@@ -1514,8 +1572,7 @@ local function volColIt(st: any, c: any, tick: number)
c.mEF = p
end
if tick > 0 then
c.period += c.mEF * 4
clampPeriod(st, c)
slide(st, c, c.mEF * 4)
end
elseif v <= 124 then
local p = (v - 115) * 4
@@ -1523,8 +1580,7 @@ local function volColIt(st: any, c: any, tick: number)
c.mEF = p
end
if tick > 0 then
c.period -= c.mEF * 4
clampPeriod(st, c)
slide(st, c, -c.mEF * 4)
end
elseif v >= 193 and v <= 202 then
local p = Tables.IT_VOLPORTA[v - 192] or 0
@@ -1550,6 +1606,66 @@ 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
-- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides):
-- 1x = every tick, 5x = once on the first tick
if tick == 0 then
if param // 16 > 0 then
c.mNoteSlide = (param // 16) * 16 + c.mNoteSlide % 16
end
if param % 16 > 0 then
c.mNoteSlide = (c.mNoteSlide // 16) * 16 + param % 16
end
c.slideCount = c.mNoteSlide // 16
end
local p = c.mNoteSlide
local go
if st.oktSlides then
go = p // 16 == 1 or tick == 0
else
go = false
if tick > 0 then
c.slideCount -= 1
go = c.slideCount == 0
end
end
if go and c.smp and c.realNote > 0 then
c.slideCount = p // 16
local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG
c.realNote = clamp(c.realNote + (if up then p % 16 else -(p % 16)), 1, 120)
c.period = notePeriod(st, c.realNote, c.smp, c.finetune)
if fx >= EXT.NOTE_SLIDE_UP_RETRIG then
retrigVoice(st, c)
end
end
elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then
if tick == 0 then
c.autoPorta = (if fx == EXT.AUTO_PORTA_UP then -param else param) * 4
end
elseif fx == EXT.FREQ_ADJUST then
if tick == 0 then
c.hzAdd = param * 80
end
elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then
if tick == 0 then
st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param
end
end
-- auto slides: every tick (fast portamentos) or every tick but the first
if tick > 0 or st.fastPortas then
if c.autoPorta ~= 0 then
slide(st, c, c.autoPorta)
end
if c.autoTone and not c.tonePortaRow then
tonePorta(st, c, c.portaSpeed * 4)
end
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
@@ -1573,6 +1689,9 @@ end
local function runEffects(st: any, c: any, tick: number)
c.vibDelta, c.arp = 0, 0
if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then
fxExt(st, c, tick)
end
if st.fmt == MOD or st.fmt == XM then
fxModXm(st, c, tick)
if st.fmt == XM then
@@ -1621,6 +1740,15 @@ local function processRow(st: any)
end
c.fx, c.param, c.vcmd = fx, param, vcmd
c.cutTick, c.keyOffTick = -1, -1
if st.autoReset and fx ~= 0 and fx ~= 255 then
-- 669: any effect stops the auto slides
c.autoPorta, c.autoTone = 0, false
end
local tp = isPorta(st, fx, vcmd)
c.tonePortaRow = tp
if tp and st.autoTonePorta then
c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0)
end
c.triggered = false
local delay = noteDelayOf(st, fx, param)
c.finetune = finetuneOf(st, fx, param)
@@ -1684,10 +1812,11 @@ local function updateVoice(st: any, v: any)
local envVol, envPan, envPitch = 64, 0, 0
local filterEnv = nil
if ins then
local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick
local e = ins.volEnv
if e and e.enabled and v.volEnvOn then
local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it)
envVol, v.volEnvPos = val, np
envVol, v.volEnvPos = val, if hold then v.volEnvPos else np
if ended and it then
if val <= 0 then
v.active = false
@@ -1699,12 +1828,12 @@ local function updateVoice(st: any, v: any)
e = ins.panEnv
if e and e.enabled and v.panEnvOn then
local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it)
envPan, v.panEnvPos = val, np
envPan, v.panEnvPos = val, if hold then v.panEnvPos else np
end
e = ins.pitchEnv
if e and e.enabled and v.pitchEnvOn then
local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it)
v.pitchEnvPos = np
v.pitchEnvPos = if hold then v.pitchEnvPos else np
if e.filter then
filterEnv = val
else
@@ -1750,7 +1879,9 @@ local function updateVoice(st: any, v: any)
-- frequency
local P = v.periodOut + avDelta
local freq
if st.linear then
if st.hz then
freq = max(0, P + (v.hzAdd or 0))
elseif st.linear then
freq = v.base * 2 ^ (-P / 768)
else
freq = if P > 0 then st.amiga / P else 0
@@ -1762,9 +1893,9 @@ local function updateVoice(st: any, v: any)
-- volume
local smp = v.smp
local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128
if it then
vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1)
end
-- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader,
-- sets them)
vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1)
if v.tremorMute then
vol = 0
end
@@ -1782,6 +1913,10 @@ local function updateVoice(st: any, v: any)
local g = vol * st.master
if v.surround then
v.tl, v.tr = g * 0.5, -g * 0.5
elseif st.ft2Pan then
-- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255
local p = min(pan, 255)
v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256)
else
v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256
end
@@ -1853,8 +1988,9 @@ function Player.tick(st: any): number
local c = st.chans[i]
local v = c.voice
if v and v.active and v.chan == i and not v.bg then
local P = arpPeriod(st, c.period, c.arp) + c.vibDelta
local P = arpPeriod(st, c.period, c.arp) + (if st.hz then -c.vibDelta * st.hzScale else c.vibDelta)
v.period, v.periodOut, v.base = c.period, P, c.base
v.hzAdd = c.hzAdd
v.vol = clamp(c.vol + c.tremDelta, 0, 64)
if c.muted then
v.vol = 0
@@ -110,4 +110,17 @@ 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)
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
local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates)
local spt = if d > 0 then 23863 // d else -(23863 // -d)
if spt <= 0 then
spt += 65536
end
return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000
end
return Tables
+48 -12
View File
@@ -1,6 +1,7 @@
--!strict
-- codecs/audio/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
-- 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.
--
@@ -9,14 +10,25 @@
-- 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
-- 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), amigaLimits (MOD) }
-- 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
@@ -25,7 +37,11 @@
-- 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.
-- (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),
@@ -85,12 +101,29 @@ export type RenderOptions = {
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) -> an empty Module (no patterns / samples) with the format's defaults
function Tracker.newModule(format: string, channels: number): any
-- 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 = {
kind = "music",
format = format,
engine = engine,
title = "",
channels = channels,
speed = 6,
@@ -99,8 +132,8 @@ function Tracker.newModule(format: string, channels: number): any
mixVolume = 48,
order = {},
restart = 0,
linear = format == "xm" or format == "it",
instrumentMode = format == "xm" or format == "it",
linear = fam == "xm" or fam == "it",
instrumentMode = fam == "xm" or fam == "it",
flags = {},
channelPan = {},
channelVolume = {},
@@ -113,7 +146,7 @@ function Tracker.newModule(format: string, channels: number): any
}
for i = 1, channels do
m.channelVolume[i] = 64
if format == "mod" then
if fam == "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
@@ -285,8 +318,11 @@ 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))
if not Tracker.family(m) then
return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format))
end
if m.preamp ~= nil and not num(m.preamp, 0, 256) then
m.preamp = nil
end
if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then
return nil, Err.new(Err.ARG, "bad channel count")
+10 -1
View File
@@ -276,6 +276,9 @@ end
-- the embedded parts) when called directly.
-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
--
-- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded
-- as music (sniffed, or as the given format).
--
-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets
-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 /
-- FLAC / AC-3 as they are), opened through F.open with that format.
@@ -299,7 +302,7 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?)
end
local function withHooks(o: Options): Options
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil then
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then
return o
end
local c = table.clone(o)
@@ -319,6 +322,12 @@ local function withHooks(o: Options): Options
return F.save(img, nil, { format = format, category = "image" })
end
end
if c.decodeModule == nil then
-- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format
c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?)
return F.load(b, { category = "music", format = format })
end
end
return c
end
+209
View File
@@ -0,0 +1,209 @@
--!strict
-- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and
-- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the
-- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides
-- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until
-- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F),
-- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms).
-- Not supported: UNIS 669's "super fast" speed 0, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Six69 = {
name = "669",
category = "music",
extensions = { "669" },
mime = { "audio/x-669" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 8, 8 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local IT = Load.IT
-- the 669 effects (high nibble of the effect byte) by name
local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" }
-- ------------------------------------------------------------------------------------------------ sniff
-- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too)
local function validHeader(r: Bytes.Reader): boolean
if r:size() < 497 then
return false
end
local magic = r:peek(2)
if magic ~= "if" and magic ~= "JN" then
return false
end
local nsmp, npat, restart = r:peekU8(110), r:peekU8(111), r:peekU8(112)
if nsmp > 64 or restart >= 128 or npat > 128 then
return false
end
local bad = 0
for i = 2, 109 do
local c = r:peekU8(i)
if c > 0 and c <= 31 then
bad += 1
if bad > 40 then
return false
end
end
end
for i = 0, 127 do
local o, t, b = r:peekU8(113 + i), r:peekU8(241 + i), r:peekU8(369 + i)
if (o >= 128 and o < 0xFE) or (o < 128 and t == 0) or t > 15 or b >= 64 then
return false
end
end
return true
end
function Six69.sniff(r: Bytes.Reader): number
return if validHeader(r) then 0.6 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if not validHeader(r) then
return nil, Err.new(if r:size() < 497 then Err.TRUNCATED else Err.CORRUPT, "not a 669 module")
end
local extended = r:peek(2) == "JN"
r:skip(2)
local message = r:string(108)
local nsmp, npat, restart = r:u8(), r:u8(), r:u8()
local orders, tempos, breaks = {}, {}, {}
for i = 1, 128 do
orders[i] = r:u8()
end
for i = 1, 128 do
tempos[i] = r:u8()
end
for i = 1, 128 do
breaks[i] = r:u8()
end
if not r:need(nsmp * 25 + npat * 1536) then
return nil, r.err
end
local m = Tracker.newModule("669", 8, "s3m")
m.title = (string.gsub(string.sub(message, 1, 36), "[%z ]+$", ""))
m.meta.message = message
m.speed, m.tempo = 4, 78
m.linear = false
m.instrumentMode = false
m.flags.periods, m.flags.hzSlide, m.flags.hzTonePorta = "hz", 20, 0.5
m.flags.fastPortas, m.flags.autoTonePorta, m.flags.autoReset = true, true, true
for i = 1, 8 do
m.channelPan[i] = if i % 2 == 0 then 0xD0 else 0x30
end
local lengths: { number } = {}
for i = 1, nsmp do
local s = Tracker.newSample(r:fixed(13))
local len, ls, le = r:u32le(), r:u32le(), r:u32le()
if len >= 0x4000000 then
return nil, Err.new(Err.CORRUPT, "sample " .. i .. " too long")
end
s.c5speed = 8363
if not (le > len and ls == 0) and le ~= 0 then
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1
end
lengths[i] = len
m.samples[i] = s
end
for i = 1, 128 do
m.order[i] = orders[i]
end
while #m.order > 0 and m.order[#m.order] == 255 do
table.remove(m.order)
end
if orders[restart + 1] < npat then
m.restart = restart
end
-- patterns: 64 rows x 8 channels x 3 bytes (note / instrument, instrument / volume, effect / parameter)
local buf = r.buf
for p = 0, npat - 1 do
local pat = Tracker.newPattern(64, 8)
m.patterns[p + 1] = pat
local d = pat.data
local effect = table.create(8, 0xFF) -- the last effect per channel (balance slides repeat)
for row = 0, 63 do
for ch = 0, 7 do
local o = r.pos + (row * 8 + ch) * 3
local ni, iv, ep = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2)
local q = (row * 8 + ch) * 5
local hasNote = ni < 0xFE
if hasNote then
buffer.writeu8(d, q, ni // 4 + 37)
buffer.writeu8(d, q + 1, (ni % 4) * 16 + iv // 16 + 1)
effect[ch + 1] = 0xFF
end
if ni <= 0xFE then
buffer.writeu8(d, q + 2, ((iv % 16) * 64 + 8) // 15 + 1)
end
if ep ~= 0xFF then
effect[ch + 1] = ep
end
local e = effect[ch + 1]
if e ~= 0xFF then
local cmd, param = e // 16, e % 16
local name = EFFECTS[cmd + 1]
if cmd == 4 then
param = param * 17 -- vibrato: speed = depth
elseif cmd == 6 then
param = if param == 0 then 0x4F elseif param == 1 then 0xF4 else -1
elseif cmd == 7 and not (hasNote and extended) then
name = nil
end
if name ~= "panslide" then
effect[ch + 1] = 0xFF
end
if name and param >= 0 then
buffer.writeu8(d, q + 3, IT[name])
buffer.writeu8(d, q + 4, param)
end
end
end
end
r:skip(1536)
if breaks[p + 1] < 63 then
Load.writeEffect(m, p, breaks[p + 1], IT["break"], 0, "next")
end
Load.writeEffect(m, p, 0, IT.speed, tempos[p + 1], "next")
end
-- sample data: unsigned 8-bit
local pos = r.pos
for i = 1, nsmp do
local s = m.samples[i]
local ok, err = Load.readSample(buf, pos, lengths[i], { bits = 8, signed = false, limit = r.limit }, s, budget)
if not ok then
return nil, err
end
pos += lengths[i]
end
m.meta.source = { format = "669", tracker = if extended then "UNIS 669" else "Composer 669" }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Six69.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Six69
+232
View File
@@ -0,0 +1,232 @@
--!strict
-- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any
-- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads
-- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods
-- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides,
-- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed
-- tempo OpenMPT uses (80 BPM in tracker terms).
-- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Far = {
name = "far",
category = "music",
extensions = { "far" },
mime = { "audio/x-far" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 16, 16 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local IT = Load.IT
-- ------------------------------------------------------------------------------------------------ sniff
function Far.sniff(r: Bytes.Reader): number
if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and r:peekU8(47) + r:peekU8(48) * 256 >= 98 then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table)
local function effect(e: number): (number, number, number)
local cmd, p = e // 16, e % 16
if cmd == 1 then
return IT.portaup, 0xF0 + p, 0
elseif cmd == 2 then
return IT.portadown, 0xF0 + p, 0
elseif cmd == 3 then
return IT.toneporta, if p ~= 0 then 60 // p else 0, 0
elseif cmd == 4 then
return IT.retrig, 6 // (1 + p) + 1, 0
elseif cmd == 5 or cmd == 9 then
return IT.vibrato, p, 0
elseif cmd == 6 then
return IT.vibrato, p * 8, 0
elseif cmd == 7 then
return IT.volslide, p * 8, 0
elseif cmd == 8 then
return IT.volslide, p, 0
elseif cmd == 0xA then
return 0, 0, p * 4 + 4 + 1 -- volume portamento: a set volume
elseif cmd == 0xB then
return IT.s3mex, 0x80 + p, 0
elseif cmd == 0xF then
return IT.speed, p, 0
end
return 0, 0, 0
end
function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if Far.sniff(r) == 0 then
return nil, Err.new(if r:size() < 98 then Err.TRUNCATED else Err.CORRUPT, "not a Farandole module")
end
r:skip(4)
local title = r:fixed(40)
r:skip(3)
local headerLength, version = r:u16le(), r:u8()
local onOff, pans = {}, {}
for i = 1, 16 do
onOff[i] = r:u8()
end
r:skip(9)
local speed = r:u8()
for i = 1, 16 do
pans[i] = r:u8()
end
r:skip(4)
local msgLen = r:u16le()
local message = r:string(msgLen)
local orders = {}
for i = 1, 256 do
orders[i] = r:u8()
end
local _npat, nord, restart = r:u8(), r:u8(), r:u8()
local sizes = {}
for i = 1, 256 do
sizes[i] = r:u16le()
end
if r.err then
return nil, r.err
end
local m = Tracker.newModule("far", 16, "s3m")
m.title = title
m.meta.message = message
m.speed, m.tempo = if speed > 0 then speed else 4, 80
m.mixVolume = 32 -- OpenMPT's pre-amp for FAR
m.linear = false
m.instrumentMode = false
m.flags.periods, m.flags.hzSlide = "hz", 36318 / 1024
m.flags.autoTonePorta = true
for i = 1, 16 do
m.channelMute[i] = onOff[i] == 0
m.channelPan[i] = (pans[i] % 16) * 16 + 8
end
for i = 1, nord do
m.order[i] = orders[i]
end
while #m.order > 0 and m.order[#m.order] == 255 do
table.remove(m.order)
end
m.restart = restart
-- patterns: (size - 2) / 64 rows of 16 channels x (note, instrument, volume, effect), after a break row byte
if not r:seek(headerLength) then
return nil, r.err
end
local last = -1
for p = 0, 255 do
if sizes[p + 1] > 0 then
last = p
end
end
for p = 0, last do
local size = sizes[p + 1]
local rows = math.clamp((size - 2) // 64, 1, 1024)
local pat = Tracker.newPattern(if size > 0 then rows else 64, 16)
m.patterns[p + 1] = pat
if size > 0 then
local pr = r:slice(size)
if r.err then
return nil, r.err
end
local br = pr:u8()
pr:skip(1)
local d = pat.data
for row = 0, rows - 1 do
for ch = 0, 15 do
local note, ins, vol, e = pr:u8(), pr:u8(), pr:u8(), pr:u8()
if pr.err then
break
end
local q = (row * 16 + ch) * 5
if note > 0 and note <= 72 then
buffer.writeu8(d, q, note + 36)
buffer.writeu8(d, q + 1, ins + 1)
end
if vol > 0 and vol <= 16 then
buffer.writeu8(d, q + 2, (vol - 1) * 64 // 15 + 1)
end
local fx, param, setVol = effect(e)
if setVol > 0 then
buffer.writeu8(d, q + 2, setVol)
end
buffer.writeu8(d, q + 3, fx)
buffer.writeu8(d, q + 4, param)
end
end
if br > 0 and br < rows - 2 then
Load.writeEffect(m, p, br + 1, IT["break"], 0, "next")
end
end
end
-- samples: a 64-bit map of the stored ones, each a 48-byte header + signed 8 / 16-bit data
local map = {}
for i = 1, 8 do
map[i] = r:u8()
end
r.err = nil
for i = 0, 63 do
if bit32.band(map[i // 8 + 1] or 0, bit32.lshift(1, i % 8)) ~= 0 then
local h = r:slice(48)
if r.err then
break
end
local s = Tracker.newSample(h:fixed(32))
local len = h:u32le()
h:skip(1)
local vol = h:u8()
local ls, le = h:u32le(), h:u32le()
local typ, loop = h:u8(), h:u8()
local bits = if typ % 2 == 1 then 16 else 8
local frames = if bits == 16 then len // 2 else len
if bits == 16 then
ls, le = ls // 2, le // 2
end
s.c5speed = 8363 * 2
s.volume = math.min(vol * 4, 64)
local ok, err = Load.readSample(r.buf, r.pos, frames, { bits = bits, signed = true, limit = r.limit }, s, budget)
if not ok then
return nil, err
end
r:skip(math.min(len, r:remaining()))
if bit32.band(loop, 8) ~= 0 and le > ls then
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1
end
for k = #m.samples + 1, i do
m.samples[k] = Tracker.newSample()
end
m.samples[i + 1] = s
end
end
m.meta.source = { format = "far", version = version }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Far.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Far
+661
View File
@@ -0,0 +1,661 @@
--!strict
-- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks,
-- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song
-- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL
-- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks
-- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop
-- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave
-- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops,
-- default pitch, volume).
-- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and
-- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Med = {
name = "med",
category = "music",
extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" },
mime = { "audio/x-med" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 64 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
-- IFF multi-octave samples: the sample (0 = the lowest octave stored first... as OpenMPT orders them) and the
-- transpose used per octave of the keyboard, by the number of octaves stored (2..7)
local OCT_SAMPLE = {
{ 1, 1, 0, 0, 0, 0, 0, 0 },
{ 2, 2, 1, 1, 0, 0, 0, 0 },
{ 3, 3, 2, 2, 1, 0, 0, 0 },
{ 4, 3, 2, 1, 1, 0, 0, 0 },
{ 5, 4, 3, 2, 1, 0, 0, 0 },
{ 6, 5, 4, 3, 2, 1, 0, 0 },
}
local OCT_TRANSPOSE = {
{ 0, 0, -12, -12, -24, -36, -48, -60 },
{ 0, 0, -12, -12, -24, -36, -48, -60 },
{ 0, 0, -12, -12, -24, -36, -48, -60 },
{ 12, 0, -12, -24, -24, -36, -48, -60 },
{ 12, 0, -12, -24, -36, -48, -48, -60 },
{ 12, 0, -12, -24, -36, -48, -60, -72 },
}
local SAMPLES_PER_TYPE = { [0] = 1, 5, 3, 2, 4, 6, 7 }
local TEMPO_8CH = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 }
-- ------------------------------------------------------------------------------------------------ sniff
local function validHeader(r: Bytes.Reader): boolean
if r:size() < 52 or r:peek(3) ~= "MMD" then
return false
end
local v = r:peekU8(3)
if v < 0x30 or v > 0x33 then
return false
end
local h = r:sub(8, 44)
local songOff = h:u32be()
h:skip(4)
local blockOff = h:u32be()
h:skip(4)
local smpOff = h:u32be()
return songOff >= 52 and songOff + 63 * 8 + 284 <= r:size() and blockOff >= 52 and (smpOff == 0 or smpOff >= 52)
end
function Med.sniff(r: Bytes.Reader): number
return if validHeader(r) then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean }
-- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes)
local function tempoToBpm(tempo: number, ctx: Ctx): number
if ctx.bpm and not ctx.is8Ch then
return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4
end
if ctx.is8Ch and tempo > 0 then
return TEMPO_8CH[math.min(tempo, 10)]
elseif not ctx.softMix and tempo > 0 and tempo <= 10 then
return 6 * 1773447 / 14500 / tempo -- SoundTracker-compatible tempo
elseif ctx.softMix and tempo < 8 then
return 157.86
end
return tempo / 0.264
end
-- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect)
local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean)
local lo = math.min(p, 15)
if cmd == 1 or cmd == 2 then
return if p > 0 then cmd else 0, p, false
elseif cmd == 4 then
return 4, p - p % 16 + math.min((p % 16) * 2, 15), false -- twice as deep as ProTracker's
elseif cmd == 5 then
return if p > 0 then 5 else 3, p, false
elseif cmd == 6 then
return if p > 0 then 6 else 4, p, false
elseif cmd == 8 or cmd == 0xE or cmd == 0x10 or cmd == 0x1C or cmd == 0x20 or cmd == 0x29 then
return 0, 0, false -- hold / decay (instrument data), synth jump, MIDI, reverse, relative offset
elseif cmd == 9 then
return if p > 0 and p <= 0x20 then 0xF else 0, math.min(p, 0x1F), false
elseif cmd == 0xC then
if not ctx.volHex and p < 0x99 then
return 0xC, (p // 16) * 10 + p % 16, false
elseif ctx.volHex and not ctx.vol7bit then
return 0xC, math.min(p % 128, 64), false
elseif ctx.volHex then
return 0xC, (p % 128 + 1) // 2, false
end
return 0, 0, false
elseif cmd == 0xD then
return if p > 0 then 0xA else 0, p, false
elseif cmd == 0xF then
if p == 0 then
return 0xD, 0, false
elseif p <= 0xF0 then
local bpm = if p < 3 then 0x70 else math.floor(tempoToBpm(p, ctx) + 0.5)
if bpm > 255 then
local ext = Tracker.EXT.TEMPO_256 + math.min(bpm // 256, 3) - 1 -- tempos past 255 (EXT 0x47..0x49)
return ext, math.min(bpm - (ext - Tracker.EXT.TEMPO_256 + 1) * 256, 255), false
end
return 0xF, math.max(bpm, 0x20), false
elseif p == 0xF1 then
return 0xE, 0x93, false
elseif p == 0xF2 then
return 0xE, 0xD3, false
elseif p == 0xF3 then
return 0xE, 0x92, false
elseif p == 0xFF then
return 0, 0, true
end
return 0, 0, false
elseif cmd == 0x11 then
return 0xE, 0x10 + lo, false
elseif cmd == 0x12 then
return 0xE, 0x20 + lo, false
elseif cmd == 0x14 then
return 4, p, false -- ProTracker depth, faster
elseif cmd == 0x15 then
return 0xE, 0x50 + p % 16, false
elseif cmd == 0x16 then
return 0xE, 0x60 + lo, false
elseif cmd == 0x18 then
return 0xE, 0xC0 + lo, false
elseif cmd == 0x19 then
return 9, p, false
elseif cmd == 0x1A then
return 0xE, 0xA0 + lo, false
elseif cmd == 0x1B then
return 0xE, 0xB0 + lo, false
elseif cmd == 0x1D then
return 0xD, Load.bcd(p), false -- pattern break, the row in hex
elseif cmd == 0x1E then
return 0xE, 0xE0 + lo, false
elseif cmd == 0x1F then
if p >= 16 then
return 0xE, 0xD0 + p // 16, false
elseif p > 0 then
return 0xE, 0x90 + p, false
end
return 0, 0, false
elseif cmd == 0x2E then
if p <= 0x10 or p >= 0xF0 then
return 8, math.clamp((bit32.bxor(p, 0x80) - 0x70) * 8, 0, 255), false
end
return 0, 0, false
elseif cmd < 0x10 and (cmd > 0 or p > 0) then
return cmd, p, false -- the remaining ProTracker effects as they are (0, 3, 7, 8, A, B)
end
return 0, 0, false
end
-- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping)
local function wrapNote(note: number, vol7bit: boolean): number
local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up)
if n > 132 and not vol7bit then
n -= 108
elseif n > 120 then
n -= (n - 109) - (n - 109) % 12
end
return if n >= 13 then n - 12 else 0
end
-- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding
local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean)
local br = r:sub(off)
local ntracks, nrows, info
if version < 1 then
ntracks, nrows, info = br:u8(), br:u8() + 1, 0
else
ntracks, nrows, info = br:u16be(), br:u16be() + 1, br:u32be()
end
if br.err or nrows > 1024 then
return nil, false
end
local cmdExt: Bytes.Reader? = nil
if version >= 1 and info > 0 then
local ir = r:sub(info, 36)
ir:skip(16)
local ext = ir:u32be()
if not ir.err and ext > 0 then
local p = r:sub(ext, 4):u32be()
if p > 0 then
cmdExt = r:sub(p)
end
end
end
local lctx = table.clone(ctx)
lctx.vol7bit = cmdExt ~= nil
local pat = Tracker.newPattern(nrows, nch)
local d = pat.data
local high = false
local used = math.min(ntracks, nch)
for row = 0, nrows - 1 do
for ch = 0, ntracks - 1 do
local note, ins, cmd, param, cut = 0, 0, 0, 0, false
if version < 1 then
local ni, ic, p = br:u8(), br:u8(), br:u8()
if ni % 64 > 0 then
note = ni % 64 + lctx.transpose
end
ins = ic // 16 + bit32.rshift(bit32.band(ni, 0x80), 3) + bit32.rshift(bit32.band(ni, 0x40), 1)
cmd, param = ic % 16, p
else
local nv, iv, c, p = br:u8(), br:u8(), br:u8(), br:u8()
if nv % 128 > 0 then
note = nv % 128 + lctx.transpose
elseif nv == 0x80 then
cut = true
end
ins, cmd, param = iv % 64, c, p
end
if br.err then
return pat, high
end
if ch < used then
local q = (row * nch + ch) * 5
if note >= 61 + 24 - 12 then
high = true
end
local n = wrapNote(note, lctx.vol7bit)
if n > 0 then
buffer.writeu8(d, q, n)
elseif cut then
buffer.writeu8(d, q, 254)
end
buffer.writeu8(d, q + 1, ins)
if cmd ~= 0 or param ~= 0 then
local fx, fp, noteCut = effect(cmd, param, lctx)
if noteCut and n == 0 then
buffer.writeu8(d, q, 254)
end
buffer.writeu8(d, q + 3, fx)
buffer.writeu8(d, q + 4, fp)
end
end
end
end
return pat, high
end
function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if not validHeader(r) then
return nil, Err.new(if r:size() < 52 then Err.TRUNCATED else Err.CORRUPT, "not a MED module")
end
local version = r:peekU8(3) - 0x30
local h = r:sub(8, 44)
local songOff = h:u32be()
h:skip(4)
local blockOff = h:u32be()
h:skip(4)
local smpOff = h:u32be()
h:skip(4)
local expOff = h:u32be()
-- the song: 63 sample headers, then the song header
local sh = r:sub(songOff, 63 * 8)
local song = r:sub(songOff + 63 * 8, 284)
local numBlocks, songLength = song:u16be(), song:u16be()
local seq = song:sub(4, 256)
song:skip(256)
local defTempo, playTranspose, flags, flags2, tempo2 = song:u16be(), song:i8(), song:u8(), song:u8(), song:u8()
local trackVol = {}
for i = 1, 16 do
trackVol[i] = song:u8()
end
local masterVol, numSamples = song:u8(), song:u8()
if song.err or numSamples > 63 or numBlocks > 0x7FFF then
return nil, Err.new(Err.CORRUPT, "bad song header")
end
if numSamples > 0 and smpOff == 0 then
return nil, Err.new(Err.CORRUPT, "no sample table")
end
-- channels: the widest block (at least 4)
local nch = 4
local blockPtr: { number } = {}
for b = 0, numBlocks - 1 do
local p = r:sub(blockOff + b * 4, 4):u32be()
blockPtr[b + 1] = p
if p > 0 and p < r:size() then
local w = if version < 1 then r:peekU8(p) else r:peekU8(p) * 256 + r:peekU8(p + 1)
nch = math.max(nch, w)
end
end
if nch > 64 then
return nil, Err.new(Err.UNSUPPORTED, nch .. " tracks")
end
local m = Tracker.newModule("med", nch, "xm")
m.linear = false
m.instrumentMode = false
m.flags.periods, m.flags.envRowHold = "amiga", true
local stSlides = bit32.band(flags, 0x20) ~= 0
m.flags.fastSlides, m.flags.fastPortas = not stSlides, not stSlides
local hardwareMix = version < 2 or bit32.band(flags2, 0x80) == 0
m.flags.amigaLimits = hardwareMix
-- the expansion data: instrument extras and names, the song name
local ext = { instrExt = 0, instrExtN = 0, instrExtSize = 0, infoOff = 0, infoN = 0, infoSize = 0, nameOff = 0, nameLen = 0, annoOff = 0, annoLen = 0 }
if expOff > 0 then
local e = r:sub(expOff, 80)
e:skip(4)
ext.instrExt, ext.instrExtN, ext.instrExtSize = e:u32be(), e:u16be(), e:u16be()
ext.annoOff, ext.annoLen = e:u32be(), e:u32be()
ext.infoOff, ext.infoN, ext.infoSize = e:u32be(), e:u16be(), e:u16be()
e:skip(16)
ext.nameOff, ext.nameLen = e:u32be(), e:u32be()
if e.err then
ext.instrExt, ext.infoOff, ext.nameOff, ext.annoOff = 0, 0, 0, 0
end
end
if ext.nameOff > 0 and ext.nameLen > 0 then
m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256))
end
-- instruments and samples
local needInstruments = false
local instruments, samples = {}, {}
local unsupported = {}
for ins = 1, numSamples do
local smpHead = sh:sub((ins - 1) * 8, 8)
local loopStart, loopLen = smpHead:u16be() * 2, smpHead:u16be() * 2
local midiCh, _midiPreset, volume, transpose = smpHead:u8(), smpHead:u8(), smpHead:u8(), smpHead:i8()
local x = { hold = 0, decay = 0, finetune = 0, pitch = 0, flags = 0, loopStart = 0, loopLen = 0, volume = 0 }
local xsize = 0
if ext.instrExt > 0 and ins <= ext.instrExtN then
xsize = ext.instrExtSize
local xr = r:sub(ext.instrExt + (ins - 1) * xsize, xsize)
x.hold, x.decay = xr:u8(), xr:u8()
xr:skip(1)
x.finetune = xr:i8()
x.pitch, x.flags = xr:u8(), xr:u8()
xr:skip(4)
x.loopStart, x.loopLen = xr:u32be(), xr:u32be()
x.volume = xr:u8()
end
local name = ""
if ext.infoOff > 0 and ins <= ext.infoN then
name = r:sub(ext.infoOff + (ins - 1) * ext.infoSize, math.min(ext.infoSize, 40)):fixed(math.min(ext.infoSize, 40))
end
local instr = Tracker.newInstrument(name)
instruments[ins] = instr
local iptr = if smpOff > 0 then r:sub(smpOff + (ins - 1) * 4, 4):u32be() else 0
local length, typ = 0, 0
if iptr > 0 then
local ih = r:sub(iptr, 6)
length, typ = ih:u32be(), ih:i16be()
if ih.err then
length, typ = 0, 0
end
end
local isSynth = typ < 0
local masked = bit32.band(typ % 65536, 0x0F)
local count = if not isSynth then (SAMPLES_PER_TYPE[masked] or 1) else 1
if isSynth then
table.insert(unsupported, "synth / hybrid instrument " .. ins)
needInstruments = needInstruments or typ == -1 or typ == -2
end
if midiCh > 0 and midiCh <= 16 then
needInstruments = true
table.insert(unsupported, "MIDI instrument " .. ins)
end
local first = #samples + 1
-- keymap: one sample per note, multi-octave samples spread over the octaves
for n = 1, 120 do
instr.sampleMap[n] = first
end
if count > 1 then
needInstruments = true
for n = 1, 120 do
local note = n + 11 + transpose -- OpenMPT's keyboard index
if note < 0 then
note = -note % 12
end
local oct = math.clamp(note // 12 - 4, 0, 7)
instr.sampleMap[n] = first + OCT_SAMPLE[count - 1][oct + 1]
instr.noteMap[n] = math.clamp(1 + note + OCT_TRANSPOSE[count - 1][oct + 1] - 12, 1, 120)
end
transpose = 0
elseif masked == 7 then
needInstruments = true -- two extra-low octaves
for n = 1, 120 do
instr.noteMap[n] = math.clamp(n - 24, 1, 120)
end
end
if midiCh == 0 then
-- notes past the mixer's range fold down (by octaves)
local top = 61 + (if hardwareMix then 24 else 36)
for n = 1, 120 do
local real = instr.noteMap[n] + 12 + transpose
if real >= top then
instr.noteMap[n] = math.max(1, instr.noteMap[n] - ((real - top + 12) - (real - top + 12) % 12))
end
end
end
-- sample data
local list = {}
for i = 0, count - 1 do
local s = Tracker.newSample(name)
s.volume = math.min(volume, 64)
s.relativeNote = transpose
list[i + 1] = s
samples[first + i] = s
end
local hasLoop = loopLen > 2
if not isSynth and iptr > 0 and length > 0 then
local bits = if bit32.band(typ, 0x10) ~= 0 then 16 else 8
local stereo = bit32.band(typ, 0x20) ~= 0
local nchs = if stereo then 2 else 1
local bytes = length * nchs
local frames = length // (bits // 8)
if count > 1 then
frames //= (2 ^ count - 1)
end
local pos = r.base + iptr + 6
local ls, le = loopStart, loopStart + loopLen
for i = 1, count do
local s = list[i]
local spec = { bits = bits, signed = true, bigEndian = true, channels = nchs, planar = stereo, delta = bit32.band(typ, 0x40) ~= 0, limit = math.min(r.limit, r.base + iptr + 6 + bytes) }
local ok, err = Load.readSample(r.buf, pos, frames, spec, s, budget)
if not ok then
return nil, err
end
pos += frames * nchs * bits // 8
if hasLoop then
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1
end
frames, ls, le = frames * 2, ls * 2, le * 2
end
end
-- the instrument extras
if xsize > 0 then
if x.hold > 0 and not isSynth then
local env = Tracker.newEnvelope()
env.enabled = true
local fall = x.hold + (if x.decay > 0 then 64 // x.decay else 0)
if x.hold == 1 then
env.ticks, env.values = { 0, fall }, { 64, 0 }
else
env.ticks, env.values = { 0, x.hold - 1, fall }, { 64, 64, 0 }
end
instr.volEnv = env
instr.fadeout = if x.decay > 0 then math.min(x.decay * 512, 65535) else 32767
needInstruments = true
end
if xsize > 4 and x.pitch ~= 0 then
instr.noteMap[24 - 12 + 1] = math.clamp(x.pitch + 1 + 23 - 12, 1, 120)
needInstruments = true
end
if xsize > 18 then
instr.globalVolume = (x.volume + 1) // 2 * 2
end
local ls, le = x.loopStart, x.loopStart + x.loopLen
for _, s in list do
s.finetune = math.clamp(x.finetune * 16, -128, 127)
if not isSynth and xsize > 14 then
s.loopStart, s.loopEnd = ls, math.min(le, s.length)
ls, le = ls * 2, le * 2
end
if xsize > 5 then
if not isSynth then
s.loopType = if bit32.band(x.flags, 1) == 0 then 0 elseif bit32.band(x.flags, 8) ~= 0 then 2 else 1
end
if bit32.band(x.flags, 4) ~= 0 then
s.globalVolume = 0
end
end
end
end
end
-- the play order: MMD0 / MMD1 a sequence of blocks; MMD2 / MMD3 sections of play sequences (stop / jump commands)
local jumps: { [number]: number } = {}
local preamp = 32
if version < 2 then
if songLength > 256 then
return nil, Err.new(Err.CORRUPT, "bad song length")
end
for i = 1, songLength do
m.order[i] = seq:u8()
end
for i = 1, nch do
local k = (i - 1) % 4
m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40
if i <= 16 then
m.channelVolume[i] = math.min(trackVol[i], 64)
end
end
else
local s2 = song:sub(4, 256)
local playSeqTable, sectionTable, trackVolsOff = s2:u32be(), s2:u32be(), s2:u32be()
local numTracks, numPlaySeqs = s2:u16be(), s2:u16be()
local trackPanOff, flags3, volAdjust = s2:u32be(), s2:u32be(), s2:u16be()
if numTracks < 1 or numTracks > 64 then
return nil, Err.new(Err.CORRUPT, "bad track count")
end
local freePan = not hardwareMix and bit32.band(flags3, 2) ~= 0
if volAdjust > 0 then
preamp = (preamp * math.min(volAdjust, 800) + 50) // 100
end
if freePan then
preamp //= 2
end
if trackVolsOff > 0 then
for i = 1, nch do
m.channelVolume[i] = math.min(r:sub(trackVolsOff + i - 1, 1):u8(), 64)
end
end
local pans = (freePan or version > 2) and trackPanOff > 0
for i = 1, nch do
if pans then
m.channelPan[i] = (math.clamp(r:sub(trackPanOff + i - 1, 1):i8(), -16, 16) + 16) * 8
else
local k = (i - 1) % 4
m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40
end
end
local sections = r:sub(sectionTable, songLength * 2)
for _ = 1, songLength do
local sec = sections:u16be()
if sections.err then
break
end
if sec <= numPlaySeqs then
local ps = r:sub(playSeqTable + sec * 4, 4):u32be()
local pr = r:sub(ps, 42)
pr:skip(32)
local cmdTable = pr:u32be()
pr:skip(4)
local len = pr:u16be()
if not pr.err then
if #m.order > 0 then
table.insert(m.order, 254)
end
local start = #m.order
local er = r:sub(ps + 42, len * 2)
for _ = 1, len do
local b = er:u16be()
if er.err then
break
end
if b < 0x8000 then
table.insert(m.order, math.min(b, 253))
end
end
if cmdTable > 0 then
local cr = r:sub(cmdTable)
for _ = 1, 4096 do
local off, c, extra = cr:u16be(), cr:u8(), cr:u8()
local arg = if extra >= 2 then cr:sub(cr:tell(), 2):u16be() else 0
cr:skip(extra)
local at = start + off + 1
if cr.err or off == 0xFFFF or at > #m.order then
break
end
if c == 1 then
m.order[at] = 255
elseif c == 2 then
jumps[at] = arg
m.order[at] = 254
end
end
end
end
end
end
end
m.preamp = preamp
-- tempo, speed, volume, the pattern context
local ctx: Ctx = {
transpose = 36 + playTranspose - (if version > 2 then 24 else 0),
is8Ch = bit32.band(flags, 0x40) ~= 0,
softMix = bit32.band(flags2, 0x80) ~= 0,
bpm = bit32.band(flags2, 0x20) ~= 0,
rowsPerBeat = 1 + bit32.band(flags2, 0x1F),
volHex = bit32.band(flags, 0x10) ~= 0,
vol7bit = false,
}
m.tempo = tempoToBpm(defTempo, ctx)
m.speed = math.clamp(tempo2, 1, 32)
if masterVol > 0 then
m.globalVolume = math.min(masterVol, 64) * 2
end
-- blocks
for b = 0, numBlocks - 1 do
local p = blockPtr[b + 1]
local pat, high = nil, false
if p and p > 0 then
pat, high = readBlock(r, p, version, ctx, nch)
end
m.patterns[b + 1] = pat or Tracker.newPattern(64, nch)
needInstruments = needInstruments or high
end
-- play-sequence jumps: a jump effect at the end of the block before the command
for at, to in jumps do
local prev = m.order[at - 1]
if prev and prev < 254 and m.patterns[prev + 1] then
-- the block may be played elsewhere: give this order entry its own copy
local src = m.patterns[prev + 1]
local cp = Tracker.newPattern(src.rows, nch)
buffer.copy(cp.data, 0, src.data)
table.insert(m.patterns, cp)
m.order[at - 1] = #m.patterns - 1
Load.writeEffect(m, #m.patterns - 1, cp.rows - 1, 0xB, math.min(to, 255), "prev")
end
end
m.samples = samples
if needInstruments then
m.instrumentMode = true
m.instruments = instruments
end
if #unsupported > 0 then
m.meta.unsupported = unsupported
end
if ext.annoOff > 0 and ext.annoLen > 1 then
m.meta.message = r:sub(ext.annoOff, ext.annoLen - 1):string(math.min(ext.annoLen - 1, r:size()))
end
m.meta.source = { format = "med", version = "MMD" .. version, instruments = needInstruments }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Med.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Med
+226
View File
@@ -0,0 +1,226 @@
--!strict
-- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared
-- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the
-- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM):
-- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk
-- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row).
-- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Mtm = {
name = "mtm",
category = "music",
extensions = { "mtm" },
mime = { "audio/x-mtm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Mtm.sniff(r: Bytes.Reader): number
if r:size() >= 66 and r:peek(3) == "MTM" and r:peekU8(3) < 0x20 and r:peekU8(33) >= 1 and r:peekU8(33) <= 32 then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- MultiTracker: a speed command resets the tempo to 125 and a tempo command the speed to 6, unless the module puts
-- both on one row somewhere (then it was written for players that treat them as ProTracker does)
local function speedTempoQuirk(m: any)
local speed, tempo, together = false, false, false
for _, p in m.patterns do
for row = 0, p.rows - 1 do
local s, t = false, false
for c = 1, m.channels do
local o = (row * m.channels + c - 1) * 5
local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4)
if fx == 0xF then
if param < 0x20 then
s = true
else
t = true
end
end
end
speed, tempo, together = speed or s, tempo or t, together or (s and t)
end
end
if not (speed and tempo) or together then
return
end
for pi, p in m.patterns do
for row = 0, p.rows - 1 do
for c = 1, m.channels do
local o = (row * m.channels + c - 1) * 5
local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4)
if fx == 0xF then
Load.writeEffect(m, pi - 1, row, 0xF, if param < 0x20 then 125 else 6, nil, nil, true)
break
end
end
end
end
end
function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if r:size() < 66 then
return nil, Err.new(Err.TRUNCATED, "header")
end
if r:peek(3) ~= "MTM" then
return nil, Err.new(Err.CORRUPT, "no MTM signature")
end
r:skip(3)
local version = r:u8()
local title = r:fixed(20)
local numTracks, lastPattern, lastOrder = r:u16le(), r:u8(), r:u8()
local commentSize, numSamples, _attr, rowsPerTrack, nch = r:u16le(), r:u8(), r:u8(), r:u8(), r:u8()
local pans: { number } = {}
for i = 1, 32 do
pans[i] = r:u8()
end
if r.err then
return nil, r.err
end
if version >= 0x20 or lastOrder > 127 or rowsPerTrack > 64 or nch == 0 or nch > 32 then
return nil, Err.new(Err.CORRUPT, "bad header")
end
local m = Tracker.newModule("mtm", nch, "xm")
m.title = title
m.linear = false
m.instrumentMode = false
for i = 1, nch do
m.channelPan[i] = (pans[i] % 16) * 16 + 8
end
-- samples
local sizes: { number } = {}
for i = 1, numSamples do
local s = Tracker.newSample(r:fixed(22))
local len, ls, le = r:u32le(), r:u32le(), r:u32le()
local ft, vol, attr = r:i8(), r:u8(), r:u8()
if r.err then
return nil, r.err
end
s.volume = math.min(vol, 64)
s.finetune = math.clamp(ft * 16, -128, 127)
local bits = if attr % 2 == 1 then 16 else 8
s.bits = bits
local frames = 0
if len > 2 then
frames = len
le = math.min(math.max(le, 1) - 1, len)
if ls + 4 >= le then
ls, le = 0, 0
end
if bits == 16 then
frames, ls, le = frames // 2, ls // 2, le // 2
end
if le > 2 then
s.loopStart, s.loopEnd, s.loopType = ls, le, 1
end
end
sizes[i] = if len > 2 then len else 0
s.length = frames
m.samples[i] = s
end
-- the order list
for i = 1, 128 do
local o = r:u8()
if i <= lastOrder + 1 then
m.order[i] = o
end
end
if r.err then
return nil, r.err
end
-- tracks (64 rows of 3 bytes each) and the patterns made of them
local rows = if rowsPerTrack > 0 then rowsPerTrack else 64
local tracks = r:tell()
if not r:skip(192 * numTracks) then
return nil, r.err
end
local buf = r.buf
for p = 0, lastPattern do
local pat = Tracker.newPattern(rows, nch)
m.patterns[p + 1] = pat
for ch = 0, 31 do
local track = r:u16le()
if r.err then
return nil, r.err
end
if track > 0 and track <= numTracks and ch < nch then
local base = r.base + tracks + 192 * (track - 1)
for row = 0, rows - 1 do
local o = base + row * 3
local b0, b1, b2 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2)
local q = (row * nch + ch) * 5
if b0 >= 4 then
buffer.writeu8(pat.data, q, b0 // 4 + 25) -- C-4 = 49 plays the sample at 8363 Hz (OpenMPT keeps MTM / XM notes an octave up)
end
buffer.writeu8(pat.data, q + 1, (b0 % 4) * 16 + b1 // 16)
local cmd, param = b1 % 16, b2
if cmd == 0xA then
param = if param >= 16 then param - param % 16 else param
elseif cmd == 8 then
cmd, param = 0, 0 -- no 8xx panning in MultiTracker
elseif cmd == 0xE then
local x = param // 16
if x == 0 or x == 3 or x == 4 or x == 6 or x == 7 or x == 0xF then
cmd, param = 0, 0 -- not in MultiTracker
end
end
buffer.writeu8(pat.data, q + 3, cmd)
buffer.writeu8(pat.data, q + 4, param)
end
end
end
end
speedTempoQuirk(m)
-- the song message (40-character lines), then the sample data (unsigned PCM)
m.meta.message = r:string(commentSize)
if r.err then
r.err = nil
end
local pos = r.pos
for i = 1, numSamples do
local s = m.samples[i]
if sizes[i] > 0 then
local ok, err = Load.readSample(buf, pos, s.length, { bits = s.bits, signed = false, limit = r.limit }, s, budget)
if not ok then
return nil, err
end
pos += sizes[i]
s.loopEnd = math.min(s.loopEnd, s.length)
end
end
m.meta.source = { format = "mtm", version = version, tracks = numTracks }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Mtm.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Mtm
+286
View File
@@ -0,0 +1,286 @@
--!strict
-- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can
-- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style
-- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with
-- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample
-- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once:
-- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume.
-- Not supported: the Amiga LED filter (F), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Chunks = require("@formats/containers/Chunks")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Okt = {
name = "okt",
category = "music",
extensions = { "okt", "okta" },
mime = { "audio/x-okt" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 4, 8 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local IT = Load.IT
local LAYOUT = table.freeze({ bigEndian = true }) :: Chunks.Layout
-- ------------------------------------------------------------------------------------------------ sniff
function Okt.sniff(r: Bytes.Reader): number
return if r:peek(8) == "OKTASONG" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- a negative arpeggio offset as the equivalent positive one
local function invert(p: number): number
p %= 16
if p == 0 then
return 0
end
return if p <= 12 then 12 - p else 24 - p
end
-- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off
local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean)
if e == 1 and p > 0 then
return "portaup", p, -1, false -- "portamento down (period)": the period goes down
elseif e == 2 and p > 0 then
return "portadown", p, -1, false
elseif e == 10 and p > 0 then
return "arpeggio", p % 16 + invert(p // 16) * 16, -1, false -- down, original, up
elseif e == 11 and p > 0 then
return "arpeggio", p - p % 16 + invert(p % 16), -1, false -- original, up, original, down
elseif e == 12 and p > 0 then
return "arpeggio", p, -1, false -- up, up, original
elseif e == 13 and p > 0 then
return "noteslidedown", 0x10 + math.min(p, 15), -1, false
elseif e == 30 and p > 0 then
return "noteslideup", 0x10 + math.min(p, 15), -1, false
elseif e == 21 and p > 0 then
return "noteslidedown", 0x50 + math.min(p, 15), -1, false
elseif e == 17 and p > 0 then
return "noteslideup", 0x50 + math.min(p, 15), -1, false
elseif e == 25 then
return "jump", p, -1, false
elseif e == 27 then
return nil, 0, -1, true
elseif e == 28 and p < 0x20 then
return "speed", p, -1, false
elseif e == 31 then
local x, y = p // 16, p % 16
local slide = if paired then "chanvolslide" else "volslide"
if p <= 0x40 then
if paired then
return "chanvol", p, -1, false
end
return nil, 0, p, false
elseif x == 4 then
return slide, y, -1, false
elseif x == 5 then
return slide, y * 16, -1, false
elseif x == 6 then
return slide, 0xF0 + math.min(y, 0xE), -1, false
elseif x == 7 then
return slide, math.min(y, 0xE) * 16 + 0xF, -1, false
end
end
return nil, 0, -1, false
end
function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if r:peek(8) ~= "OKTASONG" then
return nil, Err.new(if r:size() < 8 then Err.TRUNCATED else Err.CORRUPT, "no OKTASONG signature")
end
local buf = r.buf
local list = Chunks.walk(buf, r.base + 8, r.limit, LAYOUT)
local cmod = Chunks.find(list, "CMOD")
if not cmod or cmod.avail < 8 then
return nil, Err.new(Err.CORRUPT, "no channel table (CMOD)")
end
-- channels: each Amiga channel is one channel, or a mixed pair
local paired: { number } = {} -- 1: the first of a pair, -1: the second, 0: a raw Paula channel
local pans: { number } = {}
for ch = 0, 3 do
local pan = if ch == 1 or ch == 2 then 0xC0 else 0x40
if buffer.readu16(buf, cmod.offset + ch * 2) ~= 0 then
table.insert(paired, 1)
table.insert(pans, pan)
table.insert(paired, -1)
else
table.insert(paired, 0)
end
table.insert(pans, pan)
end
local nch = #paired
local m = Tracker.newModule("okt", nch, "it")
m.linear = false
m.instrumentMode = false
m.tempo = 125
m.flags.periods, m.flags.amigaLimits, m.flags.fastPortas, m.flags.oktSlides = "amiga", true, true, true
for i = 1, nch do
m.channelPan[i] = pans[i]
end
-- samples: 32-byte headers (name, length, loop start / length in words, volume, type 0 / 1 / 2)
local types: { number } = {}
local samp = Chunks.find(list, "SAMP")
if samp then
for i = 1, math.min(samp.avail // 32, 36) do
local h = Bytes.reader(buf, samp.offset + (i - 1) * 32, 32)
local s = Tracker.newSample(h:fixed(20))
local len, ls, ll, vol, typ = h:u32be(), h:u16be() * 2, h:u16be() * 2, h:u16be(), h:u16be()
s.c5speed = 8287
s.volume = math.min(vol, 64)
s.length = len - len % 2
if ll > 2 and ls + ll <= s.length then
s.susStart, s.susEnd, s.susType = ls, ls + ll, 1
end
types[i] = typ
m.samples[i] = s
end
end
local spee = Chunks.find(list, "SPEE")
if spee and spee.avail >= 2 then
m.speed = math.clamp(buffer.readu8(buf, spee.offset) * 256 + buffer.readu8(buf, spee.offset + 1), 1, 255)
end
local nord = 0
local plen = Chunks.find(list, "PLEN")
if plen and plen.avail >= 2 then
nord = buffer.readu8(buf, plen.offset) * 256 + buffer.readu8(buf, plen.offset + 1)
end
local patt = Chunks.find(list, "PATT")
for i = 1, math.min(nord, if patt then patt.avail else 0) do
m.order[i] = buffer.readu8(buf, (patt :: Chunks.Chunk).offset + i - 1)
end
-- patterns (PBOD: rows, then 4 bytes per cell: note 1..36, sample, effect, parameter)
local copies: { [number]: boolean } = {} -- type B samples with a loop also need an unlooped copy (paired channels)
local npat = 0
for _, c in list do
if c.id == "PBOD" and npat < 256 then
local pr = Bytes.reader(buf, c.offset, c.avail)
local rows = if c.avail >= 2 then math.clamp(pr:u16be(), 1, 1024) else 64
local pat = Tracker.newPattern(rows, nch)
npat += 1
m.patterns[npat] = pat
local d = pat.data
for row = 0, rows - 1 do
for ch = 0, nch - 1 do
local note, ins, e, p = pr:u8(), pr:u8(), pr:u8(), pr:u8()
if pr.err then
break
end
local q = (row * nch + ch) * 5
local pair = paired[ch + 1] ~= 0
if note > 0 and note <= 36 then
local n = note + 36 -- note 13 = C-4 = ProTracker period 428 (OpenMPT keeps MOD notes an octave up)
if pair and n >= 49 + 22 then
n = 49 + 21 -- the mixer's highest note
end
local smp = ins + 1
local s = m.samples[smp]
if s then
if pair and s.volume < 64 then
buffer.writeu8(d, q + 2, 64 + 1) -- the default volume only works on raw Paula channels
end
local t = types[smp]
if (t == 1 and pair) or (t == 0 and not pair) then
smp += 100 -- a sample of the wrong type stops the channel
elseif t == 2 and pair and s.susType > 0 then
copies[smp] = true
smp += 36
end
end
buffer.writeu8(d, q, n)
buffer.writeu8(d, q + 1, smp)
end
local name, param, vol, off = effect(e, p, pair)
if off then
buffer.writeu8(d, q, 255)
buffer.writeu8(d, q + 1, 0)
end
if vol >= 0 then
buffer.writeu8(d, q + 2, vol + 1)
end
local fx, fp = Load.itEffect(name, param)
if fx ~= 0 then
buffer.writeu8(d, q + 3, fx)
buffer.writeu8(d, q + 4, fp)
if name == "chanvol" or name == "chanvolslide" then
-- a mixed pair shares its volume: the other channel gets it too (the second one wins)
local other = ch + paired[ch + 1]
local o2 = (row * nch + other) * 5
local ofx = buffer.readu8(d, o2 + 3)
if ofx == 0 or ofx == IT.chanvol or ofx == IT.chanvolslide then
buffer.writeu8(d, o2 + 3, fx)
buffer.writeu8(d, o2 + 4, fp)
end
end
end
end
end
end
end
-- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length
local k = 0
local bodies: { Chunks.Chunk } = {}
for _, c in list do
if c.id == "SBOD" and c.avail > 0 then
table.insert(bodies, c)
end
end
local nsmp = #m.samples
for i = 1, nsmp do
local s = m.samples[i]
if s.length > 0 then
k += 1
local c = bodies[k]
if not c then
s.length = 0
continue
end
local ok, err = Load.readSample(buf, c.offset, math.min(s.length, c.avail), { bits = 8, signed = true, limit = c.offset + c.avail }, s, budget)
if not ok then
return nil, err
end
end
end
for i = 1, nsmp do
local s = m.samples[i]
if copies[i] then
local cp = Tracker.newSample(s.name)
cp.c5speed, cp.volume, cp.data, cp.length = s.c5speed, s.volume, s.data, s.length
m.samples[i + 36] = cp
end
end
for i = 1, (if next(copies) then 72 else nsmp) do
if m.samples[i] == nil then
m.samples[i] = Tracker.newSample()
end
end
m.meta.source = { format = "okt", channels = nch }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Okt.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Okt
+227
View File
@@ -0,0 +1,227 @@
--!strict
-- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD
-- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the
-- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx
-- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger,
-- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the
-- byte stream, as PolyTracker stores them), ping-pong loops.
-- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Ptm = {
name = "ptm",
category = "music",
extensions = { "ptm" },
mime = { "audio/x-ptm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
-- PolyTracker's effects past MOD's 0..F
local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" }
-- ------------------------------------------------------------------------------------------------ sniff
local function validHeader(r: Bytes.Reader): boolean
if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then
return false
end
local h = r:sub(32, 10)
local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le()
return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128
end
function Ptm.sniff(r: Bytes.Reader): number
return if validHeader(r) then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values
local function delta16(buf: buffer, off: number, frames: number, limit: number): (buffer, number)
local n = math.max(0, math.min(frames, (limit - off) // 2))
local raw = buffer.create(n * 2)
local acc = 0
for i = 0, n * 2 - 1 do
acc = (acc + buffer.readu8(buf, off + i)) % 256
buffer.writeu8(raw, i, acc)
end
return raw, n
end
-- a PolyTracker effect -> name?, param
local function effect(cmd: number, param: number): (string?, number)
if cmd == 0x10 then
return "globalvol", math.min(param, 0x40) * 2
elseif cmd > 0x10 then
return EXTRA[cmd - 0x10 + 1], param
elseif cmd == 8 then
return "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 -- 8xx pans in 16 steps
end
return Load.modCommand(cmd, param)
end
-- one pattern (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume)
local function readPattern(pr: Bytes.Reader, d: buffer, nch: number)
local row = 0
while row < 64 and not pr:eof() do
local b = pr:u8()
if b == 0 then
row += 1
else
local ch = b % 32
local q = (row * nch + ch) * 5
local ok = ch < nch
if bit32.band(b, 0x20) ~= 0 then
local note, ins = pr:u8(), pr:u8()
if note == 254 then
note = 254
elseif note == 0 or note > 120 then
note = 0
end
if ok then
buffer.writeu8(d, q, note)
buffer.writeu8(d, q + 1, ins)
end
end
if bit32.band(b, 0x40) ~= 0 then
local name, param = effect(pr:u8(), pr:u8())
if ok then
if name == "volume" then
if buffer.readu8(d, q + 2) == 0 then
buffer.writeu8(d, q + 2, math.min(param, 64) + 1)
end
else
local fx, fp = Load.itEffect(name, param)
buffer.writeu8(d, q + 3, fx)
buffer.writeu8(d, q + 4, fp)
end
end
end
if bit32.band(b, 0x80) ~= 0 then
local v = pr:u8()
if ok then
buffer.writeu8(d, q + 2, math.min(v, 64) + 1)
end
end
end
end
end
function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if not validHeader(r) then
return nil, Err.new(if r:size() < 608 then Err.TRUNCATED else Err.CORRUPT, "not a PolyTracker module")
end
local title = r:fixed(28)
r:skip(1)
local vlo, vhi = r:u8(), r:u8()
r:skip(1)
local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le()
r:seek(64)
local m = Tracker.newModule("ptm", nch, "it")
m.title = title
m.linear = false
m.instrumentMode = false
m.flags.oldEffects, m.flags.compatGxx = true, true
m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels
for i = 1, 32 do
local p = r:u8()
if i <= nch then
m.channelPan[i] = (p % 16) * 16 + 4
end
end
for i = 1, 256 do
local o = r:u8()
if i <= nord then
m.order[i] = o
end
end
local patOff: { number } = {}
for i = 1, 128 do
patOff[i] = r:u16le() * 16
end
if r.err then
return nil, r.err
end
-- samples
local buf = r.buf
for i = 1, nsmp do
local h = r:slice(80)
if r.err then
return nil, r.err
end
local flags = h:u8()
h:skip(12)
local vol, c4 = h:u8(), h:u16le()
h:skip(2)
local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le()
h:skip(14)
local s = Tracker.newSample(h:fixed(28))
m.samples[i] = s
s.volume = math.min(vol, 64)
s.c5speed = math.max(1, c4 * 2)
if flags % 4 == 1 and len > 0 then
local bits = if bit32.band(flags, 0x10) ~= 0 then 16 else 8
if le > ls then
le -= 1
end
local frames = len
if bits == 16 then
frames, ls, le = frames // 2, ls // 2, le // 2
end
local at = r.base + off
if at < r.limit then
local ok, err
if bits == 16 then
local raw, n = delta16(buf, at, frames, r.limit)
ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget)
else
ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget)
end
if not ok then
return nil, err
end
end
if bit32.band(flags, 4) ~= 0 and le > ls then
s.loopStart, s.loopEnd = ls, math.min(le, s.length)
s.loopType = if bit32.band(flags, 8) ~= 0 then 2 else 1
end
end
end
for p = 1, npat do
local pat = Tracker.newPattern(64, nch)
m.patterns[p] = pat
if patOff[p] > 0 and patOff[p] < r:size() then
readPattern(r:sub(patOff[p]), pat.data, nch)
end
end
m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Ptm.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Ptm
+233
View File
@@ -0,0 +1,233 @@
--!strict
-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples).
-- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module
-- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the
-- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump
-- happens at the end of the pattern or at the next Cxx).
-- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Stm = {
name = "stm",
category = "music",
extensions = { "stm" },
mime = { "audio/x-stm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 4, 4 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local IT = Load.IT
-- .ABCDEFGHIJ (K..O do nothing)
local EFFECTS = { "speed", "jump", "break", "volslide", "portadown", "portaup", "toneporta", "vibrato", "tremor", "arpeggio" }
-- ------------------------------------------------------------------------------------------------ sniff
local function validHeader(r: Bytes.Reader): boolean
if r:size() < 48 then
return false
end
local eof, ftype, major, minor = r:peekU8(28), r:peekU8(29), r:peekU8(30), r:peekU8(31)
local npat, gv = r:peekU8(33), r:peekU8(34)
if ftype ~= 2 or (eof ~= 0x1A and eof ~= 2) or major ~= 2 or (minor ~= 0 and minor ~= 10 and minor ~= 20 and minor ~= 21) then
return false
end
if npat > 64 or (gv > 64 and gv ~= 0x58) then
return false
end
for i = 20, 27 do
local c = r:peekU8(i)
if c < 0x20 or c >= 0x7F then
return false
end
end
return true
end
function Stm.sniff(r: Bytes.Reader): number
return if validHeader(r) then 0.7 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- a tempo byte of files before ST 2.21 is decimal
local function tempoByte(v: number, minor: number): number
return if minor < 21 then (v // 10) * 16 + v % 10 else v
end
function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if not validHeader(r) then
return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not a Scream Tracker 2 module")
end
local title = r:fixed(20)
local tracker = r:fixed(8)
r:skip(3)
local minor, initTempo, npat, gv = r:u8(), r:u8(), r:u8(), r:u8()
r:skip(13)
local m = Tracker.newModule("stm", 4, "s3m")
m.title = title
m.linear = false
m.instrumentMode = false
m.flags.st2Tempo = true
initTempo = tempoByte(initTempo, minor)
if initTempo == 0 then
initTempo = 0x60
end
m.speed, m.tempo = Tracker.st2Tempo(initTempo)
if minor > 10 then
m.globalVolume = math.min(gv, 64) * 2
end
local offsets: { number } = {}
for i = 1, 31 do
local s = Tracker.newSample(r:fixed(12))
local zero = r:u8()
r:skip(1)
local off, len, ls, le = r:u16le(), r:u16le(), r:u16le(), r:u16le()
local vol = r:u8()
r:skip(1)
local rate = r:u16le()
r:skip(6)
if r.err then
return nil, r.err
end
if zero ~= 0 and zero ~= 46 then
return nil, Err.new(Err.CORRUPT, "bad sample header " .. i)
end
s.c5speed = if rate > 0 then rate else 8363
s.volume = math.min(vol, 64)
if len < 2 then
len = 0
end
if ls < len and le > ls and le ~= 0xFFFF then
s.loopStart, s.loopEnd, s.loopType = ls, le, 1
len = math.max(le, len) -- ST2 lets a loop run into the next sample's data
end
s.length = len
offsets[i] = off * 16
m.samples[i] = s
end
for i = 1, (if minor == 0 then 64 else 128) do
local o = r:u8()
if o == 99 or o == 255 then
o = 255
elseif o > 63 then
return nil, Err.new(Err.CORRUPT, "bad order list")
end
m.order[i] = o
end
if r.err then
return nil, r.err
end
while #m.order > 0 and m.order[#m.order] == 255 do
table.remove(m.order)
end
-- patterns: 64 rows x 4 channels; one byte 0xFB (C-0, volume 0), 0xFC (nothing) or 0xFD (note cut), else 4 bytes
for p = 0, npat - 1 do
local pat = Tracker.newPattern(64, 4)
m.patterns[p + 1] = pat
local d = pat.data
local breakPos, breakRow = -1, 63 -- ST2: Bxx only sets the next order, taken at the pattern's end or a Cxx
for row = 0, 63 do
for ch = 0, 3 do
local q = (row * 4 + ch) * 5
local note = r:u8()
local insVol, volCmd, info = 0, 0, 0
if note == 0xFB then
note = 0 -- a C-0 at volume 0 (OpenMPT reads it so)
elseif note == 0xFD then
buffer.writeu8(d, q, 254)
elseif note ~= 0xFC then
insVol, volCmd, info = r:u8(), r:u8(), r:u8()
end
if note ~= 0xFC and note ~= 0xFD then
if note == 0xFE then
buffer.writeu8(d, q, 254)
elseif note < 0x60 then
buffer.writeu8(d, q, (note // 16) * 12 + note % 16 + 37)
end
local ins = insVol // 8
buffer.writeu8(d, q + 1, if ins > 31 then 0 else ins)
local vol = insVol % 8 + (volCmd // 16) * 8
if vol <= 64 then
buffer.writeu8(d, q + 2, vol + 1)
end
local name, param = EFFECTS[volCmd % 16], info
if name == "volslide" then
param = if param % 16 > 0 then param % 16 else param - param % 16
elseif name == "break" then
param = ((param - param % 16) * 10 + param % 16) % 256
if breakPos >= 0 and param == 0 then
name, param = "jump", breakPos -- Bxx + C00 is a plain Bxx
breakPos = -1
end
breakRow = math.min(breakRow, row)
if name == "break" then
param = Load.bcd(param)
end
elseif name == "jump" then
breakPos, breakRow = param, 63
name = nil
elseif name == "speed" then
param = tempoByte(param, minor)
if param == 0 then
name = nil
end
elseif name ~= "tremor" and param == 0 then
name = nil -- no effect memory in ST2
end
if name then
buffer.writeu8(d, q + 3, IT[name])
buffer.writeu8(d, q + 4, param)
end
end
end
end
if r.err then
return nil, r.err
end
if breakPos >= 0 then
Load.writeEffect(m, p, breakRow, IT.jump, breakPos, "prev")
end
end
-- sample data: signed 8-bit at the paragraph offsets (samples at volume 0 are not read)
local buf = r.buf
for i = 1, 31 do
local s = m.samples[i]
local len = s.length
s.length = 0
if len > 0 and s.volume > 0 and offsets[i] > 48 then
local ok, err = Load.readSample(buf, r.base + offsets[i], len, { bits = 8, signed = true, limit = r.limit }, s, budget)
if not ok then
return nil, err
end
end
end
m.meta.source = { format = "stm", tracker = tracker, version = "2." .. minor }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Stm.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Stm
+309
View File
@@ -0,0 +1,309 @@
--!strict
-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored
-- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt).
-- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects
-- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect
-- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone
-- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune.
-- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the
-- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
local Load = require("@formats/codecs/audio/Tracker/Load")
-- ------------------------------------------------------------------------------------------------ contract
local Ult = {
name = "ult",
category = "music",
extensions = { "ult" },
mime = { "audio/x-ult" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local EFFECTS: { [number]: string } = {
[0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [7] = "tremolo",
[9] = "offset", [10] = "volslide", [11] = "panning8", [12] = "volume8", [13] = "break", [15] = "speed",
}
-- ------------------------------------------------------------------------------------------------ sniff
function Ult.sniff(r: Bytes.Reader): number
local v = r:peekU8(14)
if r:size() >= 48 and r:peek(14) == "MAS_UTrack_V00" and v >= 0x31 and v <= 0x34 then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands)
local function translate(e: number, param: number, version: number): (string?, number)
local name = EFFECTS[e]
if e == 0 then
if param == 0 or version < 3 then
name = nil
end
elseif e == 5 then
if (param % 16 == 0xC or param // 16 == 0xC) and version >= 3 then
return "keyoff", 0
end
elseif e == 7 then
if version < 4 then
name = nil
end
elseif e == 0xA then
if param >= 16 then
param -= param % 16
end
elseif e == 0xB then
param = (param % 16) * 0x11
elseif e == 0xD then
param = 10 * (param // 16) + param % 16
elseif e == 0xE then
local x, y = param // 16, param % 16
if x == 1 then
return "portaup", 0xF0 + y
elseif x == 2 then
return "portadown", 0xF0 + y
elseif x == 8 and version >= 4 then
return "s3mex", 0x60 + y
elseif x == 9 then
return "retrig", y
elseif x == 0xA then
return "volslide", y * 16 + 0xF
elseif x == 0xB then
return "volslide", 0xF0 + y
elseif x == 0xC or x == 0xD then
return "s3mex", param
end
return nil, param
elseif e == 0xF then
if param > 0x2F then
name = "tempo"
end
end
return name, param
end
-- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects)
local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number)
if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then
return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0
elseif b == "volslide" and (a == "vibrato" or a == "toneportavol") and pa == 0 then
return if a == "vibrato" then "vibratovol" else "toneportavol", pb, nil, 0
end
return a, pa, b, pb
end
-- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param,
-- lost global effect (name?, param)
local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number)
local rep = 1
local b = r:u8()
if b == 0xFC then
rep = r:u8()
b = r:u8()
end
local note = if b > 0 and b < 97 then b + 24 else 0
local ins, cmd, p1, p2 = r:u8(), r:u8(), r:u8(), r:u8()
local c1, q1 = translate(cmd % 16, p1, version)
local c2, q2 = translate(cmd // 16, p2, version)
if c1 == "offset" and c2 == "offset" then
local off = (p2 * 256 + p1) // 64
return rep, note, ins, 0, Load.IT.offset, off % 256, nil, 0
elseif c1 == "offset" then
q1 = math.min(p1 * 4, 255)
elseif c2 == "offset" then
q2 = math.min(p2 * 4, 255)
elseif c1 ~= nil and c1 == c2 then
c2 = nil
end
if c2 == nil then -- (OpenMPT also swaps for CMD_VOLUME, which ULT never produces)
c1, q1, c2, q2 = c2, q2, c1, q1
end
c2, q2, c1, q1 = combine(c2, q2, c1, q1)
if c1 == "keyoff" or c2 == "keyoff" then
-- key off (5xC): a note-off when the cell has no note
if note == 0 then
note = 255
end
if c1 == "keyoff" then
c1 = nil
else
c2 = nil
end
end
local vol, name, param, lost, lostParam = Load.fillTwo(c1, q1, c2, q2)
local fx, fp = Load.itEffect(name, param)
return rep, note, ins, vol, fx, fp, lost, lostParam
end
function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
if Ult.sniff(r) == 0 then
return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not an UltraTracker module")
end
r:skip(14)
local version = r:u8() - 0x30
local title = (string.gsub(r:fixed(32), " +$", ""))
local lines = r:u8()
local message = r:string(lines * 32)
local nsmp = r:u8()
if r.err then
return nil, r.err
end
local samples, sizes = {}, {}
for i = 1, nsmp do
local s = Tracker.newSample((string.gsub(r:fixed(32), " +$", "")))
r:skip(12)
local ls, le, ss, se = r:u32le(), r:u32le(), r:u32le(), r:u32le()
local vol, flags = r:u8(), r:u8()
local speed, finetune = 8363, 0
if version >= 4 then
speed, finetune = r:u16le(), r:i16le()
else
finetune = r:i16le()
end
if r.err then
return nil, r.err
end
local bits = if bit32.band(flags, 4) ~= 0 then 16 else 8
s.bits = bits
sizes[i] = 0
if se > ss then
s.length = se - ss
sizes[i] = s.length * bits // 8
s.volume = vol / 4
s.c5speed = math.max(1, speed * 2 * 2 ^ (finetune / (12 * 32768)))
if bit32.band(flags, 8) ~= 0 then
if bits == 16 then
ls, le = ls // 2, le // 2
end
s.susStart, s.susEnd = ls, le
s.susType = if bit32.band(flags, 16) ~= 0 then 2 else 1
end
end
samples[i] = s
end
local order = {}
for i = 1, 256 do
order[i] = r:u8()
end
local nch, npat = r:u8() + 1, r:u8() + 1
if r.err then
return nil, r.err
end
if nch > 32 then
return nil, Err.new(Err.UNSUPPORTED, nch .. " channels")
end
local m = Tracker.newModule("ult", nch, "it")
m.title = title
m.meta.message = message
m.linear = false
m.instrumentMode = false
m.flags.oldEffects, m.flags.compatGxx, m.flags.autoTonePorta = true, true, true
m.samples = samples
for i = 1, 256 do
m.order[i] = order[i]
end
while #m.order > 0 and m.order[#m.order] == 255 do
table.remove(m.order)
end
for i = 1, nch do
m.channelPan[i] = if version >= 3 then (r:u8() % 16) * 16 + 8 elseif i % 2 == 0 then 192 else 64
end
for p = 1, npat do
m.patterns[p] = Tracker.newPattern(64, nch)
end
-- events, channel by channel, pattern by pattern
local speed0 = false
for ch = 0, nch - 1 do
for p = 0, npat - 1 do
if r:remaining() < 5 then
break
end
local d = m.patterns[p + 1].data
local row = 0
while row < 64 do
local rep, note, ins, vol, fx, param, lost, lostParam = readEvent(r, version)
if r.err then
break
end
if lost and Load.isGlobal(lost, lostParam) then
local lf, lp = Load.itEffect(lost, lostParam)
Load.writeEffect(m, p, row, lf, lp, "next")
end
rep = math.min(rep, 64 - row)
if rep == 0 then
break
end
if fx == Load.IT.speed and param == 0 then
speed0 = true
end
for _ = 1, rep do
local q = (row * nch + ch) * 5
buffer.writeu8(d, q, note)
buffer.writeu8(d, q + 1, ins)
buffer.writeu8(d, q + 2, vol)
buffer.writeu8(d, q + 3, fx)
buffer.writeu8(d, q + 4, param)
row += 1
end
end
end
end
r.err = nil
if speed0 then
-- speed 0 resets the song speed and tempo (UltraTracker)
for p, pat in m.patterns do
for row = 0, 63 do
for ch = 0, nch - 1 do
local q = (row * nch + ch) * 5
if buffer.readu8(pat.data, q + 3) == Load.IT.speed and buffer.readu8(pat.data, q + 4) == 0 then
buffer.writeu8(pat.data, q + 4, 6)
Load.writeEffect(m, p - 1, row, Load.IT.tempo, 125, "next")
end
end
end
end
end
-- sample data: signed 8 / 16-bit
local pos = r.pos
for i = 1, nsmp do
local s = samples[i]
if sizes[i] > 0 then
local ok, err = Load.readSample(r.buf, pos, s.length, { bits = s.bits, signed = true, limit = r.limit }, s, budget)
if not ok then
return nil, err
end
pos += sizes[i]
end
end
m.meta.source = { format = "ult", version = version }
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Ult.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Ult
+222
View File
@@ -0,0 +1,222 @@
--!strict
-- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package
-- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt):
-- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each
-- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first
-- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and
-- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is
-- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it.
-- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/audio/Tracker")
-- ------------------------------------------------------------------------------------------------ contract
local Umx = {
name = "umx",
category = "music",
extensions = { "umx" },
mime = { "audio/x-umx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
caps = { decode = true, encode = false, render = true, container = true },
}
export type DecodeOptions = {
decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, -- loads the inner module (the api passes it)
index: number?, -- which music export to load (1-based, default 1)
}
export type Entry = { name: string, data: buffer, format: string? }
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "\xC1\x83\x2A\x9E"
-- ------------------------------------------------------------------------------------------------ sniff
type Header = { version: number, nameCount: number, nameOffset: number, exportCount: number, exportOffset: number, importCount: number, importOffset: number }
local function header(r: Bytes.Reader): Header?
if r:size() < 36 or r:peek(4) ~= MAGIC then
return nil
end
local h = r:sub(4, 32)
local version = h:u16le()
h:skip(6)
local hd: Header = {
version = version,
nameCount = h:u32le(),
nameOffset = h:u32le(),
exportCount = h:u32le(),
exportOffset = h:u32le(),
importCount = h:u32le(),
importOffset = h:u32le(),
}
if h.err or hd.nameOffset < 36 or hd.exportOffset < 36 or hd.importOffset < 36 then
return nil
end
if hd.nameCount == 0 or hd.exportCount == 0 or hd.importCount == 0 or hd.nameCount > 2 ^ 20 or hd.exportCount > 2 ^ 20 or hd.importCount > 2 ^ 20 then
return nil
end
return hd
end
-- a compact index: sign and 6 bits, then 7 bits per byte while the continue bits are set
local function index(r: Bytes.Reader): number
local b = r:u8()
local neg = b >= 0x80
local v = b % 64
if bit32.band(b, 0x40) ~= 0 then
local shift = 6
repeat
b = r:u8()
v += (b % 128) * 2 ^ shift
shift += 7
until b < 0x80 or shift >= 32
end
return if neg then -v else v
end
-- the name table (lower case)
local function names(r: Bytes.Reader, h: Header): { string }
local list = {}
local nr = r:sub(h.nameOffset)
for _ = 1, math.min(h.nameCount, 65536) do
if nr:remaining() < 5 then
break
end
if h.version >= 64 then
index(nr)
end
table.insert(list, string.lower(nr:cstring(1024)))
nr:skip(4)
end
return list
end
function Umx.sniff(r: Bytes.Reader): number
local h = header(r)
if not h then
return 0
end
return if table.find(names(r, h), "music") then 1 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
-- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format:
-- a guess from the inner module's signature: "it", "s3m", "xm", "mod")
function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?)
local h = header(r)
if not h then
return nil, Err.new(if r:size() < 36 then Err.TRUNCATED else Err.CORRUPT, "not an Unreal package")
end
local nm = names(r, h)
-- imports: the class names objects refer to
local classes = {}
local ir = r:sub(h.importOffset)
for _ = 1, math.min(h.importCount, 65536) do
if ir:remaining() < 4 then
break
end
index(ir)
index(ir)
if h.version >= 60 then
ir:skip(4)
else
index(ir)
end
local obj = index(ir)
if obj >= 0 and obj < #nm then
table.insert(classes, obj)
end
end
local out: { Entry } = {}
local er = r:sub(h.exportOffset)
for _ = 1, math.min(h.exportCount, 65536) do
if er:remaining() < 8 then
break
end
local cls = -index(er) - 1 -- ~index: the import the class is
index(er)
if h.version >= 60 then
er:skip(4)
end
local objName = index(er)
er:skip(4)
local size, offset = index(er), index(er)
if er.err then
break
end
if cls >= 0 and cls < #classes and nm[classes[cls + 1] + 1] == "music" and size > 0 and offset > 36 then
local c = r:sub(offset, size)
if h.version < 40 then
c:skip(8)
end
if h.version < 60 then
c:skip(16)
end
index(c) -- the property list's "none"
if h.version >= 120 then
index(c)
c:skip(8)
elseif h.version >= 100 then
c:skip(4)
index(c)
c:skip(4)
elseif h.version >= 62 then
index(c)
c:skip(4)
else
index(c)
end
local len = index(c)
if not c.err and len > 0 and len <= c:remaining() then
local data = c:bytes(len)
local sig = Bytes.reader(data)
local fmt = if sig:peek(4) == "IMPM" then "it" elseif sig:peek(4, 44) == "SCRM" then "s3m" elseif sig:peek(17) == "Extended Module: " then "xm" elseif buffer.len(data) >= 1084 then "mod" else nil
table.insert(out, { name = nm[objName + 1] or "", data = data, format = fmt })
end
end
end
return out, nil
end
function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local list, err = Umx.extract(r)
if not list then
return nil, err
end
local i = opts and opts.index or 1
local e = list[i]
if not e then
return nil, Err.new(Err.CORRUPT, "no music export" .. (if i > 1 then " " .. i else ""))
end
local hook = opts and opts.decodeModule
if type(hook) ~= "function" then
return nil, Err.new(Err.UNSUPPORTED, "the embedded " .. (e.format or "tracker") .. " module needs opts.decodeModule (F.load passes it; Umx.extract gives the bytes)")
end
local m, merr = hook(e.data, nil)
if not m then
return nil, merr
end
if type(m) ~= "table" or m.kind ~= "music" then
return nil, Err.new(Err.UNSUPPORTED, "the embedded module is not a tracker module")
end
local h = header(r) :: Header
m.meta = if type(m.meta) == "table" then m.meta else {}
m.meta.container = { format = "umx", name = e.name, version = h.version, count = #list }
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Umx.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Umx
+4 -3
View File
@@ -27,7 +27,8 @@ local function bad(what: string): (nil, Err.Err)
end
local function isModule(m: any): boolean
return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == true and type(m.patterns) == "table"
-- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four)
return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table"
end
local function int(v: any, lo: number, hi: number): boolean
@@ -243,7 +244,7 @@ function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?)
local copy = buffer.create(length * channels * 4)
buffer.copy(copy, 0, data, 0, length * channels * 4)
s.data, s.length, s.channels = copy, length, channels
s.bits = spec.bits or (if m.format == "mod" then 8 else 16)
s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16)
if s.bits ~= 8 and s.bits ~= 16 then
return bad("addSample: bits must be 8 or 16")
end
@@ -298,7 +299,7 @@ function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err
if not isModule(m) then
return bad("addInstrument: needs a tracker Module")
end
if m.format ~= "xm" and m.format ~= "it" then
if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then
return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)")
end
if type(spec) ~= "table" then