merge ws/audio2

This commit is contained in:
4DBug committed 2026-10-31 15:59:38 -05:00
commit f0a23eb676
149 files changed
+23004 -312

No files matched your search

+94 -2
View File
@@ -99,7 +99,8 @@ the guide's [README](README.md#inputs)). Options:
| Option | Formats | Meaning |
|---|---|---|
| `format` | all | decode as this format (`"mp3"`, `"wav"`, ...) and skip detection |
| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac | `Err.LIMIT` past this many frames |
| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac, mpc, ac3 | `Err.LIMIT` past this many frames |
| `drc` | ac3 | dynamic range control: 0 = off (default), 1 = as the stream says |
| `stereo` | opus | downmix surround streams to stereo |
```luau
@@ -179,6 +180,8 @@ Encoder options:
| opus | `bitrate` (default 64000 per channel, 6000..510000); CELT only; resampled to 48 kHz |
| aiff, au, voc | `sampleFormat` (see each format's `init.luau`) |
| m4a, caf | ALAC (lossless); m4a and caf also keep tags |
| adx, vag | `loop = { start, stop }` (frames; default the source's `meta.source.loop`) |
| adpcm | `codec = "ima" \| "ima_wav" \| "ms"`, `blockAlign` (block codecs), `lowFirst` (ima nibble order) |
`bitrate` is in **bits per second** for every encoder (`bitrate = 192000`), as the Decoder's `bitrate` field is. A
value below 1000 is read as kbit/s (`bitrate = 192` is 192000), so older code that passed kbit/s to MP3 still works.
@@ -189,7 +192,7 @@ Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the f
| Read and write | Read only |
|---|---|
| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC |
| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC), qoa, adx, vag, adpcm (raw IMA / MS) | aac (ADTS), m4a / caf AAC, mpc (Musepack SV7 / SV8), ac3 (Dolby Digital), brstm / bcstm / bfstm, KVAG, wav / aifc / caf IMA and MS ADPCM, wavpack (.wv + .wvc), ape, tta |
Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as
Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see
@@ -243,6 +246,95 @@ end
Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or
visualisers.
### Musepack and AC-3
Musepack (`.mpc`, stream versions 7 and 8) decodes gapless, with its APEv2 tags. AC-3 (`.ac3`, Dolby Digital) decodes
every channel layout up to 5.1 without downmixing, in WAVE order (FL FR FC LFE SL SR), with dynamic range control off
unless `drc` asks for it. The AC-3 tracks of MKV, MP4, MPEG-TS and AVI files open as `v.audio` the same way. Both
seek exactly (Musepack SV7 like libmpcdec: 32 frames of pre-roll). E-AC-3 (Dolby Digital Plus) is `Err.UNSUPPORTED`.
```luau
local mpc = assert(F.audio.load(mpcBytes)) -- Musepack: tags, exact length
assert(F.detect(mpcBytes) == "mpc" and mpc.tags.title == "Docs Tone")
assert(mpc.frames == 44100 and mpc.meta.source.version == 8)
local dd = assert(F.audio.open(ac3Bytes)) -- AC-3 5.1: a Decoder like any other
assert(dd.channels == 6 and dd.sampleRate == 48000)
dd:seek(0.25)
local _, n = dd:read(256)
assert(n == 256)
local stereo = assert(F.ops.audio.downmix(F.audio.load(ac3Bytes))) -- 2 channels, ITU-R BS.775
local night = assert(F.audio.load(ac3Bytes, { drc = 1 })) -- the stream's dynamic range gains applied
assert(stereo.channels == 2 and night.channels == 6)
```
### Game audio and ADPCM
Console and game engines store sound as 4-bit ADPCM or QOA: small, and cheap to decode while the game runs. They load
and save like any other audio. Loop points (ADX, VAG, BRSTM) come out in `meta.source.loop` (and `dec.loop`), in
frames, `stop` exclusive; the encoders write them back.
```luau
local tone = F.Types.Audio.new(22050, 1, 22050) -- 1 s of 440 Hz
for i = 0, tone.frames - 1 do
buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(2 * math.pi * 440 * i / 22050))
end
local qoa = assert(F.save(tone, nil, { format = "qoa" })) -- Quite OK Audio: 3.2 bits per sample, as qoa.h writes it
assert(F.detect(qoa) == "qoa" and F.audio.load(qoa).frames == tone.frames)
local adx = assert(F.save(tone, nil, { format = "adx", loop = { start = 0, stop = tone.frames } })) -- CRI ADX
local looped = assert(F.audio.load(adx))
assert(looped.meta.source.loop.stop == tone.frames)
local vag = assert(F.save(tone, nil, { format = "vag" })) -- PlayStation VAG (mono VAGp; stereo is VAGi)
assert(F.audio.load(vag).frames >= tone.frames) -- + the blank frame VAGs start with, and frame padding
```
A raw ADPCM stream has no header, so the layout comes from the options, and only `opts.format` or the `.adpcm` / `.ima`
extension finds it:
<!-- doc:continue -->
```luau
local raw = assert(F.save(tone, nil, { format = "adpcm", codec = "ima" })) -- 4 bits per sample
local back = assert(F.audio.load(raw, { format = "adpcm", codec = "ima", sampleRate = 22050, channels = 1 }))
assert(back.frames == tone.frames)
```
Read only: Nintendo BRSTM / BCSTM / BFSTM (DSP ADPCM or PCM; `F.detect` names the flavour), KVAG, and the ADPCM
inside WAV (IMA, MS), AIFF-C and CAF (ima4). Decoding is bit-exact with vgmstream (ADX, VAG, BRSTM) and ffmpeg
(IMA, MS, ima4, QOA). Seeking is exact everywhere: the decoders keep the predictor state of every block they pass.
### Lossless: WavPack, Monkey's Audio, TTA
WavPack (`.wv`), Monkey's Audio (`.ape`) and TTA (`.tta`) open and load like FLAC. Their tags (APEv2) come out in
`tags` with lower-case keys. Integer streams also have `readInt`, which returns the exact samples as i32. Every
frame of these formats is independent, so `seek` lands on the exact sample.
```luau
local wv = assert(F.audio.open(wvBytes))
assert(wv.bitsPerSample == 16 and wv.lossless and wv.tags.title == "Docs Tone")
local exact, n = wv:readInt(1024) -- i32 samples, as wvunpack writes them
assert(n == 1024 and buffer.readi32(exact, 0) == 0)
local ape = assert(F.audio.load(apeBytes)) -- any level, fast .. insane
assert(ape.meta.source.format == "ape" and ape.tags.artist == "formats-luau")
local tta = assert(F.audio.open(ttaBytes))
tta:seek(0.5)
assert(math.abs(tta:position() - 0.5) < 1e-6)
```
A hybrid WavPack file holds a lossy stream. Its `.wvc` correction file makes it lossless again. Pass the correction
file as `correction`. When you load a file by path, the `.wvc` next to it is found automatically. Without it, the
file decodes lossy.
```luau
local lossy = assert(F.audio.open(hybridWvBytes))
local full = assert(F.audio.open(hybridWvBytes, { correction = hybridWvcBytes }))
assert(lossy.hybrid and not lossy.lossless and full.lossless)
```
<!-- doc:files -->
```luau
local song = assert(F.audio.load("assets/tone_hybrid.wv")) -- reads assets/tone_hybrid.wvc too
assert(song.meta.source.correction == true)
```
## Gotchas
- `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono.
+105 -2
View File
@@ -1,6 +1,7 @@
# Music
Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT) load as a **Module**:
Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT, and the
[other trackers](#more-tracker-formats): 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](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
@@ -26,7 +27,8 @@ assert(audio.channels == 2 and audio.sampleRate == 44100)
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"music"` | |
| `format` | string | `"mod"`, `"s3m"`, `"xm"` or `"it"`: the effect family the engine plays |
| `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](#more-tracker-formats) |
| `title` | string | |
| `channels` | number | pattern channels |
| `speed`, `tempo` | number | initial ticks per row, and BPM (a tick lasts `2.5 / tempo` seconds) |
@@ -312,9 +314,108 @@ assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead")
| 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](../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, ...).
```luau
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.
```luau
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.
```luau
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.
```luau
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`.
```luau
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",
@@ -325,4 +426,6 @@ See [FORMATS.md](../FORMATS.md) for each format's capabilities.
- 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.