rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -0,0 +1,53 @@
|
||||
--!strict
|
||||
-- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples:
|
||||
-- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs).
|
||||
-- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel
|
||||
-- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's
|
||||
-- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's.
|
||||
-- Not supported: writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Hively = require("@rosetta/codecs/audio/Hively")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ahx = {
|
||||
name = "ahx",
|
||||
category = "music",
|
||||
extensions = { "ahx", "thx" },
|
||||
mime = { "audio/x-ahx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, stereo (0..4), loop, maxDuration
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ahx.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m and #m == 4 and string.sub(m, 1, 3) == "THX" and string.byte(m, 4) < 3 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?)
|
||||
local tune, err = Hively.parse(r.buf, r.base, r.limit)
|
||||
if not tune or tune.format ~= "ahx" then
|
||||
return nil, err or Err.new(Err.CORRUPT, "not an AHX module")
|
||||
end
|
||||
return Hively.module(tune), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions)
|
||||
function Ahx.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
local song, err = Ahx.decode(r)
|
||||
if not song then
|
||||
return nil, err
|
||||
end
|
||||
return Hively.decoder((song :: any).tune, opts)
|
||||
end
|
||||
|
||||
return Ahx
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -0,0 +1,273 @@
|
||||
--!strict
|
||||
-- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header)
|
||||
-- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the
|
||||
-- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE
|
||||
-- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per
|
||||
-- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker
|
||||
-- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a
|
||||
-- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP
|
||||
-- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the
|
||||
-- tracks apply on top. Renders through codecs/audio/MidiRender.
|
||||
-- Not supported: writing; HMP branch tables (skipped).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Render = require("@rosetta/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Hmp = {
|
||||
name = "hmp",
|
||||
category = "music",
|
||||
extensions = { "hmp", "hmi" },
|
||||
mime = { "audio/x-hmp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true, hmi = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxEvents: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local HMI_MAGIC = "HMI-MIDISONG061595"
|
||||
|
||||
function Hmp.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(8) == "HMIMIDIP" or r:peek(18) == HMI_MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 }
|
||||
local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
|
||||
|
||||
-- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set;
|
||||
-- otherwise the MIDI encoding
|
||||
local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number)
|
||||
local v, shift = 0, 1
|
||||
for _ = 1, 5 do
|
||||
if p >= e then
|
||||
return nil, p
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if hmp then
|
||||
v += (c % 128) * shift
|
||||
shift *= 128
|
||||
if c >= 128 then
|
||||
return v, p
|
||||
end
|
||||
else
|
||||
v = v * 128 + c % 128
|
||||
if c < 128 then
|
||||
return v, p
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil, p
|
||||
end
|
||||
|
||||
local function bytes(b: buffer, p: number, n: number): { number }
|
||||
local t: { number } = table.create(n) :: { number }
|
||||
for i = 1, n do
|
||||
t[i] = readu8(b, p + i - 1)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
type Ctx = { loops: number, budget: number }
|
||||
|
||||
-- one track [p, e) -> events (note-offs merged in) | nil, message
|
||||
local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?)
|
||||
local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {}
|
||||
local tick, running = 0, 0
|
||||
while p < e do
|
||||
local d, q = delta(b, p, e, hmp)
|
||||
if not d then
|
||||
break -- (a track cut inside its last delta: keep what was read)
|
||||
end
|
||||
tick += d
|
||||
p = q
|
||||
if p >= e then
|
||||
return nil, "truncated event"
|
||||
end
|
||||
local st = readu8(b, p)
|
||||
if st == 0xFE and not hmp then
|
||||
-- HMI-only events: FE 10 (with a length at +4), FE 15, others 4 bytes
|
||||
local n = 4
|
||||
if p + 1 < e and readu8(b, p + 1) == 0x10 then
|
||||
n = if p + 4 < e then readu8(b, p + 4) + 9 else e - p + 1
|
||||
elseif p + 1 < e and readu8(b, p + 1) == 0x15 then
|
||||
n = 8
|
||||
end
|
||||
if p + n > e then
|
||||
return nil, "truncated FE event"
|
||||
end
|
||||
p += n
|
||||
elseif st == 0xFF then
|
||||
local kind = if p + 1 < e then readu8(b, p + 1) else -1
|
||||
local n, r = delta(b, p + 2, e, false)
|
||||
if kind < 0 or not n or r + n > e then
|
||||
return nil, "truncated meta event"
|
||||
end
|
||||
if kind == 0x2F then
|
||||
break
|
||||
end
|
||||
table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, r, n) })
|
||||
p = r + n
|
||||
elseif st == 0xF0 or st == 0xF7 then
|
||||
local n, r = delta(b, p + 1, e, false)
|
||||
if not n or r + n > e then
|
||||
return nil, "truncated sysex"
|
||||
end
|
||||
table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, r, n) })
|
||||
p = r + n
|
||||
running = 0
|
||||
else
|
||||
if st >= 0x80 then
|
||||
if st >= 0xF0 then
|
||||
return nil, string.format("unexpected status byte 0x%02X", st)
|
||||
end
|
||||
running = st
|
||||
p += 1
|
||||
elseif running == 0 then
|
||||
return nil, "running status without a status byte"
|
||||
end
|
||||
local hi, ch = running // 16, running % 16
|
||||
local n = DATA[hi]
|
||||
if p + n > e then
|
||||
return nil, "truncated event"
|
||||
end
|
||||
local data = bytes(b, p, n)
|
||||
p += n
|
||||
if hmp and hi == 11 and (data[1] == 110 or data[1] == 111) and data[2] > 127 then
|
||||
ctx.loops += 1
|
||||
else
|
||||
for i = 1, n do
|
||||
data[i] %= 128
|
||||
end
|
||||
table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = data })
|
||||
end
|
||||
if hi == 9 and not hmp then
|
||||
local dur, r = delta(b, p, e, false)
|
||||
if not dur then
|
||||
return nil, "truncated note duration"
|
||||
end
|
||||
p = r
|
||||
table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { data[1], 64 } } })
|
||||
end
|
||||
end
|
||||
ctx.budget -= 1
|
||||
if ctx.budget < 0 then
|
||||
return nil, "limit: too many events"
|
||||
end
|
||||
end
|
||||
-- (notes still sounding at the end of an HMI track keep their full duration, as wildmidi plays them)
|
||||
local out = Render.merge(list, offs)
|
||||
table.insert(out, { tick = math.max(tick, if #out > 0 then out[#out].tick else 0), type = "meta", meta = 0x2F, data = {} })
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- the chunk table -> { { start, stop } } track ranges | nil, message, kind
|
||||
local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?)
|
||||
local new = buffer.readstring(b, base + 8, 6) == "013195"
|
||||
local n = readu32(b, base + 0x30)
|
||||
local p = base + (if new then 0x388 else 0x308)
|
||||
if n == 0 or n > 256 then
|
||||
return nil, string.format("bad track count %d", n), nil
|
||||
end
|
||||
local ranges = {}
|
||||
for _ = 1, n do
|
||||
if p + 12 > limit then
|
||||
return nil, "truncated chunk header", "truncated"
|
||||
end
|
||||
local len = readu32(b, p + 4)
|
||||
if len < 12 or p + len > limit then
|
||||
return nil, "truncated chunk", "truncated"
|
||||
end
|
||||
table.insert(ranges, { p + 12, p + len })
|
||||
p += len
|
||||
end
|
||||
return ranges, nil, nil
|
||||
end
|
||||
|
||||
local function hmiTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?)
|
||||
local n = readu8(b, base + 228)
|
||||
if n == 0 then
|
||||
return nil, "no tracks", nil
|
||||
end
|
||||
if base + 370 + n * 4 > limit then
|
||||
return nil, "truncated track table", "truncated"
|
||||
end
|
||||
local ranges, heads = {}, {}
|
||||
for i = 0, n - 1 do
|
||||
local at = base + readu32(b, base + 370 + i * 4)
|
||||
if at < base or at + 0x5B > limit or buffer.readstring(b, at, 13) ~= "HMI-MIDITRACK" then
|
||||
return nil, string.format("bad track %d header", i), nil
|
||||
end
|
||||
local start = at + readu32(b, at + 0x57)
|
||||
if start >= limit then
|
||||
return nil, "truncated track", "truncated"
|
||||
end
|
||||
table.insert(ranges, { start, limit })
|
||||
table.insert(heads, at)
|
||||
end
|
||||
-- a track ends where the next track header starts (or at the end of the file)
|
||||
for _, rg in ranges do
|
||||
for _, h in heads do
|
||||
if h >= rg[1] and h < rg[2] then
|
||||
rg[2] = h
|
||||
end
|
||||
end
|
||||
end
|
||||
return ranges, nil, nil
|
||||
end
|
||||
|
||||
function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
local hmi = r:peek(18) == HMI_MAGIC
|
||||
if not hmi and r:peek(8) ~= "HMIMIDIP" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an HMP / HMI file")
|
||||
end
|
||||
if limit - base < (if hmi then 371 else 0x40) then
|
||||
return nil, Err.new(Err.TRUNCATED, "truncated header")
|
||||
end
|
||||
local rate = if hmi then readu8(b, base + 212) else readu32(b, base + 0x38)
|
||||
if rate == 0 or rate > 100000 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad tick rate " .. rate)
|
||||
end
|
||||
local ranges, msg, kind = (if hmi then hmiTracks else hmpTracks)(b, base, limit)
|
||||
if not ranges then
|
||||
return nil, Err.from(msg :: string, nil, kind)
|
||||
end
|
||||
local ctx: Ctx = { loops = 0, budget = (opts and opts.maxEvents) or 2 ^ 24 }
|
||||
local midi = Types.Midi.new(60)
|
||||
for i, rg in ranges do
|
||||
local evs, err = track(b, rg[1], rg[2], not hmi, ctx)
|
||||
if not evs then
|
||||
return nil, Err.from(err :: string, rg[1])
|
||||
end
|
||||
if i == 1 then
|
||||
local us = math.min(60000000 // rate, 0xFFFFFF)
|
||||
table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = { us // 65536, (us // 256) % 256, us % 256 } })
|
||||
end
|
||||
midi.tracks[i] = { events = evs }
|
||||
end
|
||||
local version = if hmi then "hmi" elseif buffer.readstring(b, base + 8, 6) == "013195" then "013195" else "hmp"
|
||||
Render.attach(midi, { format = if hmi then "hmi" else "hmp", version = version, rate = rate, loops = ctx.loops })
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
|
||||
function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Hmp.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
return Hmp
|
||||
@@ -0,0 +1,53 @@
|
||||
--!strict
|
||||
-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns,
|
||||
-- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module-
|
||||
-- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with
|
||||
-- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer
|
||||
-- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's.
|
||||
-- Not supported: writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Hively = require("@rosetta/codecs/audio/Hively")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Hvl = {
|
||||
name = "hvl",
|
||||
category = "music",
|
||||
extensions = { "hvl" },
|
||||
mime = { "audio/x-hvl" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, loop, maxDuration (stereo: the file's)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Hvl.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m and #m == 4 and string.sub(m, 1, 3) == "HVL" and string.byte(m, 4) <= 1 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?)
|
||||
local tune, err = Hively.parse(r.buf, r.base, r.limit)
|
||||
if not tune or tune.format ~= "hvl" then
|
||||
return nil, err or Err.new(Err.CORRUPT, "not an HVL module")
|
||||
end
|
||||
return Hively.module(tune), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions)
|
||||
function Hvl.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
local song, err = Hvl.decode(r)
|
||||
if not song then
|
||||
return nil, err
|
||||
end
|
||||
return Hively.decoder((song :: any).tune, opts)
|
||||
end
|
||||
|
||||
return Hvl
|
||||
@@ -0,0 +1,120 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit).
|
||||
-- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of
|
||||
-- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods.
|
||||
--
|
||||
-- Never throws: every read is bounds-checked; corrupt streams return nil, message.
|
||||
local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32
|
||||
|
||||
local Itsex = {}
|
||||
|
||||
-- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message
|
||||
function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string)
|
||||
local out = buffer.create(frames * 4)
|
||||
local blockLen = if bits == 16 then 0x4000 else 0x8000
|
||||
local topWidth = if bits == 16 then 17 else 9
|
||||
local fetchA = if bits == 16 then 4 else 3
|
||||
local lowerB = if bits == 16 then -8 else -4
|
||||
local upperB = if bits == 16 then 7 else 3
|
||||
local scale = if bits == 16 then 1 / 32768 else 1 / 128
|
||||
local wrap = if bits == 16 then 65536 else 256
|
||||
local half = wrap // 2
|
||||
local p = off
|
||||
local done = 0
|
||||
while done < frames do
|
||||
if p + 2 > limit then
|
||||
return nil, "compressed sample truncated"
|
||||
end
|
||||
local clen = readu16(buf, p)
|
||||
p += 2
|
||||
local bstart = p
|
||||
local bend = p + clen
|
||||
if bend > limit then
|
||||
return nil, "compressed block runs past the end"
|
||||
end
|
||||
p = bend
|
||||
-- bit reader over [bstart, bend)
|
||||
local bytePos = bstart
|
||||
local bitBuf = 0
|
||||
local bitCount = 0
|
||||
local function readBits(n: number): number
|
||||
while bitCount < n do
|
||||
if bytePos >= bend then
|
||||
return -1
|
||||
end
|
||||
bitBuf += readu8(buf, bytePos) * 2 ^ bitCount
|
||||
bytePos += 1
|
||||
bitCount += 8
|
||||
end
|
||||
local v = bitBuf % 2 ^ n
|
||||
bitBuf = (bitBuf - v) / 2 ^ n
|
||||
bitCount -= n
|
||||
return v
|
||||
end
|
||||
local count = math.min(blockLen, frames - done)
|
||||
local width = topWidth
|
||||
local d1, d2 = 0, 0
|
||||
local i = 0
|
||||
while i < count do
|
||||
if width < 1 or width > topWidth then
|
||||
return nil, "bad bit width"
|
||||
end
|
||||
local v = readBits(width)
|
||||
if v < 0 then
|
||||
return nil, "compressed block ends early"
|
||||
end
|
||||
if width < 7 then
|
||||
-- method A: a marker value, then the new width in fetchA bits
|
||||
if v == 2 ^ (width - 1) then
|
||||
local nw = readBits(fetchA)
|
||||
if nw < 0 then
|
||||
return nil, "compressed block ends early"
|
||||
end
|
||||
nw += 1
|
||||
width = if nw < width then nw else nw + 1
|
||||
continue
|
||||
end
|
||||
elseif width < topWidth then
|
||||
-- method B: values just below the top of the range encode the new width
|
||||
local border = bit32.rshift(if bits == 16 then 0xFFFF else 0xFF, topWidth - width) + lowerB
|
||||
if v > border and v <= border + (upperB - lowerB + 1) then
|
||||
local nw = v - border
|
||||
width = if nw < width then nw else nw + 1
|
||||
continue
|
||||
end
|
||||
else
|
||||
-- method C: the top bit flags a width change
|
||||
if v >= wrap then
|
||||
width = (v + 1) % 256
|
||||
continue
|
||||
end
|
||||
end
|
||||
-- a delta, sign-extended from its width
|
||||
local x = v
|
||||
if width < topWidth then
|
||||
local shift = 2 ^ width
|
||||
if x >= shift / 2 then
|
||||
x -= shift
|
||||
end
|
||||
else
|
||||
x = v % wrap
|
||||
if x >= half then
|
||||
x -= wrap
|
||||
end
|
||||
end
|
||||
d1 = (d1 + x + half) % wrap - half
|
||||
local s = d1
|
||||
if it215 then
|
||||
d2 = (d2 + d1 + half) % wrap - half
|
||||
s = d2
|
||||
end
|
||||
writef32(out, (done + i) * 4, s * scale)
|
||||
i += 1
|
||||
end
|
||||
done += count
|
||||
end
|
||||
return out, p - off
|
||||
end
|
||||
|
||||
return Itsex
|
||||
@@ -0,0 +1,427 @@
|
||||
--!strict
|
||||
-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the
|
||||
-- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to
|
||||
-- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or
|
||||
-- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation,
|
||||
-- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo
|
||||
-- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message.
|
||||
-- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's
|
||||
-- extension chunks (plugins, extended instrument properties), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Itsex = require("@rosetta/music/it/Itsex")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local It = {
|
||||
name = "it",
|
||||
category = "music",
|
||||
extensions = { "it" },
|
||||
mime = { "audio/it", "audio/x-it" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function It.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "IMPM" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the 82-byte envelope of a new-format instrument
|
||||
local function readEnvelope(r: Bytes.Reader, kind: string): any
|
||||
local flags, n = r:u8(), r:u8()
|
||||
local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8()
|
||||
local e = Tracker.newEnvelope()
|
||||
n = math.min(n, 25)
|
||||
for i = 1, 25 do
|
||||
local y, x = r:i8(), r:u16le()
|
||||
if i <= n then
|
||||
e.ticks[i] = x
|
||||
e.values[i] = if kind == "vol" then math.clamp(y, 0, 64) else math.clamp(y, -32, 32)
|
||||
end
|
||||
end
|
||||
r:skip(1)
|
||||
e.enabled = bit32.band(flags, 1) ~= 0 and n > 0
|
||||
e.loop = bit32.band(flags, 2) ~= 0
|
||||
e.sustain = bit32.band(flags, 4) ~= 0
|
||||
e.carry = bit32.band(flags, 8) ~= 0
|
||||
e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0
|
||||
e.loopStart, e.loopEnd = lb + 1, le + 1
|
||||
e.susStart, e.susEnd = sb + 1, se + 1
|
||||
return e
|
||||
end
|
||||
|
||||
local function readInstrument(r: Bytes.Reader, old: boolean): (any?, string?)
|
||||
if r:string(4) ~= "IMPI" then
|
||||
return nil, "bad instrument signature"
|
||||
end
|
||||
local ins = Tracker.newInstrument()
|
||||
r:skip(13)
|
||||
if old then
|
||||
-- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512
|
||||
local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
|
||||
r:skip(2)
|
||||
ins.fadeout = r:u16le() * 2
|
||||
ins.nna = r:u8()
|
||||
ins.dct = if r:u8() ~= 0 then 1 else 0
|
||||
r:skip(4)
|
||||
ins.name = r:fixed(26)
|
||||
r:skip(6)
|
||||
for n = 1, 120 do
|
||||
local note, smp = r:u8(), r:u8()
|
||||
ins.noteMap[n] = math.clamp(note + 1, 1, 120)
|
||||
ins.sampleMap[n] = smp
|
||||
end
|
||||
r:skip(200)
|
||||
local e = Tracker.newEnvelope()
|
||||
for i = 1, 25 do
|
||||
local t, v = r:u8(), r:u8()
|
||||
if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then
|
||||
r:skip((25 - i) * 2)
|
||||
break
|
||||
end
|
||||
table.insert(e.ticks, t)
|
||||
table.insert(e.values, math.min(v, 64))
|
||||
end
|
||||
e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0
|
||||
e.loop = bit32.band(flg, 2) ~= 0
|
||||
e.sustain = bit32.band(flg, 4) ~= 0
|
||||
e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1
|
||||
ins.volEnv = e
|
||||
return ins
|
||||
end
|
||||
ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3
|
||||
ins.fadeout = math.min(r:u16le(), 1024)
|
||||
ins.pps, ins.ppc = r:i8(), r:u8()
|
||||
ins.globalVolume = math.min(r:u8(), 128)
|
||||
local dfp = r:u8()
|
||||
if dfp < 128 then
|
||||
ins.pan = math.min(dfp, 64) * 4
|
||||
end
|
||||
r:skip(2 + 2 + 1 + 1)
|
||||
ins.name = r:fixed(26)
|
||||
local ifc, ifr = r:u8(), r:u8()
|
||||
if ifc >= 128 then
|
||||
ins.cutoff = ifc - 128
|
||||
end
|
||||
if ifr >= 128 then
|
||||
ins.resonance = ifr - 128
|
||||
end
|
||||
r:skip(4)
|
||||
for n = 1, 120 do
|
||||
local note, smp = r:u8(), r:u8()
|
||||
ins.noteMap[n] = math.clamp(note + 1, 1, 120)
|
||||
ins.sampleMap[n] = smp
|
||||
end
|
||||
ins.volEnv = readEnvelope(r, "vol")
|
||||
ins.panEnv = readEnvelope(r, "pan")
|
||||
ins.pitchEnv = readEnvelope(r, "pitch")
|
||||
if r.err then
|
||||
return nil, "instrument truncated"
|
||||
end
|
||||
return ins
|
||||
end
|
||||
|
||||
function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 28
|
||||
if r:peek(4) ~= "IMPM" then
|
||||
return nil, Err.new(Err.CORRUPT, "no IMPM signature")
|
||||
end
|
||||
r:skip(4)
|
||||
local title = r:fixed(26)
|
||||
r:skip(2)
|
||||
local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
|
||||
local msgLen, msgOff = r:u16le(), r:u32le()
|
||||
r:skip(4)
|
||||
local chnPan, chnVol = {}, {}
|
||||
for i = 1, 64 do
|
||||
chnPan[i] = r:u8()
|
||||
end
|
||||
for i = 1, 64 do
|
||||
chnVol[i] = r:u8()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header counts")
|
||||
end
|
||||
local orders = {}
|
||||
for i = 1, ordnum do
|
||||
orders[i] = r:u8()
|
||||
end
|
||||
local insOff, smpOff, patOff = {}, {}, {}
|
||||
for i = 1, insnum do
|
||||
insOff[i] = r:u32le()
|
||||
end
|
||||
for i = 1, smpnum do
|
||||
smpOff[i] = r:u32le()
|
||||
end
|
||||
for i = 1, patnum do
|
||||
patOff[i] = r:u32le()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
-- channels: the highest one any pattern uses
|
||||
local nch = 1
|
||||
local packed: { Bytes.Reader? } = {}
|
||||
local rowsOf: { number } = {}
|
||||
for p = 1, patnum do
|
||||
if patOff[p] > 0 then
|
||||
local pr = r:sub(patOff[p])
|
||||
local len, rows = pr:u16le(), pr:u16le()
|
||||
pr:skip(4)
|
||||
if pr.err or rows < 1 or rows > 1024 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p])
|
||||
end
|
||||
local data = pr:slice(len)
|
||||
packed[p], rowsOf[p] = data, rows
|
||||
-- scan for the channel count
|
||||
local scan = data:sub(0)
|
||||
local seen: { [number]: number } = {}
|
||||
while not scan:eof() do
|
||||
local cv = scan:u8()
|
||||
if cv == 0 then
|
||||
continue
|
||||
end
|
||||
local ch = (cv - 1) % 64
|
||||
nch = math.max(nch, ch + 1)
|
||||
local mask = 0
|
||||
if cv >= 128 then
|
||||
mask = scan:u8()
|
||||
seen[ch] = mask
|
||||
else
|
||||
mask = seen[ch] or 0
|
||||
end
|
||||
if bit32.band(mask, 1) ~= 0 then
|
||||
scan:skip(1)
|
||||
end
|
||||
if bit32.band(mask, 2) ~= 0 then
|
||||
scan:skip(1)
|
||||
end
|
||||
if bit32.band(mask, 4) ~= 0 then
|
||||
scan:skip(1)
|
||||
end
|
||||
if bit32.band(mask, 8) ~= 0 then
|
||||
scan:skip(2)
|
||||
end
|
||||
end
|
||||
else
|
||||
rowsOf[p] = 64
|
||||
end
|
||||
end
|
||||
local m = Tracker.newModule("it", nch)
|
||||
m.title = title
|
||||
m.speed = if speed > 0 then speed else 6
|
||||
m.tempo = if tempo >= 31 then tempo else 125
|
||||
m.globalVolume = math.min(gv, 128)
|
||||
m.mixVolume = math.min(mv, 128)
|
||||
m.linear = bit32.band(flags, 8) ~= 0
|
||||
m.instrumentMode = bit32.band(flags, 4) ~= 0
|
||||
m.flags.oldEffects = bit32.band(flags, 16) ~= 0
|
||||
m.flags.compatGxx = bit32.band(flags, 32) ~= 0
|
||||
local stereo = bit32.band(flags, 1) ~= 0
|
||||
for i = 1, nch do
|
||||
local p = chnPan[i]
|
||||
if p >= 128 then
|
||||
m.channelMute[i] = true
|
||||
p -= 128
|
||||
end
|
||||
if not stereo then
|
||||
m.channelPan[i] = 128
|
||||
elseif p == 100 then
|
||||
m.channelPan[i] = 512
|
||||
else
|
||||
m.channelPan[i] = math.min(p, 64) * 4
|
||||
end
|
||||
m.channelVolume[i] = math.min(chnVol[i], 64)
|
||||
end
|
||||
for i = 1, ordnum do
|
||||
if orders[i] == 255 then
|
||||
break
|
||||
end
|
||||
table.insert(m.order, orders[i])
|
||||
end
|
||||
m.meta.source = { format = "it", tracker = cwt, compatible = cmwt }
|
||||
if bit32.band(special, 1) ~= 0 and msgLen > 0 then
|
||||
local mr = r:sub(msgOff, msgLen)
|
||||
m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n")
|
||||
end
|
||||
-- instruments
|
||||
for i = 1, insnum do
|
||||
local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200)
|
||||
if not ins then
|
||||
return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i])
|
||||
end
|
||||
m.instruments[i] = ins
|
||||
end
|
||||
-- samples
|
||||
local total = 0
|
||||
for i = 1, smpnum do
|
||||
local h = r:sub(smpOff[i], 80)
|
||||
if h:string(4) ~= "IMPS" then
|
||||
return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i])
|
||||
end
|
||||
h:skip(13)
|
||||
local s = Tracker.newSample()
|
||||
m.samples[i] = s
|
||||
local gvl, flg, vol = h:u8(), h:u8(), h:u8()
|
||||
s.name = h:fixed(26)
|
||||
local cvt, dfp = h:u8(), h:u8()
|
||||
local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le()
|
||||
local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8()
|
||||
if h.err then
|
||||
return nil, Err.new(Err.TRUNCATED, "sample header " .. i)
|
||||
end
|
||||
s.globalVolume = math.min(gvl, 64)
|
||||
s.volume = math.min(vol, 64)
|
||||
if dfp >= 128 then
|
||||
s.pan = math.min(dfp - 128, 64) * 4
|
||||
end
|
||||
s.c5speed = if c5 > 0 then c5 else 8363
|
||||
s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4
|
||||
local bits = if bit32.band(flg, 2) ~= 0 then 16 else 8
|
||||
local nchs = if bit32.band(flg, 4) ~= 0 then 2 else 1
|
||||
s.bits = bits
|
||||
if bit32.band(flg, 1) ~= 0 and len > 0 then
|
||||
len = math.min(len, 2 ^ 26)
|
||||
total += len * nchs * 4
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
local data: buffer? = nil
|
||||
if bit32.band(flg, 8) ~= 0 then
|
||||
-- compressed: each channel separately
|
||||
local it215 = bit32.band(cvt, 4) ~= 0
|
||||
local p = r.base + ptr
|
||||
local parts = {}
|
||||
for c = 1, nchs do
|
||||
local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215)
|
||||
if not d then
|
||||
return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used))
|
||||
end
|
||||
parts[c] = d
|
||||
p += used :: number
|
||||
end
|
||||
if nchs == 1 then
|
||||
data = parts[1]
|
||||
else
|
||||
local inter = buffer.create(len * 8)
|
||||
for f = 0, len - 1 do
|
||||
buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4))
|
||||
buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4))
|
||||
end
|
||||
data = inter
|
||||
end
|
||||
else
|
||||
local bps = bits // 8
|
||||
local avail = math.max(0, r:size() - ptr) // (bps * nchs)
|
||||
len = math.min(len, avail)
|
||||
data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, {
|
||||
bits = bits,
|
||||
signed = bit32.band(cvt, 1) ~= 0,
|
||||
bigEndian = bit32.band(cvt, 2) ~= 0,
|
||||
delta = bit32.band(cvt, 4) ~= 0,
|
||||
channels = nchs,
|
||||
planar = true,
|
||||
})
|
||||
end
|
||||
if data then
|
||||
s.data, s.length, s.channels = data, len, nchs
|
||||
if bit32.band(flg, 16) ~= 0 then
|
||||
s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), if bit32.band(flg, 64) ~= 0 then 2 else 1
|
||||
end
|
||||
if bit32.band(flg, 32) ~= 0 then
|
||||
s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), if bit32.band(flg, 128) ~= 0 then 2 else 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- patterns
|
||||
for p = 1, patnum do
|
||||
local pat = Tracker.newPattern(rowsOf[p], nch)
|
||||
m.patterns[p] = pat
|
||||
local pr = packed[p]
|
||||
if pr then
|
||||
local d = pat.data
|
||||
local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {}
|
||||
local row = 0
|
||||
while row < pat.rows and not pr:eof() do
|
||||
local cv = pr:u8()
|
||||
if cv == 0 then
|
||||
row += 1
|
||||
continue
|
||||
end
|
||||
local ch = (cv - 1) % 64
|
||||
local mask = if cv >= 128 then pr:u8() else (lastMask[ch] or 0)
|
||||
lastMask[ch] = mask
|
||||
local note, ins, vol, fx, param = 0, 0, 0, 0, 0
|
||||
if bit32.band(mask, 1) ~= 0 then
|
||||
local n = pr:u8()
|
||||
-- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing
|
||||
note = if n < 120 then n + 1 elseif n == 255 then 255 elseif n == 254 then 254 elseif n == 246 then 253 else 0
|
||||
lastNote[ch] = note
|
||||
elseif bit32.band(mask, 16) ~= 0 then
|
||||
note = lastNote[ch] or 0
|
||||
end
|
||||
if bit32.band(mask, 2) ~= 0 then
|
||||
ins = pr:u8()
|
||||
lastIns[ch] = ins
|
||||
elseif bit32.band(mask, 32) ~= 0 then
|
||||
ins = lastIns[ch] or 0
|
||||
end
|
||||
if bit32.band(mask, 4) ~= 0 then
|
||||
vol = math.min(pr:u8(), 212) + 1
|
||||
lastVol[ch] = vol
|
||||
elseif bit32.band(mask, 64) ~= 0 then
|
||||
vol = lastVol[ch] or 0
|
||||
end
|
||||
if bit32.band(mask, 8) ~= 0 then
|
||||
fx, param = pr:u8(), pr:u8()
|
||||
if fx > 26 then
|
||||
fx, param = 0, 0
|
||||
end
|
||||
lastFx[ch], lastParam[ch] = fx, param
|
||||
elseif bit32.band(mask, 128) ~= 0 then
|
||||
fx, param = lastFx[ch] or 0, lastParam[ch] or 0
|
||||
end
|
||||
if ch < nch then
|
||||
local o = (row * nch + ch) * 5
|
||||
buffer.writeu8(d, o, note)
|
||||
buffer.writeu8(d, o + 1, ins)
|
||||
buffer.writeu8(d, o + 2, vol)
|
||||
buffer.writeu8(d, o + 3, fx)
|
||||
buffer.writeu8(d, o + 4, param)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
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 It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = It.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return It
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -0,0 +1,418 @@
|
||||
--!strict
|
||||
-- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE
|
||||
-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps
|
||||
-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are
|
||||
-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the
|
||||
-- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track
|
||||
-- has none. Written from the SMF 1.0 specification (no third-party code).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Smf = {}
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
|
||||
local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 }
|
||||
Smf.TYPE_STATUS = TYPE_STATUS
|
||||
|
||||
export type ReadOptions = {
|
||||
strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated)
|
||||
maxEvents: number?, -- default 2^24
|
||||
}
|
||||
export type WriteOptions = {
|
||||
runningStatus: boolean?, -- default true
|
||||
}
|
||||
|
||||
local function bytesOf(b: buffer, p: number, n: number): { number }
|
||||
local t: { number } = table.create(n) :: { number }
|
||||
for i = 0, n - 1 do
|
||||
t[i + 1] = readu8(b, p + i)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local function text(data: { number }): string
|
||||
local parts = table.create(#data)
|
||||
for i, c in data do
|
||||
parts[i] = string.char(c)
|
||||
end
|
||||
return table.concat(parts)
|
||||
end
|
||||
Smf.text = text
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ read
|
||||
-- one MTrk body [p, e): events | nil, message, truncated
|
||||
local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean)
|
||||
local events: { Types.MidiEvent } = {}
|
||||
local tick = 0
|
||||
local running = 0
|
||||
while p < e do
|
||||
-- delta time
|
||||
local delta, n = 0, 0
|
||||
repeat
|
||||
if p >= e then
|
||||
return events, nil, true
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
n += 1
|
||||
delta = delta * 128 + c % 128
|
||||
if n > 4 then
|
||||
return nil, "delta time longer than 4 bytes", false
|
||||
end
|
||||
until c < 128
|
||||
tick += delta
|
||||
if p >= e then
|
||||
return events, nil, true
|
||||
end
|
||||
local status = readu8(b, p)
|
||||
if status < 0x80 then
|
||||
if running == 0 then
|
||||
return nil, "running status without a previous status byte", false
|
||||
end
|
||||
status = running
|
||||
else
|
||||
p += 1
|
||||
if status < 0xF0 then
|
||||
running = status
|
||||
end
|
||||
end
|
||||
budget[1] -= 1
|
||||
if budget[1] < 0 then
|
||||
return nil, "LIMIT", false
|
||||
end
|
||||
if status == 0xFF or status == 0xF0 or status == 0xF7 then
|
||||
local mtype = 0
|
||||
if status == 0xFF then
|
||||
if p >= e then
|
||||
return events, nil, true
|
||||
end
|
||||
mtype = readu8(b, p)
|
||||
p += 1
|
||||
end
|
||||
local len, m = 0, 0
|
||||
repeat
|
||||
if p >= e then
|
||||
return events, nil, true
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
m += 1
|
||||
len = len * 128 + c % 128
|
||||
if m > 4 then
|
||||
return nil, "length longer than 4 bytes", false
|
||||
end
|
||||
until c < 128
|
||||
if p + len > e then
|
||||
return events, nil, true
|
||||
end
|
||||
local data = bytesOf(b, p, len)
|
||||
p += len
|
||||
if status == 0xFF then
|
||||
table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data })
|
||||
else
|
||||
table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data })
|
||||
end
|
||||
elseif status >= 0xF0 then
|
||||
return nil, string.format("unexpected status byte 0x%02x in a track", status), false
|
||||
else
|
||||
local kind = status // 16
|
||||
local count = if kind == 12 or kind == 13 then 1 else 2
|
||||
if p + count > e then
|
||||
return events, nil, true
|
||||
end
|
||||
local d1 = readu8(b, p)
|
||||
local d2 = if count == 2 then readu8(b, p + 1) else 0
|
||||
if d1 >= 128 or d2 >= 128 then
|
||||
return nil, "data byte over 127", false
|
||||
end
|
||||
p += count
|
||||
table.insert(events, {
|
||||
tick = tick,
|
||||
type = CHANNEL_TYPES[kind],
|
||||
channel = status % 16,
|
||||
data = if count == 2 then { d1, d2 } else { d1 },
|
||||
})
|
||||
end
|
||||
end
|
||||
return events, nil, false
|
||||
end
|
||||
|
||||
-- read(r, opts?) -> Midi | nil, Err
|
||||
function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?)
|
||||
local strict = opts and opts.strict or false
|
||||
local budget = { opts and opts.maxEvents or 2 ^ 24 }
|
||||
local b = r.buf
|
||||
local base, limit = r.base, r.limit
|
||||
local rmid = false
|
||||
-- RIFF RMID: the SMF is the "data" chunk
|
||||
if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then
|
||||
local q = base + 12
|
||||
local found = false
|
||||
while q + 8 <= limit do
|
||||
local id = buffer.readstring(b, q, 4)
|
||||
local size = buffer.readu32(b, q + 4)
|
||||
if id == "data" then
|
||||
base = q + 8
|
||||
limit = math.min(limit, base + size)
|
||||
found = true
|
||||
break
|
||||
end
|
||||
q += 8 + size + size % 2
|
||||
end
|
||||
if not found then
|
||||
return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base)
|
||||
end
|
||||
rmid = true
|
||||
end
|
||||
local h = Bytes.reader(b, base, limit - base)
|
||||
if h:string(4) ~= "MThd" then
|
||||
return nil, Err.new(Err.CORRUPT, "no MThd header", base)
|
||||
end
|
||||
local hlen = h:u32be()
|
||||
local format, ntrks, division = h:u16be(), h:u16be(), h:i16be()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if hlen < 6 then
|
||||
return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4)
|
||||
end
|
||||
if format > 2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8)
|
||||
end
|
||||
if division == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12)
|
||||
end
|
||||
local midi = Types.Midi.new(division)
|
||||
midi.format = format
|
||||
local truncated = false
|
||||
local p = base + 8 + hlen
|
||||
while #midi.tracks < ntrks and p + 8 <= limit do
|
||||
local id = buffer.readstring(b, p, 4)
|
||||
local size = bit32.byteswap(buffer.readu32(b, p + 4))
|
||||
local s = p + 8
|
||||
local e = s + size
|
||||
if e > limit then
|
||||
e = limit
|
||||
truncated = true
|
||||
end
|
||||
if id == "MTrk" then
|
||||
local events, msg, short = readTrack(b, s, e, budget)
|
||||
if not events then
|
||||
if msg == "LIMIT" then
|
||||
return nil, Err.new(Err.LIMIT, "over the event limit")
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, msg or "bad track", s)
|
||||
end
|
||||
truncated = truncated or short
|
||||
local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil }
|
||||
for _, ev in events do
|
||||
if ev.type == "meta" and ev.meta == 3 then
|
||||
track.name = text(ev.data :: { number })
|
||||
break
|
||||
end
|
||||
end
|
||||
table.insert(midi.tracks, track)
|
||||
end
|
||||
p = s + size
|
||||
end
|
||||
if #midi.tracks < ntrks and p < limit then
|
||||
truncated = true
|
||||
elseif #midi.tracks < ntrks then
|
||||
truncated = true
|
||||
end
|
||||
if truncated and strict then
|
||||
return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)")
|
||||
end
|
||||
midi.meta.declaredTracks = ntrks
|
||||
midi.meta.truncated = truncated
|
||||
midi.meta.rmid = rmid
|
||||
if division < 0 then
|
||||
local fps = -(division // 256)
|
||||
midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 }
|
||||
end
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ write
|
||||
local function vlq(w: Bytes.Writer, v: number)
|
||||
if v < 128 then
|
||||
w:u8(v)
|
||||
return
|
||||
end
|
||||
local bytes = {}
|
||||
while v > 0 do
|
||||
table.insert(bytes, 1, v % 128)
|
||||
v = v // 128
|
||||
end
|
||||
for i, c in bytes do
|
||||
w:u8(if i < #bytes then c + 128 else c)
|
||||
end
|
||||
end
|
||||
|
||||
local function byteList(d: any, want: number?): { number }?
|
||||
if type(d) ~= "table" then
|
||||
return if want == 0 then {} else nil
|
||||
end
|
||||
for i, v in d do
|
||||
if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
if want and #d < want then
|
||||
return nil
|
||||
end
|
||||
return d
|
||||
end
|
||||
|
||||
-- write(midi, opts?) -> buffer | nil, Err
|
||||
function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
|
||||
if type(midi) ~= "table" or type(midi.tracks) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Midi value with tracks")
|
||||
end
|
||||
local running = not (opts and opts.runningStatus == false)
|
||||
local format = midi.format or 1
|
||||
local division = midi.division or 480
|
||||
if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "format must be 0, 1 or 2")
|
||||
end
|
||||
if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "division must be a non-zero 16-bit integer")
|
||||
end
|
||||
if format == 0 and #midi.tracks ~= 1 then
|
||||
return nil, Err.new(Err.ARG, "format 0 needs exactly one track")
|
||||
end
|
||||
if #midi.tracks > 65535 then
|
||||
return nil, Err.new(Err.ARG, "too many tracks")
|
||||
end
|
||||
local w = Bytes.writer(1024)
|
||||
w:string("MThd")
|
||||
w:u32be(6)
|
||||
w:u16be(format)
|
||||
w:u16be(#midi.tracks)
|
||||
w:u16be(if division < 0 then division + 65536 else division)
|
||||
for ti, track in midi.tracks do
|
||||
local events = if type(track) == "table" then track.events else nil
|
||||
if type(events) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list")
|
||||
end
|
||||
-- stable order by tick
|
||||
local sorted = true
|
||||
local last = 0
|
||||
for i, ev in events do
|
||||
if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i))
|
||||
end
|
||||
if ev.tick < last then
|
||||
sorted = false
|
||||
end
|
||||
last = ev.tick
|
||||
end
|
||||
local list: { any } = events
|
||||
if not sorted then
|
||||
list = table.clone(events)
|
||||
local order: { [any]: number } = {}
|
||||
for i, ev in list do
|
||||
order[ev] = i
|
||||
end
|
||||
table.sort(list, function(a: any, c: any): boolean
|
||||
if a.tick ~= c.tick then
|
||||
return a.tick < c.tick
|
||||
end
|
||||
return order[a] < order[c]
|
||||
end)
|
||||
end
|
||||
-- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own
|
||||
if type(track.name) == "string" and track.name ~= "" then
|
||||
local named = false
|
||||
for _, ev in list do
|
||||
if ev.type == "meta" and ev.meta == 0x03 then
|
||||
named = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if not named then
|
||||
local bytes = { string.byte(track.name, 1, math.min(#track.name, 4096)) }
|
||||
list = table.clone(list)
|
||||
table.insert(list, 1, { tick = 0, type = "meta", meta = 0x03, data = bytes })
|
||||
end
|
||||
end
|
||||
w:string("MTrk")
|
||||
local lenAt = w:tell()
|
||||
w:u32be(0)
|
||||
local start = w:tell()
|
||||
local prev = 0
|
||||
local status = 0
|
||||
local endTick = 0
|
||||
for i, ev in list do
|
||||
local t = ev.type
|
||||
endTick = ev.tick
|
||||
if t == "meta" and ev.meta == 0x2F then
|
||||
continue -- written once at the end
|
||||
end
|
||||
local delta = ev.tick - prev
|
||||
if delta > 0x0FFFFFFF then
|
||||
return nil, Err.new(Err.ARG, "a delta time over 0x0FFFFFFF ticks")
|
||||
end
|
||||
local base = TYPE_STATUS[t]
|
||||
if base then
|
||||
local ch = ev.channel or 0
|
||||
if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i))
|
||||
end
|
||||
local n = if base == 0xC0 or base == 0xD0 then 1 else 2
|
||||
local d = byteList(ev.data, n)
|
||||
if not d or d[1] > 127 or (n == 2 and d[2] > 127) then
|
||||
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n))
|
||||
end
|
||||
vlq(w, delta)
|
||||
local st = base + ch
|
||||
if not (running and st == status) then
|
||||
w:u8(st)
|
||||
end
|
||||
status = st
|
||||
w:u8(d[1])
|
||||
if n == 2 then
|
||||
w:u8(d[2])
|
||||
end
|
||||
elseif t == "meta" or t == "sysex" or t == "escape" then
|
||||
local d = byteList(ev.data, 0)
|
||||
if not d then
|
||||
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i))
|
||||
end
|
||||
vlq(w, delta)
|
||||
if t == "meta" then
|
||||
local m = ev.meta
|
||||
if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i))
|
||||
end
|
||||
w:u8(0xFF)
|
||||
w:u8(m)
|
||||
else
|
||||
w:u8(if t == "sysex" then 0xF0 else 0xF7)
|
||||
end
|
||||
if #d > 0x0FFFFFFF then
|
||||
return nil, Err.new(Err.ARG, "event data too long")
|
||||
end
|
||||
vlq(w, #d)
|
||||
for _, c in d do
|
||||
w:u8(c)
|
||||
end
|
||||
status = 0
|
||||
else
|
||||
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t)))
|
||||
end
|
||||
prev = ev.tick
|
||||
end
|
||||
vlq(w, math.max(0, endTick - prev))
|
||||
w:u8(0xFF)
|
||||
w:u8(0x2F)
|
||||
w:u8(0)
|
||||
w:setU32be(lenAt, w:tell() - start)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
return Smf
|
||||
@@ -0,0 +1,154 @@
|
||||
--!strict
|
||||
-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the
|
||||
-- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port).
|
||||
-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller /
|
||||
-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length,
|
||||
-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke:
|
||||
-- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to
|
||||
-- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), encode (running
|
||||
-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and
|
||||
-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set.
|
||||
-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Smf = require("@rosetta/music/midi/Smf")
|
||||
local Render = require("@rosetta/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Midi = {
|
||||
name = "midi",
|
||||
category = "music",
|
||||
extensions = { "mid", "midi", "smf", "kar", "rmi" },
|
||||
mime = { "audio/midi", "audio/x-midi" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" },
|
||||
caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24)
|
||||
export type EncodeOptions = Smf.WriteOptions -- runningStatus (default true)
|
||||
export type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Midi.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) == "MThd" then
|
||||
return 1
|
||||
end
|
||||
if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and
|
||||
-- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags
|
||||
local function karaoke(midi: Types.Midi)
|
||||
local lyrics: { { time: number, tick: number, text: string } } = {}
|
||||
local headers: { [string]: { string } } = {}
|
||||
local map = Render.tempoMap(midi)
|
||||
local kar, hasWords = false, false
|
||||
for _, t in midi.tracks do
|
||||
if t.name == "Words" then
|
||||
kar, hasWords = true, true
|
||||
end
|
||||
for _, ev in t.events do
|
||||
if ev.type == "meta" and ev.meta == 1 and type(ev.data) == "table" and ev.data[1] == 64 then
|
||||
local c = ev.data[2]
|
||||
if c == 75 or c == 84 then -- @K, @T
|
||||
kar = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for ti, t in midi.tracks do
|
||||
local tmap = if midi.format == 2 then Render.tempoMap(midi, ti) else map
|
||||
local words = kar and (t.name == "Words" or not hasWords)
|
||||
for _, ev in t.events do
|
||||
if ev.type == "meta" and type(ev.data) == "table" and (ev.meta == 5 or (ev.meta == 1 and words)) then
|
||||
local text = Smf.text(ev.data :: { number })
|
||||
if ev.meta == 1 and string.sub(text, 1, 1) == "@" and #text >= 2 then
|
||||
local key = string.sub(text, 2, 2)
|
||||
local list = headers[key] or {}
|
||||
headers[key] = list
|
||||
table.insert(list, string.sub(text, 3))
|
||||
else
|
||||
table.insert(lyrics, { time = Render.seconds(tmap, ev.tick), tick = ev.tick, text = text })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #lyrics == 0 and next(headers) == nil then
|
||||
return
|
||||
end
|
||||
table.sort(lyrics, function(a: { time: number, tick: number, text: string }, b: { time: number, tick: number, text: string }): boolean
|
||||
return a.time < b.time
|
||||
end)
|
||||
midi.meta.lyrics = lyrics
|
||||
midi.meta.karaoke = headers
|
||||
local tags: { [string]: string } = {}
|
||||
if headers.T then
|
||||
tags.title = headers.T[1]
|
||||
tags.artist = headers.T[2]
|
||||
end
|
||||
if headers.L then
|
||||
tags.language = headers.L[1]
|
||||
end
|
||||
if headers.I then
|
||||
tags.comment = table.concat(headers.I, "\n")
|
||||
end
|
||||
midi.meta.tags = tags
|
||||
end
|
||||
|
||||
function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local midi, err = Smf.read(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
Render.attach(midi, { format = "midi", smf = midi.format })
|
||||
karaoke(midi)
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
return Smf.write(midi, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions)
|
||||
function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Midi.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new)
|
||||
function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map)
|
||||
function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number
|
||||
return Render.seconds(Render.tempoMap(midi, track), tick)
|
||||
end
|
||||
|
||||
-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points)
|
||||
Midi.tempoMap = Render.tempoMap
|
||||
Midi.seconds = Render.seconds
|
||||
|
||||
-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1)
|
||||
function Midi.length(midi: Types.Midi): number
|
||||
return Render.length(midi)
|
||||
end
|
||||
|
||||
-- text(data) -> the bytes of a text meta event as a string
|
||||
Midi.text = Smf.text
|
||||
|
||||
return Midi
|
||||
@@ -0,0 +1,361 @@
|
||||
--!strict
|
||||
-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4,
|
||||
-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or
|
||||
-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through
|
||||
-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod"
|
||||
-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns).
|
||||
-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter
|
||||
-- (E0x), PowerPacker-packed files.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mod = {
|
||||
name = "mod",
|
||||
category = "music",
|
||||
extensions = { "mod", "m15", "stk", "nst" },
|
||||
mime = { "audio/x-mod", "audio/mod" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
caps = { decode = true, encode = true, render = true, channels = { 1, 32 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples)
|
||||
}
|
||||
export type EncodeOptions = {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local Pcm = Tracker.Pcm
|
||||
local Tables = Tracker.Tables
|
||||
|
||||
local FIXED: { [string]: number } = {
|
||||
["M.K."] = 4,
|
||||
["M!K!"] = 4,
|
||||
["M&K!"] = 4,
|
||||
["N.T."] = 4,
|
||||
["FLT4"] = 4,
|
||||
["FLT8"] = 8,
|
||||
["CD81"] = 8,
|
||||
["OKTA"] = 8,
|
||||
["OCTA"] = 8,
|
||||
["EXO4"] = 4,
|
||||
["EXO8"] = 8,
|
||||
}
|
||||
|
||||
-- channels from the 4-byte signature at 1080, or nil
|
||||
local function signatureChannels(sig: string): number?
|
||||
local fixed = FIXED[sig]
|
||||
if fixed then
|
||||
return fixed
|
||||
end
|
||||
local d = string.match(sig, "^(%d)CHN$")
|
||||
if d then
|
||||
local n = tonumber(d) :: number
|
||||
return if n >= 1 then n else nil
|
||||
end
|
||||
local dd = string.match(sig, "^(%d%d)C[HN]$")
|
||||
if dd then
|
||||
local n = tonumber(dd) :: number
|
||||
return if n >= 1 and n <= 32 then n else nil
|
||||
end
|
||||
local t = string.match(sig, "^TDZ(%d)$")
|
||||
if t then
|
||||
local n = tonumber(t) :: number
|
||||
return if n >= 1 then n else nil
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mod.sniff(r: Bytes.Reader): number
|
||||
if r:size() < 1084 then
|
||||
return 0
|
||||
end
|
||||
local sig = r:peek(4, 1080)
|
||||
if signatureChannels(sig) then
|
||||
return 0.8
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 26
|
||||
local size = r:size()
|
||||
local sig = if size >= 1084 then r:peek(4, 1080) else ""
|
||||
local channels = signatureChannels(sig)
|
||||
local nsamples = 31
|
||||
if not channels then
|
||||
-- a 15-sample Soundtracker module (no signature): only when the header is plausible
|
||||
nsamples, channels = 15, 4
|
||||
end
|
||||
local nch = channels :: number
|
||||
local m = Tracker.newModule("mod", nch)
|
||||
m.title = r:fixed(20)
|
||||
local lengths: { number } = {}
|
||||
for i = 1, nsamples do
|
||||
local s = Tracker.newSample(r:fixed(22))
|
||||
local len = r:u16be() * 2
|
||||
local ft = r:u8() % 16
|
||||
local vol = r:u8()
|
||||
local ls = r:u16be() * 2
|
||||
local ll = r:u16be() * 2
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if nsamples == 15 and (vol > 64 or ft ~= 0) then
|
||||
return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)")
|
||||
end
|
||||
s.finetune = (if ft >= 8 then ft - 16 else ft) * 16
|
||||
s.volume = math.min(vol, 64)
|
||||
s.bits = 8
|
||||
if ll > 2 then
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1
|
||||
end
|
||||
lengths[i] = len
|
||||
m.samples[i] = s
|
||||
end
|
||||
local songLength = r:u8()
|
||||
local restart = r:u8()
|
||||
local order: { number } = {}
|
||||
local maxPat = 0
|
||||
for i = 1, 128 do
|
||||
local p = r:u8()
|
||||
order[i] = p
|
||||
maxPat = math.max(maxPat, p)
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if songLength == 0 or songLength > 128 or maxPat >= 128 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)")
|
||||
end
|
||||
if nsamples == 31 then
|
||||
r:skip(4)
|
||||
end
|
||||
for i = 1, songLength do
|
||||
m.order[i] = order[i]
|
||||
end
|
||||
m.restart = if restart < songLength then restart else 0
|
||||
m.meta.signature = if nsamples == 31 then sig else nil
|
||||
m.flags.amigaLimits = nch == 4
|
||||
-- patterns
|
||||
local npat = maxPat + 1
|
||||
local patBytes = 64 * nch * 4
|
||||
if not r:need(npat * patBytes) then
|
||||
return nil, r.err
|
||||
end
|
||||
local buf = r.buf
|
||||
for p = 0, npat - 1 do
|
||||
local pat = Tracker.newPattern(64, nch)
|
||||
local base = r.pos + p * patBytes
|
||||
local d = pat.data
|
||||
for i = 0, 64 * nch - 1 do
|
||||
local o = base + i * 4
|
||||
local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3)
|
||||
local period = (b0 % 16) * 256 + b1
|
||||
local ins = (b0 // 16) * 16 + b2 // 16
|
||||
local q = i * 5
|
||||
buffer.writeu8(d, q, Tables.periodToNote(period))
|
||||
buffer.writeu8(d, q + 1, ins)
|
||||
buffer.writeu8(d, q + 3, b2 % 16)
|
||||
buffer.writeu8(d, q + 4, b3)
|
||||
end
|
||||
m.patterns[p + 1] = pat
|
||||
end
|
||||
r:skip(npat * patBytes)
|
||||
-- sample data (8-bit signed; the last samples of a truncated file are cut short)
|
||||
local total = 0
|
||||
for i = 1, nsamples do
|
||||
local s = m.samples[i]
|
||||
local len = math.min(lengths[i], r:remaining())
|
||||
total += len * 4
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true })
|
||||
if not data then
|
||||
return nil, Err.new(Err.TRUNCATED, "sample data", r.pos)
|
||||
end
|
||||
r:skip(len)
|
||||
s.data, s.length = data, len
|
||||
if s.loopEnd > len then
|
||||
s.loopEnd = len
|
||||
if s.loopEnd - s.loopStart < 2 then
|
||||
s.loopType, s.loopStart, s.loopEnd = 0, 0, 0
|
||||
end
|
||||
end
|
||||
end
|
||||
m.meta.source = { format = "mod", samples = nsamples }
|
||||
m.render = Tracker.renderMethod
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function writeName(w: Bytes.Writer, s: string, n: number)
|
||||
local t = string.sub(s or "", 1, n)
|
||||
w:string(t)
|
||||
w:fill(0, n - #t)
|
||||
end
|
||||
|
||||
-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to
|
||||
-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F.
|
||||
function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, verr
|
||||
end
|
||||
if m.format ~= "mod" and m.format ~= "xm" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format")
|
||||
end
|
||||
local nch = m.channels
|
||||
if nch > 32 then
|
||||
return nil, Err.new(Err.ARG, "MOD holds at most 32 channels")
|
||||
end
|
||||
-- the sample for each instrument number
|
||||
local smpOf: { any } = {}
|
||||
if m.format == "xm" then
|
||||
for i, ins in m.instruments do
|
||||
local first = 0
|
||||
for n = 1, 120 do
|
||||
local s = ins.sampleMap[n]
|
||||
if s ~= 0 then
|
||||
if first ~= 0 and s ~= first then
|
||||
return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples")
|
||||
end
|
||||
first = s
|
||||
end
|
||||
end
|
||||
smpOf[i] = m.samples[first] or Tracker.newSample(ins.name)
|
||||
end
|
||||
else
|
||||
for i, s in m.samples do
|
||||
smpOf[i] = s
|
||||
end
|
||||
end
|
||||
if #smpOf > 31 then
|
||||
return nil, Err.new(Err.ARG, "MOD holds at most 31 samples")
|
||||
end
|
||||
local order: { number } = {}
|
||||
for _, o in m.order do
|
||||
if o == 255 then
|
||||
break
|
||||
elseif o ~= 254 then
|
||||
table.insert(order, o)
|
||||
end
|
||||
end
|
||||
if #order == 0 or #order > 128 then
|
||||
return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries")
|
||||
end
|
||||
local npat = #m.patterns
|
||||
if npat > 100 then
|
||||
return nil, Err.new(Err.ARG, "too many patterns for MOD")
|
||||
end
|
||||
for p, pat in m.patterns do
|
||||
if pat.rows ~= 64 then
|
||||
return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)")
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536)
|
||||
writeName(w, m.title or "", 20)
|
||||
local datas: { buffer } = {}
|
||||
for i = 1, 31 do
|
||||
local s = smpOf[i]
|
||||
if s then
|
||||
local len = math.min(s.length, 131070)
|
||||
local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 })
|
||||
if s.channels == 2 then
|
||||
-- mix stereo samples down
|
||||
local mono = buffer.create(len * 4)
|
||||
for k = 0, len - 1 do
|
||||
buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2)
|
||||
end
|
||||
pcm = Pcm.encode(mono, len, { bits = 8, signed = true })
|
||||
end
|
||||
local even = len + len % 2
|
||||
local padded = buffer.create(even)
|
||||
buffer.copy(padded, 0, pcm, 0, len)
|
||||
datas[i] = padded
|
||||
writeName(w, s.name or "", 22)
|
||||
w:u16be(even // 2)
|
||||
local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7)
|
||||
w:u8(ft % 16)
|
||||
w:u8(math.clamp(math.floor(s.volume), 0, 64))
|
||||
if s.loopType > 0 and s.loopEnd <= even then
|
||||
w:u16be(s.loopStart // 2)
|
||||
w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2))
|
||||
else
|
||||
w:u16be(0)
|
||||
w:u16be(1)
|
||||
end
|
||||
else
|
||||
w:fill(0, 22)
|
||||
w:u16be(0)
|
||||
w:u8(0)
|
||||
w:u8(0)
|
||||
w:u16be(0)
|
||||
w:u16be(1)
|
||||
end
|
||||
end
|
||||
w:u8(#order)
|
||||
w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127)
|
||||
for i = 1, 128 do
|
||||
w:u8(order[i] or 0)
|
||||
end
|
||||
local sig
|
||||
if nch == 4 then
|
||||
sig = if npat > 64 then "M!K!" else "M.K."
|
||||
elseif nch < 10 then
|
||||
sig = nch .. "CHN"
|
||||
else
|
||||
sig = nch .. "CH"
|
||||
end
|
||||
w:string(sig)
|
||||
for p = 1, npat do
|
||||
local d = m.patterns[p].data
|
||||
for i = 0, 64 * nch - 1 do
|
||||
local q = i * 5
|
||||
local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4)
|
||||
local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0
|
||||
if period > 4095 then
|
||||
period = 0
|
||||
end
|
||||
if fx > 15 then
|
||||
fx, param = 0, 0
|
||||
end
|
||||
if ins > 31 then
|
||||
ins = 0
|
||||
end
|
||||
w:u8((ins // 16) * 16 + period // 256)
|
||||
w:u8(period % 256)
|
||||
w:u8((ins % 16) * 16 + fx)
|
||||
w:u8(param)
|
||||
end
|
||||
end
|
||||
for i = 1, 31 do
|
||||
if datas[i] then
|
||||
w:bytes(datas[i])
|
||||
end
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Mod.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Mod
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -0,0 +1,163 @@
|
||||
--!strict
|
||||
-- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format
|
||||
-- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter
|
||||
-- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel
|
||||
-- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at
|
||||
-- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without
|
||||
-- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per
|
||||
-- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont /
|
||||
-- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate.
|
||||
-- Not supported: writing (save as .mid through the midi format's encoder).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Render = require("@rosetta/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mus = {
|
||||
name = "mus",
|
||||
category = "music",
|
||||
extensions = { "mus" },
|
||||
mime = { "audio/x-mus" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
rate: number?, -- ticks per second, default 140 (Doom); some players use 70
|
||||
maxEvents: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- MUS controller / system event number -> MIDI controller (0 is the program change)
|
||||
local CONTROLLER = { [0] = 0, 0, 0x01, 0x07, 0x0A, 0x0B, 0x5B, 0x5D, 0x40, 0x43, 0x78, 0x7B, 0x7E, 0x7F, 0x79 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mus.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "MUS\x1a" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- the score [p, e) -> events | nil, message
|
||||
local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean)
|
||||
local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } }
|
||||
local map: { [number]: number } = { [15] = 9 }
|
||||
local volume: { [number]: number } = {}
|
||||
local nextChannel = 0
|
||||
local tick = 0
|
||||
while p < e do
|
||||
local ev = readu8(b, p)
|
||||
p += 1
|
||||
local kind, mch = bit32.band(bit32.rshift(ev, 4), 7), bit32.band(ev, 15)
|
||||
if kind == 6 then
|
||||
return events, nil, false
|
||||
end
|
||||
local ch = map[mch]
|
||||
if not ch then
|
||||
ch = nextChannel
|
||||
map[mch] = ch
|
||||
nextChannel += if nextChannel == 8 then 2 else 1
|
||||
table.insert(events, { tick = tick, type = "controller", channel = ch, data = { 0x07, 127 } })
|
||||
end
|
||||
local need = if kind == 1 then (if p < e and readu8(b, p) >= 128 then 2 else 1) elseif kind == 4 then 2 elseif kind == 5 then 0 else 1
|
||||
if kind == 7 then
|
||||
return nil, "unknown event type 7", false
|
||||
elseif p + need > e then
|
||||
return events, nil, true
|
||||
end
|
||||
local d1, d2 = if need > 0 then readu8(b, p) else 0, if need > 1 then readu8(b, p + 1) else 0
|
||||
p += need
|
||||
if kind == 0 then
|
||||
table.insert(events, { tick = tick, type = "noteOff", channel = ch, data = { d1 % 128, 64 } })
|
||||
elseif kind == 1 then
|
||||
if need == 2 then
|
||||
volume[ch] = math.min(d2, 127)
|
||||
end
|
||||
table.insert(events, { tick = tick, type = "noteOn", channel = ch, data = { d1 % 128, volume[ch] or 127 } })
|
||||
elseif kind == 2 then
|
||||
table.insert(events, { tick = tick, type = "pitchBend", channel = ch, data = { bit32.band(d1, 1) * 64, bit32.rshift(d1, 1) } })
|
||||
elseif kind == 3 or kind == 4 then
|
||||
local c, v = d1, if kind == 3 then (if d1 == 12 then math.min(primary + 1, 127) else 0) else math.min(d2, 127)
|
||||
if CONTROLLER[c] == nil then
|
||||
return nil, string.format("unknown controller %d", c), false
|
||||
end
|
||||
if kind == 4 and c == 0 then
|
||||
table.insert(events, { tick = tick, type = "program", channel = ch, data = { v } })
|
||||
else
|
||||
table.insert(events, { tick = tick, type = "controller", channel = ch, data = { CONTROLLER[c], v } })
|
||||
end
|
||||
end
|
||||
if #events > maxEvents then
|
||||
return nil, "limit: more than " .. maxEvents .. " events", false
|
||||
end
|
||||
if ev >= 128 then
|
||||
local delay = 0
|
||||
repeat
|
||||
if p >= e then
|
||||
return events, nil, true
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
delay = delay * 128 + c % 128
|
||||
until c < 128 or delay > 2 ^ 28
|
||||
tick += delay
|
||||
end
|
||||
end
|
||||
return events, nil, true
|
||||
end
|
||||
|
||||
function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local rate = o.rate or 140
|
||||
if type(rate) ~= "number" or rate < 1 or rate > 100000 then
|
||||
return nil, Err.new(Err.ARG, "rate must be 1..100000 ticks per second")
|
||||
end
|
||||
if r:peek(4) ~= "MUS\x1a" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a MUS file")
|
||||
end
|
||||
r:skip(4)
|
||||
local len, start, primary, secondary, ninst = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
r:skip(2)
|
||||
local instruments = {}
|
||||
for i = 1, ninst do
|
||||
instruments[i] = r:u16le()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
if start > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "score starts past the end")
|
||||
end
|
||||
local p = r.base + start
|
||||
local events, msg, truncated = score(r.buf, p, math.min(p + len, r.limit), primary, o.maxEvents or 2 ^ 24)
|
||||
if not events then
|
||||
return nil, Err.from(msg :: string, p)
|
||||
end
|
||||
local last = events[#events].tick
|
||||
table.insert(events, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(70, rate) })
|
||||
table.insert(events, { tick = last, type = "meta", meta = 0x2F, data = {} })
|
||||
local midi = Types.Midi.new(70)
|
||||
midi.format = 0
|
||||
midi.tracks = { { events = events } }
|
||||
Render.attach(midi, { format = "mus", primaryChannels = primary, secondaryChannels = secondary, instruments = instruments, rate = rate })
|
||||
midi.meta.truncated = truncated or p + len > r.limit
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
|
||||
function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Mus.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
return Mus
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Chunks = require("@rosetta/containers/Chunks")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -0,0 +1,242 @@
|
||||
--!strict
|
||||
-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism
|
||||
-- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio
|
||||
-- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning
|
||||
-- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5
|
||||
-- speed reference, as IT shows S3M files).
|
||||
-- Not supported: AdLib (OPL) instruments and channels (read as silent), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local S3m = {
|
||||
name = "s3m",
|
||||
category = "music",
|
||||
extensions = { "s3m" },
|
||||
mime = { "audio/s3m", "audio/x-s3m" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
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 S3m.sniff(r: Bytes.Reader): number
|
||||
if r:size() >= 48 and r:peek(4, 44) == "SCRM" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 28
|
||||
if r:size() < 96 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header")
|
||||
end
|
||||
if r:peek(4, 44) ~= "SCRM" then
|
||||
return nil, Err.new(Err.CORRUPT, "no SCRM signature")
|
||||
end
|
||||
local title = r:fixed(28)
|
||||
r:seek(32)
|
||||
local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le()
|
||||
local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le()
|
||||
r:seek(48)
|
||||
local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
|
||||
r:seek(64)
|
||||
local chnset: { number } = {}
|
||||
for i = 1, 32 do
|
||||
chnset[i] = r:u8()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if ordnum > 256 or insnum > 256 or patnum > 256 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header counts")
|
||||
end
|
||||
-- channels: enabled PCM channels (0..15); the count is the last used one
|
||||
local nch = 0
|
||||
for i = 1, 32 do
|
||||
local c = chnset[i]
|
||||
if c < 16 then
|
||||
nch = i
|
||||
end
|
||||
end
|
||||
if nch == 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)")
|
||||
end
|
||||
local m = Tracker.newModule("s3m", nch)
|
||||
m.title = title
|
||||
m.speed = if speed > 0 and speed < 255 then speed else 6
|
||||
m.tempo = if tempo >= 33 then tempo else 125
|
||||
m.globalVolume = math.min(gv, 64) * 2
|
||||
m.mixVolume = math.max(mv % 128, 16)
|
||||
if mv < 128 then
|
||||
-- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same)
|
||||
m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5)
|
||||
end
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0
|
||||
m.flags.amigaLimits = bit32.band(flags, 16) ~= 0
|
||||
m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 }
|
||||
-- orders, parapointers, panning
|
||||
r:seek(96)
|
||||
for i = 1, ordnum do
|
||||
local o = r:u8()
|
||||
table.insert(m.order, o)
|
||||
end
|
||||
local insPtr, patPtr = {}, {}
|
||||
for i = 1, insnum do
|
||||
insPtr[i] = r:u16le() * 16
|
||||
end
|
||||
for i = 1, patnum do
|
||||
patPtr[i] = r:u16le() * 16
|
||||
end
|
||||
local pans: { number } = {}
|
||||
if dp == 252 then
|
||||
for i = 1, 32 do
|
||||
pans[i] = r:u8()
|
||||
end
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
-- drop trailing end markers; keep inner "+++" / "---"
|
||||
while #m.order > 0 and m.order[#m.order] == 255 do
|
||||
table.remove(m.order)
|
||||
end
|
||||
local stereo = mv >= 128
|
||||
for i = 1, nch do
|
||||
local c = chnset[i]
|
||||
local pan = 128
|
||||
if stereo then
|
||||
pan = if c % 16 >= 8 then 0xCC else 0x33
|
||||
local p = pans[i]
|
||||
if p and bit32.band(p, 0x20) ~= 0 then
|
||||
pan = (p % 16) * 0x11
|
||||
end
|
||||
end
|
||||
m.channelPan[i] = pan
|
||||
m.channelMute[i] = c >= 16
|
||||
end
|
||||
-- samples
|
||||
local total = 0
|
||||
local unsigned = ffi ~= 1
|
||||
for i = 1, insnum do
|
||||
local s = Tracker.newSample()
|
||||
m.samples[i] = s
|
||||
local h = r:sub(insPtr[i], 80)
|
||||
if h:size() < 80 then
|
||||
return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i])
|
||||
end
|
||||
local typ = h:u8()
|
||||
h:skip(12)
|
||||
local hi = h:u8()
|
||||
local lo = h:u16le()
|
||||
local len, ls, le = h:u32le(), h:u32le(), h:u32le()
|
||||
local vol = h:u8()
|
||||
h:skip(1)
|
||||
local pack, sflags = h:u8(), h:u8()
|
||||
local c2spd = h:u32le()
|
||||
h:seek(48)
|
||||
s.name = h:fixed(28)
|
||||
s.volume = math.min(vol, 64)
|
||||
s.c5speed = if c2spd > 0 then c2spd else 8363
|
||||
if typ == 1 and len > 0 and pack == 0 then
|
||||
local bits = if bit32.band(sflags, 4) ~= 0 then 16 else 8
|
||||
local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1
|
||||
local off = (hi * 65536 + lo) * 16
|
||||
len = math.min(len, 2 ^ 26)
|
||||
-- a short file: keep what is there
|
||||
local avail = math.max(0, r:size() - off) // (nchs * bits // 8)
|
||||
len = math.min(len, avail)
|
||||
total += len * nchs * 4
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true })
|
||||
if data then
|
||||
s.data, s.length, s.bits, s.channels = data, len, bits, nchs
|
||||
if bit32.band(sflags, 1) ~= 0 and le > ls then
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- patterns
|
||||
for p = 1, patnum do
|
||||
local pat = Tracker.newPattern(64, nch)
|
||||
m.patterns[p] = pat
|
||||
local ptr = patPtr[p]
|
||||
if ptr > 0 then
|
||||
local pr = r:sub(ptr)
|
||||
local plen = pr:u16le()
|
||||
pr = pr:sub(2, math.max(0, plen - 2))
|
||||
local d = pat.data
|
||||
local row = 0
|
||||
while row < 64 and not pr:eof() do
|
||||
local what = pr:u8()
|
||||
if what == 0 then
|
||||
row += 1
|
||||
else
|
||||
local ch = what % 32
|
||||
local note, ins, vol, cmd, info = 0, 0, 0, 0, 0
|
||||
if bit32.band(what, 0x20) ~= 0 then
|
||||
local nb = pr:u8()
|
||||
ins = pr:u8()
|
||||
if nb == 254 then
|
||||
note = 254
|
||||
elseif nb < 254 and nb % 16 < 12 then
|
||||
note = (nb // 16) * 12 + nb % 16 + 13
|
||||
if note > 120 then
|
||||
note = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
if bit32.band(what, 0x40) ~= 0 then
|
||||
vol = math.min(pr:u8(), 64) + 1
|
||||
end
|
||||
if bit32.band(what, 0x80) ~= 0 then
|
||||
cmd = pr:u8()
|
||||
info = pr:u8()
|
||||
if cmd > 26 then
|
||||
cmd, info = 0, 0
|
||||
end
|
||||
end
|
||||
if ch < nch then
|
||||
local o = (row * nch + ch) * 5
|
||||
buffer.writeu8(d, o, note)
|
||||
buffer.writeu8(d, o + 1, ins)
|
||||
buffer.writeu8(d, o + 2, vol)
|
||||
buffer.writeu8(d, o + 3, cmd)
|
||||
buffer.writeu8(d, o + 4, info)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
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 S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = S3m.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return S3m
|
||||
@@ -0,0 +1,44 @@
|
||||
--!strict
|
||||
-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the
|
||||
-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit),
|
||||
-- presets / instruments / sample headers with global zones, generator merging into playable regions.
|
||||
-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied).
|
||||
-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local SoundFont = require("@rosetta/codecs/audio/SoundFont")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Sf2 = {
|
||||
name = "sf2",
|
||||
category = "music",
|
||||
extensions = { "sf2" },
|
||||
mime = { "audio/x-soundfont" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" },
|
||||
caps = { decode = true, encode = false, sm24 = true, sf3 = false },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxRegions: number?, -- default 10^6
|
||||
maxSamples: number?, -- default 2^28
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Sf2.sniff(r: Bytes.Reader): number
|
||||
return if SoundFont.sniff(r) then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?)
|
||||
return SoundFont.parse(r, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it)
|
||||
Sf2.synth = SoundFont.synth
|
||||
Sf2.fallback = SoundFont.fallback
|
||||
|
||||
return Sf2
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Load = require("@rosetta/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
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/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
|
||||
@@ -0,0 +1,573 @@
|
||||
--!strict
|
||||
-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker /
|
||||
-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and
|
||||
-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit
|
||||
-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga
|
||||
-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files
|
||||
-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies).
|
||||
-- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's
|
||||
-- stereo-sample / extra-effect extensions on write.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Tracker = require("@rosetta/codecs/audio/Tracker")
|
||||
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xm = {
|
||||
name = "xm",
|
||||
category = "music",
|
||||
extensions = { "xm" },
|
||||
mime = { "audio/xm", "audio/x-xm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
tracker: string?, -- the tracker name field (default: the source file's, else "rosetta")
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "Extended Module: "
|
||||
local Pcm = Tracker.Pcm
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xm.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(17) == MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function readEnvelope(r: Bytes.Reader): ({ number }, { number })
|
||||
local xs, ys = {}, {}
|
||||
for i = 1, 12 do
|
||||
xs[i] = r:u16le()
|
||||
ys[i] = r:u16le()
|
||||
end
|
||||
return xs, ys
|
||||
end
|
||||
|
||||
local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any
|
||||
local e = Tracker.newEnvelope()
|
||||
n = math.min(n, 12)
|
||||
for i = 1, n do
|
||||
e.ticks[i] = xs[i]
|
||||
e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64)
|
||||
end
|
||||
e.enabled = bit32.band(typ, 1) ~= 0 and n > 0
|
||||
e.sustain = bit32.band(typ, 2) ~= 0
|
||||
e.loop = bit32.band(typ, 4) ~= 0
|
||||
e.susStart, e.susEnd = sus + 1, sus + 1
|
||||
e.loopStart, e.loopEnd = ls + 1, le + 1
|
||||
-- the raw fields, for a faithful re-save
|
||||
e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n }
|
||||
return e
|
||||
end
|
||||
|
||||
function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 28
|
||||
if r:peek(17) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "no XM signature")
|
||||
end
|
||||
r:skip(17)
|
||||
local title = r:fixed(20)
|
||||
r:skip(1)
|
||||
local tracker = r:fixed(20)
|
||||
local version = r:u16le()
|
||||
local hdrStart = r:tell()
|
||||
local hdrSize = r:u32le()
|
||||
local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le()
|
||||
local orders = {}
|
||||
for i = 1, 256 do
|
||||
orders[i] = r:u8()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header counts")
|
||||
end
|
||||
if version < 0x0104 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version))
|
||||
end
|
||||
local m = Tracker.newModule("xm", nch)
|
||||
m.title = title
|
||||
m.speed = if speed > 0 and speed < 256 then speed else 6
|
||||
m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125
|
||||
m.linear = bit32.band(flags, 1) ~= 0
|
||||
m.restart = restart
|
||||
for i = 1, songLen do
|
||||
m.order[i] = orders[i]
|
||||
end
|
||||
m.meta.tracker = tracker
|
||||
m.meta.source = { format = "xm", tracker = tracker, version = version }
|
||||
-- patterns
|
||||
if not r:seek(hdrStart + hdrSize) then
|
||||
return nil, r.err
|
||||
end
|
||||
for p = 1, npat do
|
||||
local start = r:tell()
|
||||
local plen = r:u32le()
|
||||
r:u8()
|
||||
local rows = r:u16le()
|
||||
local psize = r:u16le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if rows < 1 or rows > 256 then
|
||||
return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos)
|
||||
end
|
||||
r:seek(start + plen)
|
||||
local pat = Tracker.newPattern(rows, nch)
|
||||
m.patterns[p] = pat
|
||||
local pr = r:slice(psize)
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local d = pat.data
|
||||
if psize > 0 then
|
||||
for i = 0, rows * nch - 1 do
|
||||
local b = pr:u8()
|
||||
local note, ins, vol, fx, param = 0, 0, 0, 0, 0
|
||||
if b >= 128 then
|
||||
if bit32.band(b, 1) ~= 0 then
|
||||
note = pr:u8()
|
||||
end
|
||||
if bit32.band(b, 2) ~= 0 then
|
||||
ins = pr:u8()
|
||||
end
|
||||
if bit32.band(b, 4) ~= 0 then
|
||||
vol = pr:u8()
|
||||
end
|
||||
if bit32.band(b, 8) ~= 0 then
|
||||
fx = pr:u8()
|
||||
end
|
||||
if bit32.band(b, 16) ~= 0 then
|
||||
param = pr:u8()
|
||||
end
|
||||
else
|
||||
note = b
|
||||
ins = pr:u8()
|
||||
vol = pr:u8()
|
||||
fx = pr:u8()
|
||||
param = pr:u8()
|
||||
end
|
||||
if pr.err then
|
||||
break -- a short pattern: the rest stays empty
|
||||
end
|
||||
if note == 97 then
|
||||
note = 255
|
||||
elseif note > 96 then
|
||||
note = 0
|
||||
end
|
||||
if fx > 35 then
|
||||
fx, param = 0, 0
|
||||
end
|
||||
local o = i * 5
|
||||
buffer.writeu8(d, o, note)
|
||||
buffer.writeu8(d, o + 1, ins)
|
||||
buffer.writeu8(d, o + 2, vol)
|
||||
buffer.writeu8(d, o + 3, fx)
|
||||
buffer.writeu8(d, o + 4, param)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- instruments and their samples
|
||||
local total = 0
|
||||
for i = 1, nins do
|
||||
local start = r:tell()
|
||||
local isize = r:u32le()
|
||||
local ins = Tracker.newInstrument(r:fixed(22))
|
||||
r:u8()
|
||||
local ns = r:u16le()
|
||||
if r.err then
|
||||
-- a file cut inside the instruments: keep what was read
|
||||
r.err = nil
|
||||
break
|
||||
end
|
||||
m.instruments[i] = ins
|
||||
ins.samples = {}
|
||||
if ns == 0 then
|
||||
r:seek(start + math.max(isize, 29))
|
||||
continue
|
||||
end
|
||||
if ns > 256 then
|
||||
return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples")
|
||||
end
|
||||
local shSize = r:u32le()
|
||||
local keymap = {}
|
||||
for n = 1, 96 do
|
||||
keymap[n] = r:u8()
|
||||
end
|
||||
local vx, vy = readEnvelope(r)
|
||||
local px, py = readEnvelope(r)
|
||||
local nv, np = r:u8(), r:u8()
|
||||
local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
|
||||
local vt, pt = r:u8(), r:u8()
|
||||
ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8()
|
||||
ins.fadeout = r:u16le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false)
|
||||
ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true)
|
||||
ins.headerSize = isize
|
||||
r:seek(start + isize)
|
||||
local base = #m.samples
|
||||
local heads = {}
|
||||
for k = 1, ns do
|
||||
local hs = r:tell()
|
||||
local len, ls, ll = r:u32le(), r:u32le(), r:u32le()
|
||||
local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8()
|
||||
local nm = r:fixed(22)
|
||||
r:seek(hs + math.max(shSize, 40))
|
||||
heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm }
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
for k = 1, ns do
|
||||
local h = heads[k]
|
||||
local s = Tracker.newSample(h.name)
|
||||
local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8
|
||||
local bps = bits // 8
|
||||
s.bits = bits
|
||||
s.volume = math.min(h.vol, 64)
|
||||
s.finetune = h.ft
|
||||
s.relativeNote = h.rel
|
||||
s.pan = h.pan
|
||||
local frames = h.len // bps
|
||||
if h.res == 0xAD and bits == 8 then
|
||||
-- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps
|
||||
-- the samples whose nibbles are present
|
||||
frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2))
|
||||
total += frames * 4
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
s.data = buffer.create(frames * 4)
|
||||
if frames > 0 then
|
||||
Adpcm.modplug(r.buf, r.pos, frames, s.data, 0)
|
||||
end
|
||||
r:skip(math.min(16 + (h.len + 1) // 2, r:remaining()))
|
||||
else
|
||||
local avail = r:remaining() // bps
|
||||
local got = math.min(frames, avail)
|
||||
total += got * 4
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true })
|
||||
r:skip(got * bps)
|
||||
s.data = data or buffer.create(0)
|
||||
frames = if data then got else 0
|
||||
end
|
||||
s.length = frames
|
||||
local lt = h.typ % 4
|
||||
if lt == 3 then
|
||||
lt = 2
|
||||
end
|
||||
if lt > 0 and h.ll > 0 then
|
||||
s.loopStart = h.ls // bps
|
||||
s.loopEnd = (h.ls + h.ll) // bps
|
||||
s.loopType = lt
|
||||
end
|
||||
m.samples[base + k] = s
|
||||
table.insert(ins.samples, base + k)
|
||||
end
|
||||
for n = 1, 120 do
|
||||
local k = keymap[math.min(n, 96)]
|
||||
ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0
|
||||
end
|
||||
ins.keymap = keymap
|
||||
end
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function writeName(w: Bytes.Writer, s: string?, n: number)
|
||||
local t = string.sub(s or "", 1, n)
|
||||
w:string(t)
|
||||
w:fill(0, n - #t)
|
||||
end
|
||||
|
||||
-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? }
|
||||
local function instrumentsOf(m: any): ({ any }?, string?)
|
||||
local out = {}
|
||||
if m.format == "mod" then
|
||||
for i, s in m.samples do
|
||||
local km = table.create(96, 0)
|
||||
out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil }
|
||||
end
|
||||
return out
|
||||
end
|
||||
for i, ins in m.instruments do
|
||||
local list: { number } = {}
|
||||
if type(ins.samples) == "table" then
|
||||
for _, g in ins.samples do
|
||||
table.insert(list, g)
|
||||
end
|
||||
end
|
||||
local index: { [number]: number } = {}
|
||||
for k, g in list do
|
||||
index[g] = k - 1
|
||||
end
|
||||
local km = table.create(96, 0)
|
||||
for n = 1, 96 do
|
||||
local g = ins.sampleMap[n] or 0
|
||||
if g > 0 and m.samples[g] then
|
||||
if index[g] == nil then
|
||||
table.insert(list, g)
|
||||
index[g] = #list - 1
|
||||
end
|
||||
km[n] = index[g]
|
||||
end
|
||||
end
|
||||
if #list > 255 then
|
||||
return nil, "instrument " .. i .. " uses more than 255 samples"
|
||||
end
|
||||
local smps = {}
|
||||
for k, g in list do
|
||||
smps[k] = m.samples[g] or Tracker.newSample()
|
||||
end
|
||||
out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins }
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean)
|
||||
local n = if e then math.min(#e.ticks, 12) else 0
|
||||
for i = 1, 12 do
|
||||
if i <= n then
|
||||
w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535))
|
||||
w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64))
|
||||
else
|
||||
w:u32le(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- envelope count, type, sustain, loop start, loop end
|
||||
local function envelopeFields(e: any): (number, number, number, number, number)
|
||||
if not e then
|
||||
return 0, 0, 0, 0, 0
|
||||
end
|
||||
local n = math.min(#e.ticks, 12)
|
||||
local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0)
|
||||
local raw = e.raw
|
||||
if raw and raw.type % 8 == typ then
|
||||
typ = raw.type -- keep unknown bits
|
||||
end
|
||||
local function idx(v: number): number
|
||||
return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1))
|
||||
end
|
||||
local sus = idx(e.susStart)
|
||||
local ls, le = idx(e.loopStart), idx(e.loopEnd)
|
||||
if raw and n == 0 then
|
||||
sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd
|
||||
end
|
||||
return n, typ, sus, ls, le
|
||||
end
|
||||
|
||||
-- encode(module, opts) -> XM bytes ("xm" or "mod" modules)
|
||||
function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, verr
|
||||
end
|
||||
if m.format ~= "xm" and m.format ~= "mod" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")")
|
||||
end
|
||||
local nch = m.channels
|
||||
if nch > 64 then
|
||||
return nil, Err.new(Err.ARG, "XM holds at most 64 channels")
|
||||
end
|
||||
local insts, ierr = instrumentsOf(m)
|
||||
if not insts then
|
||||
return nil, Err.new(Err.ARG, ierr or "bad instruments")
|
||||
end
|
||||
if #insts > 128 then
|
||||
return nil, Err.new(Err.ARG, "XM holds at most 128 instruments")
|
||||
end
|
||||
if #m.patterns > 256 then
|
||||
return nil, Err.new(Err.ARG, "XM holds at most 256 patterns")
|
||||
end
|
||||
local order: { number } = {}
|
||||
for _, o in m.order do
|
||||
if o == 255 then
|
||||
break
|
||||
elseif o ~= 254 then
|
||||
table.insert(order, o)
|
||||
end
|
||||
end
|
||||
if #order > 256 then
|
||||
return nil, Err.new(Err.ARG, "XM holds at most 256 order entries")
|
||||
end
|
||||
local w = Bytes.writer(65536)
|
||||
w:string(MAGIC)
|
||||
writeName(w, m.title, 20)
|
||||
w:u8(0x1A)
|
||||
writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "rosetta", 20)
|
||||
w:u16le(0x0104)
|
||||
w:u32le(276)
|
||||
w:u16le(#order)
|
||||
w:u16le(if m.restart < #order then m.restart else 0)
|
||||
w:u16le(nch)
|
||||
w:u16le(#m.patterns)
|
||||
w:u16le(#insts)
|
||||
w:u16le(if m.linear then 1 else 0)
|
||||
w:u16le(m.speed)
|
||||
w:u16le(math.clamp(math.floor(m.tempo), 32, 999))
|
||||
for i = 1, 256 do
|
||||
w:u8(order[i] or 0)
|
||||
end
|
||||
-- patterns (every cell packed, as FT2-compatible writers may)
|
||||
for _, pat in m.patterns do
|
||||
local pk = Bytes.writer(pat.rows * nch * 2)
|
||||
local d = pat.data
|
||||
for i = 0, pat.rows * nch - 1 do
|
||||
local o = i * 5
|
||||
local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
|
||||
if note == 255 then
|
||||
note = 97
|
||||
elseif note > 96 then
|
||||
note = 0
|
||||
end
|
||||
if m.format == "mod" then
|
||||
vol = 0
|
||||
if fx > 15 then
|
||||
fx, param = 0, 0
|
||||
end
|
||||
end
|
||||
if ins > 128 then
|
||||
ins = 0
|
||||
end
|
||||
local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0)
|
||||
pk:u8(flags)
|
||||
if note > 0 then
|
||||
pk:u8(note)
|
||||
end
|
||||
if ins > 0 then
|
||||
pk:u8(ins)
|
||||
end
|
||||
if vol > 0 then
|
||||
pk:u8(vol)
|
||||
end
|
||||
if fx > 0 then
|
||||
pk:u8(fx)
|
||||
end
|
||||
if param > 0 then
|
||||
pk:u8(param)
|
||||
end
|
||||
end
|
||||
local data = pk:finish()
|
||||
if buffer.len(data) > 65535 then
|
||||
return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB")
|
||||
end
|
||||
w:u32le(9)
|
||||
w:u8(0)
|
||||
w:u16le(pat.rows)
|
||||
w:u16le(buffer.len(data))
|
||||
w:bytes(data)
|
||||
end
|
||||
-- instruments
|
||||
for _, it in insts do
|
||||
local ins = it.ins
|
||||
local smps = it.samples
|
||||
if #smps == 0 then
|
||||
w:u32le(29)
|
||||
writeName(w, it.name, 22)
|
||||
w:u8(0)
|
||||
w:u16le(0)
|
||||
continue
|
||||
end
|
||||
w:u32le(263)
|
||||
writeName(w, it.name, 22)
|
||||
w:u8(0)
|
||||
w:u16le(#smps)
|
||||
w:u32le(40)
|
||||
for n = 1, 96 do
|
||||
w:u8(it.keymap[n])
|
||||
end
|
||||
local ve, pe = ins and ins.volEnv, ins and ins.panEnv
|
||||
writeEnvelope(w, ve, false)
|
||||
writeEnvelope(w, pe, true)
|
||||
local vn, vt, vs, vls, vle = envelopeFields(ve)
|
||||
local pn, pt, ps, pls, ple = envelopeFields(pe)
|
||||
w:u8(vn)
|
||||
w:u8(pn)
|
||||
w:u8(vs)
|
||||
w:u8(vls)
|
||||
w:u8(vle)
|
||||
w:u8(ps)
|
||||
w:u8(pls)
|
||||
w:u8(ple)
|
||||
w:u8(vt)
|
||||
w:u8(pt)
|
||||
w:u8(ins and ins.vibType or 0)
|
||||
w:u8(ins and ins.vibSweep or 0)
|
||||
w:u8(ins and ins.vibDepth or 0)
|
||||
w:u8(ins and ins.vibRate or 0)
|
||||
w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0)
|
||||
w:fill(0, 22)
|
||||
local datas = {}
|
||||
for k, s in smps do
|
||||
local mono = s.data
|
||||
if s.channels == 2 then
|
||||
mono = buffer.create(s.length * 4)
|
||||
for f = 0, s.length - 1 do
|
||||
buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2)
|
||||
end
|
||||
end
|
||||
local bits = if s.bits == 16 then 16 else 8
|
||||
local bps = bits // 8
|
||||
datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true })
|
||||
local typ = (if bits == 16 then 16 else 0)
|
||||
local ls, ll = 0, 0
|
||||
if s.loopType > 0 then
|
||||
typ += s.loopType
|
||||
ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps
|
||||
end
|
||||
local ft = s.finetune
|
||||
local rel = s.relativeNote
|
||||
if m.format == "mod" then
|
||||
rel = 0
|
||||
end
|
||||
w:u32le(s.length * bps)
|
||||
w:u32le(ls)
|
||||
w:u32le(ll)
|
||||
w:u8(math.clamp(math.floor(s.volume), 0, 64))
|
||||
w:u8(math.clamp(math.floor(ft), -128, 127) % 256)
|
||||
w:u8(typ)
|
||||
w:u8(math.clamp(math.floor(s.pan or 128), 0, 255))
|
||||
w:u8(math.clamp(math.floor(rel), -128, 127) % 256)
|
||||
w:u8(0)
|
||||
writeName(w, s.name, 22)
|
||||
end
|
||||
for _, dd in datas do
|
||||
w:bytes(dd)
|
||||
end
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Xm.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Xm
|
||||
@@ -0,0 +1,215 @@
|
||||
--!strict
|
||||
-- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs,
|
||||
-- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description
|
||||
-- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track,
|
||||
-- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's
|
||||
-- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second
|
||||
-- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the
|
||||
-- first tempo event's value, unused). Renders through codecs/audio/MidiRender.
|
||||
-- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Chunks = require("@rosetta/containers/Chunks")
|
||||
local Render = require("@rosetta/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xmi = {
|
||||
name = "xmi",
|
||||
category = "music",
|
||||
extensions = { "xmi", "xmidi" },
|
||||
mime = { "audio/x-xmidi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true, songs = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
track: number?, -- the song (1-based), default 1
|
||||
maxEvents: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xmi.sniff(r: Bytes.Reader): number
|
||||
local id, kind = r:peek(4), r:peek(4, 8)
|
||||
if id == "FORM" and (kind == "XDIR" or kind == "XMID") then
|
||||
return 1
|
||||
end
|
||||
return if id == "CAT " and kind == "XMID" then 0.9 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8 = buffer.readu8
|
||||
local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 }
|
||||
local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
|
||||
|
||||
-- a MIDI variable-length number at p -> value, next p (nil past e)
|
||||
local function vlq(b: buffer, p: number, e: number): (number?, number)
|
||||
local v = 0
|
||||
for _ = 1, 4 do
|
||||
if p >= e then
|
||||
return nil, p
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
v = v * 128 + c % 128
|
||||
if c < 128 then
|
||||
return v, p
|
||||
end
|
||||
end
|
||||
return nil, p
|
||||
end
|
||||
|
||||
local function bytes(b: buffer, p: number, n: number): { number }
|
||||
local t: { number } = table.create(n) :: { number }
|
||||
for i = 1, n do
|
||||
t[i] = readu8(b, p + i - 1)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
-- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message
|
||||
local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?)
|
||||
local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {}
|
||||
local tick, tempo = 0, nil
|
||||
while p < e do
|
||||
local st = readu8(b, p)
|
||||
p += 1
|
||||
if st < 0x80 then
|
||||
tick += st
|
||||
elseif st == 0xFF then
|
||||
if p >= e then
|
||||
return nil, "truncated meta event"
|
||||
end
|
||||
local kind = readu8(b, p)
|
||||
local n, q = vlq(b, p + 1, e)
|
||||
if not n or q + n > e then
|
||||
return nil, "truncated meta event"
|
||||
end
|
||||
if kind == 0x2F then
|
||||
break
|
||||
elseif kind == 0x51 and n >= 3 then
|
||||
tempo = tempo or readu8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2)
|
||||
else
|
||||
table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, q, n) })
|
||||
end
|
||||
p = q + n
|
||||
elseif st == 0xF0 or st == 0xF7 then
|
||||
local n, q = vlq(b, p, e)
|
||||
if not n or q + n > e then
|
||||
return nil, "truncated sysex"
|
||||
end
|
||||
table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, q, n) })
|
||||
p = q + n
|
||||
elseif st < 0xF0 then
|
||||
local hi, ch = st // 16, st % 16
|
||||
local n = DATA[hi]
|
||||
if p + n > e then
|
||||
return nil, "truncated event"
|
||||
end
|
||||
local d = bytes(b, p, n)
|
||||
p += n
|
||||
table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = d })
|
||||
if hi == 9 then
|
||||
local dur, q = vlq(b, p, e)
|
||||
if not dur then
|
||||
return nil, "truncated note duration"
|
||||
end
|
||||
p = q
|
||||
table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { d[1] % 128, 64 } } })
|
||||
end
|
||||
else
|
||||
return nil, string.format("unexpected status byte 0x%02X", st)
|
||||
end
|
||||
if #list + #offs > maxEvents then
|
||||
return nil, "limit: more than " .. maxEvents .. " events"
|
||||
end
|
||||
end
|
||||
-- the sequence stops at its end-of-track event: notes still sounding end there (wildmidi leaves them hanging)
|
||||
for _, o in offs do
|
||||
if o.tick > tick then
|
||||
o.tick = tick
|
||||
o.ev.tick = tick
|
||||
end
|
||||
end
|
||||
return Render.merge(list, offs), tick, tempo
|
||||
end
|
||||
|
||||
-- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree
|
||||
local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } }
|
||||
local out = {}
|
||||
local function form(c: Chunks.Chunk)
|
||||
local song = {}
|
||||
for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do
|
||||
song[s.id] = song[s.id] or s
|
||||
end
|
||||
if song.EVNT then
|
||||
table.insert(out, song)
|
||||
end
|
||||
end
|
||||
for _, c in Chunks.walk(b, base, limit, Chunks.IFF) do
|
||||
local kind = if c.avail >= 4 then buffer.readstring(b, c.offset, 4) else ""
|
||||
if c.id == "FORM" and kind == "XMID" then
|
||||
form(c)
|
||||
elseif c.id == "CAT " and kind == "XMID" then
|
||||
for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do
|
||||
if s.id == "FORM" and s.avail >= 4 and buffer.readstring(b, s.offset, 4) == "XMID" then
|
||||
form(s)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
if Xmi.sniff(r) == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not an XMIDI file")
|
||||
end
|
||||
local list = songs(r.buf, r.base, r.limit)
|
||||
local index = o.track or 1
|
||||
if #list == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no XMID song with an EVNT chunk")
|
||||
elseif type(index) ~= "number" or index < 1 or index > #list or index % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, string.format("track must be 1..%d", #list))
|
||||
end
|
||||
local song = list[index]
|
||||
local ev = song.EVNT
|
||||
local evs, endTick, tempo = events(r.buf, ev.offset, ev.offset + ev.avail, o.maxEvents or 2 ^ 24)
|
||||
if not evs then
|
||||
return nil, Err.from(endTick :: string, ev.offset)
|
||||
end
|
||||
local last = math.max(endTick :: number, if #evs > 0 then evs[#evs].tick else 0)
|
||||
table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(60, 120) })
|
||||
table.insert(evs, { tick = last, type = "meta", meta = 0x2F, data = {} })
|
||||
local timbres = {}
|
||||
local tb = song.TIMB
|
||||
if tb and tb.avail >= 2 then
|
||||
for i = 0, math.min(buffer.readu16(r.buf, tb.offset), (tb.avail - 2) // 2) - 1 do
|
||||
table.insert(timbres, { patch = readu8(r.buf, tb.offset + 2 + i * 2), bank = readu8(r.buf, tb.offset + 3 + i * 2) })
|
||||
end
|
||||
end
|
||||
local rb = song.RBRN
|
||||
local branches = if rb and rb.avail >= 2 then buffer.readu16(r.buf, rb.offset) else 0
|
||||
local midi = Types.Midi.new(60)
|
||||
midi.format = 0
|
||||
midi.tracks = { { events = evs } }
|
||||
Render.attach(midi, { format = "xmi", songs = #list, song = index, timbres = timbres, tempo = tempo, branches = branches })
|
||||
midi.meta.truncated = ev.truncated
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
|
||||
function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Xmi.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
return Xmi
|
||||
Reference in new issue
Block a user