Files
rosetta/docs/guide/music.md
T

22 KiB

Music

Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT, and the other trackers: MTM, 669, STM, ULT, OKT, MED, PTM, FAR, UMX) load as a Module: the patterns, the order list, the samples and the instruments. Standard MIDI files load as a Midi: tracks of timed events. Both render to the standard audio Decoder, so every music file can also be played, analysed or saved as audio. MIDI renders through a SoundFont 2 bank, or through a small built-in set of waveforms when you don't give one.

local song = assert(F.music.load(modBytes))              -- Module
print(song.format, song.title, song.channels)            -- mod  basic  4
local dec = song:render({ sampleRate = 22050 })          -- an audio Decoder (stereo f32)
local wav = assert(F.save(dec, nil, { format = "wav" })) -- streamed into a WAV
assert(F.detect(wav) == "wav")

local tune = assert(F.music.load(midiBytes))             -- Midi
local bank = assert(F.music.load(sf2Bytes))              -- a SoundFont
local audio = assert(F.ops.audio.toAudio(tune:render({ soundfont = bank })))
assert(audio.channels == 2 and audio.sampleRate == 44100)

The types

Module (MOD, S3M, XM, IT)

Field Type Meaning
kind "music"
format string the format it was read from: "mod", "s3m", "xm", "it", "mtm", "669", "med", ...
engine string? the effect family the engine plays ("mod", "s3m", "xm", "it"); absent: the same as format. Set by the other trackers
title string
channels number pattern channels
speed, tempo number initial ticks per row, and BPM (a tick lasts 2.5 / tempo seconds)
order { number } the play order: 0-based pattern numbers; 254 = skip (+++), 255 = end (---)
restart number the 0-based order index the song loops back to
patterns { Pattern } pattern n (as numbered in order) is patterns[n + 1]
samples { Sample } the sample data, as f32
instruments { Instrument } XM / IT instruments (empty for MOD and S3M, where the instrument column names a sample)
instrumentMode boolean notes go through instrument keymaps (XM, IT with instruments)
globalVolume, mixVolume number 0..128
channelPan, channelVolume, channelMute { number }, { number }, { boolean } per channel: pan 0..256 (128 = centre), volume 0..64
linear boolean linear frequency slides (XM / IT) rather than Amiga periods
meta table meta.source.format
module:render(opts?) Decoder plays the song once (see Rendering)

Pattern layout. A Pattern is { rows, data }. data is a buffer of rows * channels cells of 5 bytes each, row by row: note, instrument, volume column, effect, parameter. Row r (0-based), channel c (0-based) starts at byte (r * channels + c) * 5. Notes are 0 (none), 1..120 (1 = C-0), 253 (note fade), 254 (note cut), 255 (key off). The volume column and the effect bytes keep the file's own coding: MOD / XM effects 0..35, S3M / IT effects 1..26 (A = 1).

local m = assert(F.music.load(modBytes))
local p = m.patterns[m.order[1] + 1]                    -- the first pattern played
local notes = 0
for row = 0, p.rows - 1 do
	for ch = 0, m.channels - 1 do
		local at = (row * m.channels + ch) * 5
		local note, instrument = buffer.readu8(p.data, at), buffer.readu8(p.data, at + 1)
		if note > 0 and note <= 120 then
			notes += 1
			local _ = instrument                        -- a sample number for MOD / S3M
		end
	end
end
assert(buffer.len(p.data) == p.rows * m.channels * 5 and notes > 0)

Samples. Each Sample has name, data (f32, interleaved when channels is 2), length (frames), channels, bits (8 or 16, what writers store), loopStart / loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), volume 0..64, and the tuning fields of its format (finetune and relativeNote for MOD / XM, c5speed for S3M / IT).

local m = assert(F.music.load(modBytes))
for i, s in m.samples do
	if s.length > 0 then
		assert(buffer.len(s.data) == s.length * s.channels * 4)
		print(i, s.name, s.length, s.loopType)
	end
end

Midi

Field Type Meaning
kind "midi"
format number SMF type 0, 1 or 2
division number ticks per quarter note (negative: SMPTE time)
tracks { { events, name? } }
meta table tempos, timeSignatures, keySignatures, length (seconds), source
midi:render(opts?) Decoder set by the decoder; for a hand-built Midi use F.format("midi").render(midi, opts)

