# Music Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT) 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](audio.md#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. ```luau 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 | `"mod"`, `"s3m"`, `"xm"` or `"it"`: the effect family the engine plays | | `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](#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). ```luau 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). ```luau 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 | ```luau 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. ```luau 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) | `F.audio.open` and `F.audio.load` do not take music files; use `F.music.open`, or `F.open`, which detects any category. | 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 | ```luau 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) ``` ## 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 | ```luau 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: ```luau 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 events only, so put the name in an event. ```luau 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 = "meta", meta = 0x03, data = { string.byte("Arpeggio", 1, -1) } }, -- the track name { 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, { events = events }) 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. ```luau 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 ``` | 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 | See [FORMATS.md](../FORMATS.md) for each format's capabilities. ## Gotchas - **Saving music as audio needs a render.** `F.save(song, nil, { format = "wav" })` and `F.convert(modBytes, "wav")` fail with `UNKNOWN_FORMAT` ("no format named wav for music"). Render first: `F.save(song:render(), nil, { format = "wav" })`. - `F.audio.open(midiBytes)` fails with `UNKNOWN_FORMAT`; use `F.music.open` or `F.open`. - `track.name` is not written: add a meta 0x03 event to name a track. - 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). - A module's `duration` is one pass. `render({ loop = true })` keeps playing past it.