api (init.luau): detectFor() falls back from audio to rendering music formats; encoderFor finds audio formats for music values; renderMusic() through codecs/audio/Tracker or music/midi render. Co-Authored-By: Claude Opus 5.5 <[email protected]>
329 lines
16 KiB
Markdown
329 lines
16 KiB
Markdown
# 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) |
|
|
|
|
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 |
|
|
|
|
```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)
|
|
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 |
|
|
|
|
```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 `track.name` as one at tick 0 when the track has no 0x03 event of
|
|
its own.
|
|
|
|
```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 = "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.
|
|
|
|
```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
|
|
```
|
|
|
|
Saving a Module or a Midi to an **audio** format renders it first, with the render options (see
|
|
[Rendering](#rendering)) taken from the same `opts`; `F.convert` does the same from music bytes:
|
|
|
|
```luau
|
|
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? }`.
|
|
|
|
```luau
|
|
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 |
|
|
|
|
See [FORMATS.md](../FORMATS.md) for each format's capabilities.
|
|
|
|
## 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).
|
|
- A module's `duration` is one pass. `render({ loop = true })` keeps playing past it.
|