ws-audio2: music/med (MED / OctaMED MMD0..MMD3): xm family with ProTracker periods, MED effects and tempo modes, play sequences, hold / decay envelopes, IFF multi-octave keymaps; engine: EXT tempo > 255, flags.envRowHold

Synthetic / hybrid / MIDI instruments are silent (listed in meta.unsupported).
This commit is contained in:
4DBug committed 2026-10-31 14:51:33 -05:00
1 parent d418458e2a
commit 3d5cf3130e
8 files changed
+935 -5

No files matched your search

+1
View File
@@ -76,6 +76,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| music | 669 | .669 | yes | - | render: true, channels: 8, 8 | `tests/music/669.luau` |
| music | far | .far | yes | - | render: true, channels: 16, 16 | `tests/music/far.luau` |
| music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` |
| music | med | .med .mmd0 .mmd1 .mmd2 .mmd3 .omed | yes | - | render: true, channels: 1, 64 | `tests/music/med.luau` |
| music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` |
| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` |
| music | mtm | .mtm | yes | - | render: true, channels: 1, 32 | `tests/music/mtm.luau` |
+12
View File
@@ -866,6 +866,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",
+10 -3
View File
@@ -33,6 +33,7 @@ local EXT = {
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
@@ -222,6 +223,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any
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,
@@ -1648,6 +1650,10 @@ local function fxExt(st: any, c: any, tick: number)
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
@@ -1806,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
@@ -1821,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
+4 -2
View File
@@ -27,7 +27,8 @@
-- 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) }
-- 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
@@ -39,7 +40,8 @@
-- (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)). Tracker.cell / Tracker.setCell read and write cells.
-- 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),
+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
+22
View File
@@ -0,0 +1,22 @@
-- music/med tests: generated MED / OctaMED modules (tools/fixtures/med.py: MMD0, MMD1 with hold / decay and finetune,
-- MMD2 with a play sequence, an IFF 3-octave sample) parsed, rendered through codecs/audio/Tracker and compared with openmpt123's render
-- (loudness envelope, band spectrum, stereo balance, song length), the contract, and the fuzz no-throw pass.
local T = require("@tests/T")
local S = require("@tests/music/_similar")
local Med = require("@formats/music/med")
local Cases = require("@tests/gen/med_cases")
local t = T.suite("med")
t:eq(Med.name, "med", "name")
t:eq(Med.category, "music", "category")
t:check(Med.caps.decode and not Med.caps.encode, "caps")
local mods = S.against(t, Med, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "xm")
t:check(mods[2] and mods[2].instrumentMode and mods[2].instruments[1].volEnv ~= nil, "MMD1 hold / decay: an instrument envelope")
t:check(mods[2] and mods[2].title == "med test", "song name")
t:check(mods[3] and mods[3].channels == 6 and mods[3].meta.source.version == "MMD2", "MMD2")
t:check(mods[4] and mods[4].instrumentMode and #mods[4].samples == 4 and mods[4].samples[3].length == 128, "IFF 3-octave sample")
t:fuzz("decode", S.fuzzer(Med), S.samples(Cases), { mutations = 30 })
t:done()
+112
View File
@@ -781,3 +781,115 @@ def write_okt(samples, orders, patterns, cmod=(0, 0, 0, 0), speed=6):
for s in samples:
out += chunk(b"SBOD", s["data"])
return bytes(out)
def write_med(version, samples, blocks, sequence, tempo=125, tempo2=6, flags=0, flags2=0, trackvols=None,
pans=None, master=64, play_transpose=0, sections=None, title=None):
"""an MMD0 .. MMD3 module. samples: [{data (signed 8-bit bytes, or big-endian 16-bit with bits 16), bits, volume,
transpose, loop: (start, length) in bytes (even) | None, hold, decay, finetune, octaves (IFF multi-octave count:
data holds the octaves from the lowest, each twice as long)}]; blocks: [[row: [(note, ins, cmd, param)] * tracks]
* rows] with note 0 = none else the MED note (1 = C-1; MMD1+: 0x80 = note off); sequence: block numbers (MMD0 / 1)
or the play sequence (MMD2 / 3; sections: [[playseq numbers]] and playseqs = [sequence])"""
out = bytearray(52)
song_at = 52
out += b"\0" * (63 * 8 + 284)
need_ext = any(s.get("hold") or s.get("finetune") for s in samples) or title is not None
def align():
while len(out) % 4:
out.append(0)
# blocks
block_ptrs = []
for blk in blocks:
align()
block_ptrs.append(len(out))
ntr = len(blk[0])
if version == 0:
out += bytes([ntr, len(blk) - 1])
else:
out += struct.pack(">HHI", ntr, len(blk) - 1, 0)
for row in blk:
for (note, ins, cmd, param) in row:
if version == 0:
out += bytes([(note & 0x3F) | ((ins & 0x10) << 3) | ((ins & 0x20) << 1), ((ins & 15) << 4) | (cmd & 15), param])
else:
out += bytes([note, ins & 0x3F, cmd, param])
align()
block_arr = len(out)
for p in block_ptrs:
out += struct.pack(">I", p)
# instruments
inst_ptrs = []
for s in samples:
align()
inst_ptrs.append(len(out))
oct_ = s.get("octaves", 1)
typ = {1: 0, 5: 1, 3: 2, 2: 3, 4: 4, 6: 5, 7: 6}[oct_] | (0x10 if s.get("bits", 8) == 16 else 0)
out += struct.pack(">Ih", len(s["data"]), typ) + s["data"]
align()
smp_arr = len(out)
for p in inst_ptrs:
out += struct.pack(">I", p)
# play sequences (MMD2 / 3)
seq_info = None
if version >= 2:
align()
psq = []
for sq in [sequence]:
psq.append(len(out))
out += name("seq", 32) + struct.pack(">IIH", 0, 0, len(sq)) + b"".join(struct.pack(">H", b) for b in sq)
align()
ps_table = len(out)
for p in psq:
out += struct.pack(">I", p)
sec_table = len(out)
secs = sections or [0]
for sc in secs:
out += struct.pack(">H", sc)
align()
tv = len(out)
out += bytes(trackvols or [64] * len(blocks[0][0]))
tp = 0
if pans:
tp = len(out)
out += bytes([p & 255 for p in pans])
seq_info = (ps_table, sec_table, tv, tp, len(secs))
# expansion: instrument extras + song name
exp = 0
if need_ext:
align()
ie = len(out)
for s in samples:
ls, ll = s.get("loop") or (0, 0)
out += struct.pack(">BBBbBBHBBIIBBH", s.get("hold", 0), s.get("decay", 0), 0, s.get("finetune", 0), 0,
1 if s.get("loop") else 0, 0, 0, 0, ls, ll, 127, 0, 0)
nm = (title or "").encode() + b"\0"
na = len(out)
out += nm
align()
exp = len(out)
e = bytearray(80)
struct.pack_into(">IIHH", e, 0, 0, ie, len(samples), 22)
struct.pack_into(">II", e, 44, na, len(nm))
out += e
# the song header
for i, s in enumerate(samples):
ls, ll = s.get("loop") or (0, 0)
struct.pack_into(">HHBBBb", out, song_at + 8 * i, ls // 2, ll // 2, 0, 0, s.get("volume", 64), s.get("transpose", 0))
sh = song_at + 63 * 8
if version < 2:
struct.pack_into(">HH", out, sh, len(blocks), len(sequence))
out[sh + 4:sh + 4 + len(sequence)] = bytes(sequence)
else:
ps_table, sec_table, tv, tp, nsec = seq_info
struct.pack_into(">HH", out, sh, len(blocks), nsec)
struct.pack_into(">IIIHHIIHH", out, sh + 4, ps_table, sec_table, tv, len(blocks[0][0]), 1, tp, 0, 100, 0)
struct.pack_into(">HbBBB", out, sh + 260, tempo, play_transpose, flags, flags2, tempo2)
out[sh + 266:sh + 282] = bytes((trackvols or [64] * 16)[:16]) + bytes(max(0, 16 - len(trackvols or [0] * 16)))
out[sh + 282] = master
out[sh + 283] = len(samples)
hdr = bytearray(b"MMD" + bytes([0x30 + version]))
hdr += struct.pack(">IIHHIB3sIIII11sB", len(out), song_at, 0, 0, block_arr, 0, b"\0\0\0", smp_arr, 0, exp, 0, b"\0" * 11, 0)
out[0:52] = hdr
return bytes(out)
+113
View File
@@ -0,0 +1,113 @@
# MED fixtures (tools/fixtures.py): generated MED / OctaMED modules (MMD0, MMD1 with instrument extras, MMD2 with a play
# sequence) exercising the effects, rendered by openmpt123.
# tests/gen/med_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
# duration (openmpt's song length) }
import os, sys
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
T = sys.modules.get("_tracker")
if T is None:
import importlib.util
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
T = importlib.util.module_from_spec(_spec)
sys.modules["_tracker"] = T
_spec.loader.exec_module(T)
INPUTS = ["tools/fixtures/_tracker.py"]
def empty(ch, rows=64):
return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)]
def put(p, row, ch, note=0, ins=0, cmd=0, param=0):
p[row][ch] = (note, ins, cmd, param)
def samples(extras=False):
s = [
{"data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)},
{"data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 44, "loop": (0, 64)},
{"data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64), "transpose": -12},
{"data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 60},
{"data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "loop": (0, 32)},
]
if extras:
s[0]["hold"], s[0]["decay"] = 6, 4 # hold / decay: a volume envelope
s[1]["finetune"] = 3
s[4]["hold"], s[4]["decay"] = 2, 0
return s
def song_basic(keep=None, version=0):
a, b = empty(4), empty(4, 32)
mel = [13, 17, 20, 25, 20, 17, 15, 13]
for i in range(16):
put(a, i * 4, 0, mel[i % 8], 1)
put(a, 2, 0, 0, 0, 0x0, 0x37) # arpeggio
put(a, 0, 1, 1, 2)
put(a, 4, 1, 0, 0, 0x1, 0x02)
put(a, 12, 1, 0, 0, 0x2, 0x03)
put(a, 20, 1, 13, 2, 0xC, 0x32) # volume (decimal: 32)
put(a, 24, 1, 0, 0, 0xD, 0x03) # volume slide down (every tick)
put(a, 28, 1, 0, 0, 0xD, 0x20)
put(a, 32, 1, 8, 2, 0x4, 0x34) # vibrato (twice as deep)
put(a, 40, 1, 13, 2)
put(a, 41, 1, 20, 0, 0x3, 0x10) # tone portamento
put(a, 48, 1, 0, 0, 0x5, 0x01)
for r in range(0, 64, 8):
put(a, r, 3, 13, 4, 0xC, 0x64 - r)
put(a, 2, 2, 25, 3)
put(a, 36, 2, 1, 5, 0xF, 0xF2) # delay note
put(a, 44, 2, 1, 5, 0xF, 0xF1) # play twice
put(a, 34, 3, 0, 0, 0x9, 0x04) # secondary speed
put(a, 50, 3, 0, 0, 0xF, 0x90) # tempo 0x90 (BPM 144 / 0.264...)
put(b, 0, 0, 13, 1)
put(b, 8, 1, 20, 2)
put(b, 16, 2, 13, 3, 0x8, 0x40) # panning (8xx)
put(b, 24, 3, 25, 5, 0xF, 0x00) # pattern break
if keep is not None:
for p in (a, b):
for row in p:
for ch in range(4):
if ch not in keep and row[ch][2] not in (0x9, 0xF):
row[ch] = (0, 0, 0, 0)
return T.write_med(version, samples(version > 0), [a, b], [0, 1, 0], tempo=0x21 if version == 0 else 125, tempo2=6,
flags=0x10 if version > 0 else 0, flags2=0x23 if version > 0 else 0, title="med test" if version > 0 else None)
def song_mmd2():
"""MMD2: 6 tracks, a play sequence with a section, ProTracker-style slides, BPM tempo, track volumes"""
a = empty(6, 48)
for r in range(0, 48, 4):
put(a, r, r // 4 % 6, 13 + (r // 4) % 12, 1 + r // 4 % 5)
put(a, 6, 1, 0, 0, 0x1, 0x04)
put(a, 10, 2, 0, 0, 0xD, 0x02)
put(a, 20, 4, 0, 0, 0x16, 0x00) # loop start
put(a, 23, 4, 0, 0, 0x16, 0x01) # loop once
put(a, 30, 5, 0, 0, 0x1F, 0x20) # note delay 2
put(a, 44, 0, 0, 0, 0x1D, 0x08) # break to row 8 (hex)
b = empty(6, 16)
put(b, 0, 0, 25, 2, 0x0C, 0x20)
put(b, 8, 3, 30, 4)
return T.write_med(2, samples(), [a, b], [0, 1], tempo=120, tempo2=5, flags=0x20 | 0x10, flags2=0x20 | 3,
trackvols=[64, 48, 64, 32, 64, 64])
def song_octaves():
"""MMD1 with an IFF 3-octave sample (three copies of a waveform, each twice as long as the last): a keymap"""
w = T.s8(T.synth("saw", 32, 32, 0.7)) + T.s8(T.synth("saw", 64, 64, 0.7)) + T.s8(T.synth("saw", 128, 128, 0.7))
smp = [{"data": w, "volume": 64, "octaves": 3, "loop": (0, 32)}, samples()[0]]
a = empty(2, 48)
for i, n in enumerate([1, 8, 13, 20, 25, 32, 37, 30, 18, 6, 13, 25]):
put(a, i * 4, 0, n, 1)
put(a, i * 4 + 2, 1, n, 2, 0xC, 0x20)
return T.write_med(1, smp, [a], [0], tempo=125, tempo2=6, flags=0x10, flags2=0x23)
def generate(ctx):
cases = []
for nm, data in (("mmd0", song_basic()), ("mmd1", song_basic(version=1)), ("mmd2", song_mmd2()), ("octaves", song_octaves())):
ref = T.reference(ctx, data, "med")
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
ctx.emit("med_cases", cases)