Each event is { tick, type, channel?, data?, meta? }. tick is absolute (ticks since the start of the track, not a delta). channel is 0..15. data holds the raw data bytes as numbers:

type data
noteOn, noteOff { note, velocity } (a noteOn with velocity 0 is kept as written)
aftertouch { note, pressure }
controller { controller, value }
program { program }
channelPressure { pressure }
pitchBend { lsb, msb } (centre 0, 64)
meta the meta event's bytes; meta is its type (0x03 track name, 0x51 tempo, 0x58 time signature, ...)
sysex, escape the bytes after the length
local tune = assert(F.music.load(midiBytes))
assert(tune.format == 1 and tune.division == 480 and #tune.tracks == 2)
assert(tune.tracks[2].name == "Melody")
assert(tune.meta.tempos[1].bpm == 120 and tune.meta.length == 2)
local notes = {}
for _, ev in tune.tracks[2].events do
	if ev.type == "noteOn" and ev.data[2] > 0 then
		table.insert(notes, ev.data[1])                 -- MIDI note numbers: 60 = middle C
	end
end
assert(#notes == 8 and notes[1] == 60)
local midi = assert(F.format("midi"))
assert(midi.tickToSeconds(tune, 480) == 0.5)            -- one quarter note at 120 BPM

SoundFont

F.music.load(sf2Bytes) returns a SoundFont bank (kind = "soundfont", read only): info (name, engine, comment, ...), presets (each with name, bank, preset), instruments, sampleHeaders and samples. Its only use is as opts.soundfont when rendering MIDI.

local bank = assert(F.music.load(sf2Bytes))
assert(bank.kind == "soundfont" and bank.info.name == "formats-luau test bank")
for _, p in bank.presets do
	print(p.bank, p.preset, p.name)                     -- 0  0  Sine, ...
end

Loading

Call Gives
F.music.load(src, opts?) / F.load a Module, a Midi or a SoundFont
F.music.open(src, opts?) / F.open the rendered audio Decoder (decode and render options together)

Every music file that renders is also audio: F.audio.open(src) gives the same rendered Decoder as F.music.open, and F.audio.load(src) the whole render as an Audio. Decode and render options go in the same opts.

Option Formats Meaning
maxBytes mod, xm, s3m, it refuse more sample data (f32 bytes)
strict midi a truncated track is an error (default: keep the events read, meta.truncated = true)
maxEvents midi default 2^24
local dec = assert(F.music.open(midiBytes, { soundfont = sf2Bytes, sampleRate = 22050 }))
assert(dec.sampleRate == 22050 and dec.channels == 2)
assert(math.abs(dec.duration - 3) < 0.01)               -- 2 s of notes + the 1 s release tail
local d2 = assert(F.open(modBytes))                     -- any category: a Decoder for a module
assert(d2.channels == 2)
local d3 = assert(F.audio.open(midiBytes, { sampleRate = 22050 }))   -- music is audio too
assert(d3.sampleRate == 22050)

Rendering

render(opts?) returns a Decoder (stereo f32). Read it block by block, convert it with F.ops.audio.toAudio, or save it with F.save(decoder, dest, { format = ... }), which encodes as it reads.

Option Applies to Meaning
sampleRate both default 44100
soundfont MIDI a SoundFont value, or SF2 bytes (buffer / string); default the built-in waveforms
gain MIDI linear output gain, default 0.5
tail MIDI seconds rendered after the last event (release tails), default 1
maxVoices MIDI default 256
interpolation modules "linear" (default) or "none"
stereoSeparation modules 0..200 % (default 100; 200 makes MOD's Amiga panning hard left / right)
loop modules keep playing past the end (frames / duration still give one pass)
maxDuration modules seconds, default 3600
local tune = assert(F.music.load(midiBytes))
local plain = tune:render()                             -- built-in waveforms
local sf = tune:render({ soundfont = sf2Bytes, gain = 0.8, tail = 0.5 })
assert(plain.frames == 3 * 44100 and sf.frames == 2.5 * 44100)   -- 2 s of notes + the tail
local flac = assert(F.save(sf, nil, { format = "flac" }))
assert(F.detect(flac) == "flac")

A module's frames and duration come from one pass through the order list, with song loops detected:

local song = assert(F.music.load(modBytes))
local dec = song:render({ sampleRate = 22050, stereoSeparation = 200 })
assert(dec.duration > 1 and dec.frames == math.floor(dec.duration * 22050 + 0.5))
local first = assert(F.ops.audio.trim(F.ops.audio.toAudio(dec), 0, 1))   -- the first second as an Audio
assert(first.frames == 22050)

Building and saving

A Midi is plain data: build one with F.Types.Midi.new(division?) and save it as .mid. Events need absolute ticks; the writer sorts nothing, so keep each track's events in tick order. A track's name is read from its track-name meta event (0x03); the writer writes track.name as one at tick 0 when the track has no 0x03 event of its own.

local m = F.Types.Midi.new(480)                         -- 480 ticks per quarter note, SMF type 1
local events = {
	{ tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } },   -- tempo: 500000 us per quarter
	{ tick = 0, type = "program", channel = 0, data = { 0 } },
}
for i, note in { 60, 64, 67, 72 } do
	table.insert(events, { tick = (i - 1) * 240, type = "noteOn", channel = 0, data = { note, 100 } })
	table.insert(events, { tick = i * 240, type = "noteOff", channel = 0, data = { note, 0 } })
end
table.insert(m.tracks, { name = "Arpeggio", events = events })   -- written as a 0x03 event
local bytes = assert(F.save(m, nil, { format = "midi" }))
local back = assert(F.music.load(bytes))
assert(back.tracks[1].name == "Arpeggio" and back.meta.length == 1)   -- 4 eighth notes at 120 BPM
local dec = assert(F.format("midi").render(m, { soundfont = sf2Bytes }))   -- render without saving first
assert(dec.frames > 0)

Modules save as MOD or XM. MOD writes the 31-sample format; XM modules convert to MOD when they fit (one sample per instrument, effects 0..F, 64-row patterns). S3M and IT are read only.

local song = assert(F.music.load(modBytes))
local mod = assert(F.save(song))                         -- the source format: MOD
local xm = assert(F.save(song, nil, { format = "xm", tracker = "my tool" }))
assert(F.detect(mod) == "mod" and F.detect(xm) == "xm")
local _, err = F.save(song, nil, { format = "it" })
assert(err.code == F.Err.UNSUPPORTED)                    -- read only

Saving a Module or a Midi to an audio format renders it first, with the render options (see Rendering) taken from the same opts; F.convert does the same from music bytes:

local song = assert(F.music.load(modBytes))
local wav = assert(F.save(song, nil, { format = "wav", sampleRate = 22050 }))
assert((assert(F.audio.load(wav))).sampleRate == 22050)
local flac = assert(F.convert(midiBytes, "flac", { soundfont = sf2Bytes, tail = 0.5 }))
assert(F.detect(flac) == "flac")

Building a module

F.music has a small builder for tracker modules, so you never touch the pattern buffers or the sample tuning fields yourself. Pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, and sample and instrument numbers 1-based (0 = none in a cell). Every call returns nil, Err.ARG for bad arguments.

Call Returns
F.music.new({ format?, channels?, title?, speed?, tempo? }) an empty Module: format "mod" (default), "xm", "s3m" or "it"; 4 channels by default
F.music.addPattern(m, rows?, { order? }?) the new pattern's number; rows default 64 (MOD needs 64); appended to m.order unless order = false
F.music.setCell(m, pattern, row, channel, cell) true; cell = { note, instrument, volume, effect, param }, missing fields 0
F.music.getCell(m, pattern, row, channel) the cell, with note as a number
F.music.addSample(m, spec) the new sample's number
F.music.addInstrument(m, spec) the new instrument's number (XM / IT only; MOD and S3M cells name samples)
F.music.note(name) the note number: "C-4" = 49, "C#4" / "Db4" = 50, "off" 255, "cut" 254, "fade" 253

addSample takes audio (a mono or stereo Audio) or data (f32 frames) with length and channels; rate (the Hz the sample plays at on C-4 for MOD / XM, C-5 for S3M / IT; default the Audio's rate, else 8363), loop ("none", "forward", "pingpong"), loopStart / loopEnd (frames), volume 0..64, pan 0..256 and bits (8 or 16, what a writer stores). MOD files keep only a finetune of -1..+7/8 semitone, so give MOD samples a rate near 8363 Hz. addInstrument takes name, sample (every note) or samples (a { [note] = sample } keymap), fadeout, and a volume envelope = { points = { { tick, 0..64 }, ... }, sustain?, loopStart?, loopEnd? }.

local tone = F.Types.Audio.new(8363, 1, 8363)            -- 1 s of a 440 Hz sine at MOD's C-4 rate
for i = 0, 8362 do
	buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(i / 8363 * 2 * math.pi * 440))
end
local song = assert(F.music.new({ format = "mod", channels = 4, title = "beeps" }))
local s = assert(F.music.addSample(song, { name = "sine", audio = tone, loop = "forward" }))
local p = assert(F.music.addPattern(song))               -- pattern 0, 64 rows, in the order list
for row = 0, 63, 8 do
	assert(F.music.setCell(song, p, row, 1, { note = if row % 16 == 0 then "C-4" else "G-4", instrument = s }))
end
assert(F.music.setCell(song, p, 63, 2, { effect = 0xC, param = 0 }))   -- effect C00: volume 0
assert(F.music.getCell(song, p, 8, 1).note == F.music.note("G-4"))
local mod = assert(F.save(song))                         -- a .mod (the module's format)
local wav = assert(F.save(song, nil, { format = "wav" }))  -- or rendered
assert(F.detect(mod) == "mod" and F.detect(wav) == "wav")

local xm = assert(F.music.new({ format = "xm", channels = 2 }))
local smp = assert(F.music.addSample(xm, { audio = tone }))
local lead = assert(F.music.addInstrument(xm, {
	name = "lead", sample = smp, fadeout = 512,
	envelope = { points = { { 0, 64 }, { 10, 40 }, { 40, 0 } }, sustain = 2 },
}))
local p2 = assert(F.music.addPattern(xm, 32))
assert(F.music.setCell(xm, p2, 0, 1, { note = "C-4", instrument = lead }))
assert(F.music.setCell(xm, p2, 16, 1, { note = "off" }))
assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead")
Format Encoder options
midi runningStatus (default true: the bytes python's mido writes)
xm tracker (the tracker name field)
mod none

Formats

Format Read Write Value
mod (MOD, 4..32 channels) yes yes Module
xm yes yes Module
s3m, it yes - Module
midi (.mid, .kar, RMID) yes yes (SMF) Midi
sf2 yes - SoundFont
ahx (AHX / THX), hvl (HivelyTracker) yes - Module (own synth engine)
mus (Doom), xmi (Miles XMIDI), hmp (HMP, HMI) yes - (save as midi) Midi
mtm (MultiTracker) yes - Module (xm family)
669 (Composer 669, UNIS 669) yes - Module (s3m family)
stm (Scream Tracker 2) yes - Module (s3m family)
ult (UltraTracker) yes - Module (it family)
okt (Oktalyzer) yes - Module (it family)
med (MED / OctaMED MMD0..MMD3) yes - Module (xm family)
ptm (PolyTracker) yes - Module (it family)
far (Farandole Composer) yes - Module (s3m family)
umx (Unreal package) yes - the embedded IT / S3M / XM / MOD Module

See FORMATS.md for each format's capabilities.

More tracker formats

MultiTracker, Composer 669, Scream Tracker 2, UltraTracker, Oktalyzer, MED / OctaMED, PolyTracker and Farandole modules load as Modules too (ported from OpenMPT's loaders). Each keeps its own format name and plays through one of the four effect families (engine), with the format's quirks in flags: 669 and Farandole slide in Hz, Scream Tracker 2 has its own tempo byte, MED its tempo modes and hold / decay, Oktalyzer its mixed channel pairs. Their cells use the family's effect coding (an MTM cell reads like an XM cell, an OKT cell like an IT cell); a few effects of these formats have no family equivalent and use the engine's extension codes (0x40 and up: note slides, auto portamentos, ...).

local song = assert(F.music.load(mtmBytes))
assert(song.format == "mtm" and song.engine == "xm" and song.channels == 6)
local med = assert(F.music.load(medBytes))
assert(med.format == "med" and med.meta.source.version == "MMD1" and med.instrumentMode)  -- hold / decay: instruments
local audio = assert(F.ops.audio.toAudio(med:render({ sampleRate = 22050 })))
assert(audio.frames > 0)

An Unreal .umx package holds a module (usually IT, S3M or XM). F.load unwraps it and returns that module, with the package in meta.container; F.format("umx").extract lists the embedded modules without loading them.

local m = assert(F.music.load(umxBytes))
assert(m.format == "s3m" and m.meta.container.format == "umx" and m.meta.container.name == "theme")
local list = assert(F.format("umx").extract(F.Bytes.reader(umxBytes)))
assert(#list == 1 and list[1].format == "s3m")
local dec = assert(F.open(umxBytes))                    -- rendered, like any module
assert(dec.channels == 2)

These formats are read only. Their Modules render to audio like any other (F.save(song, nil, { format = "wav" })), and the module of an UMX keeps its own format, so F.save(m) works when that format has a writer (MOD, XM).

AHX / HVL and MIDI variants

AHX and HivelyTracker modules carry no samples: their instruments are small synth programs (waveforms, filter and pulse-width sweeps, a performance list). They load as a Module-shaped value (format "ahx" / "hvl"; patterns are the tracks, 6 bytes per row: note, instrument, effect, parameter, second effect, parameter; positions hold each channel's track and transpose; subsongs) and render through their own replayer, a port of HivelyTracker's, which gives hvl2wav's samples exactly. Render options: sampleRate, subsong (0 = the main song), loop, maxDuration (default 600 s) and, for AHX, stereo 0..4 (0 mono as hvl2wav renders by default, 4 the Amiga's hard L R R L panning); HVL files store their own panning and gain.

local song = assert(F.music.load(ahxBytes))
assert(song.format == "ahx" and song.channels == 4 and song.title == "demo")
local dec = song:render({ stereo = 4 })                 -- a Decoder, stereo f32 at 44100 Hz
assert(dec.channels == 2 and dec.duration > 1)
local hvl = assert(F.music.load(hvlBytes))
assert(hvl.format == "hvl" and hvl.channels == 6 and #hvl.subsongs == 1)
local intro = hvl:render({ subsong = 1, sampleRate = 22050 })
local wav = assert(F.save(intro, nil, { format = "wav" }))
assert(F.detect(wav) == "wav" and F.detect(hvlBytes) == "hvl")

Doom MUS, Miles XMIDI and HMI's HMP / HMI files load as a Midi, so they play through the SoundFont synth and save as a Standard MIDI File. MUS runs at 140 ticks per second (rate option), XMIDI at a fixed 120 (note durations become note-offs; track picks the song of a multi-song file, meta.source.songs counts them), HMP / HMI at the rate in their header.

local doom = assert(F.music.load(musBytes))
assert(doom.kind == "midi" and doom.meta.source.format == "mus")
local audio = assert(F.ops.audio.toAudio(doom:render({ soundfont = sf2Bytes, tail = 0.2 })))
assert(audio.channels == 2)
local xmi = assert(F.music.load(xmiBytes, { track = 2 }))   -- the second song
assert(xmi.meta.source.songs == 2 and xmi.meta.source.song == 2)
local smf = assert(F.save(xmi, nil, { format = "midi" }))  -- as a .mid
assert(F.detect(smf) == "midi")
local hmp = assert(F.music.load(hmpBytes))
assert(hmp.meta.source.format == "hmp" and #hmp.tracks == 3)

Karaoke .kar files are MIDI files with the lyrics in text events: meta.lyrics lists them with their time ({ time, tick, text }; a leading \ starts a new paragraph, / a new line), the @ headers land in meta.karaoke (T = title lines, L language, I info, ...) and meta.tags.

local kar = assert(F.music.load(karBytes))
assert(kar.meta.tags.title == "Little Song" and kar.meta.tags.artist == "The Docs")
local line = {}
for _, l in kar.meta.lyrics do
	table.insert(line, l.text)
end
assert(table.concat(line) == "\\Hello /karaoke" and kar.meta.lyrics[2].time == 0.5)

Gotchas

  • Saving music to an audio format renders it with the options in opts: F.save(song, nil, { format = "wav", loop = true }) would render up to maxDuration (an hour by default), so leave loop off when saving.
  • A Midi you build yourself has no render method; F.format("midi").render(midi, opts) renders it.
  • MIDI event ticks are absolute, not the deltas stored in the file. Pitch bend data is { lsb, msb }, not a signed value: (msb * 128 + lsb) - 8192.
  • Without a SoundFont, MIDI plays on simple built-in waveforms, which is fine for testing but not General MIDI. SF3 banks (Ogg-compressed samples) are not supported.
  • Pattern cells keep the file's own effect numbering, which differs between MOD / XM (0..35) and S3M / IT (1..26). The other tracker formats use their engine family's numbering (m.engine), not their file's.
  • A Module's meta.unsupported lists what was read but plays silent (MED synth / hybrid / MIDI instruments).
  • A module's duration is one pass. render({ loop = true }) keeps playing past it.