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

+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