18 KiB
audio
Sound read from WAV, Ogg Vorbis, FLAC, MP3, and Ogg Opus, mixed, and played: a mixer of sounds and the voices playing them, filtered, sent to buses of reverb, and limited, and an audio_output playing what it mixes to a device the system plays to, on a thread of its own. Long compressed files are streamed, decoded as they play, and sought anywhere. It's Sakura's, built with blossom, reads std's containers, io, math, and thread, and plays through WASAPI on Windows. Its decoders, its mixer, its effects, and its output are its own.
import malunal::audio;
var out := audio_output::open() else (e) { ... }; # the default device, followed as it changes
var clink := audio::load("sounds/coin.wav") else (e) { ... }; # decoded whole
val coin := out.add(move(clink));
val file := io::read_file(&music_path) else (e) { ... };
val music := out.add_streamed(file.span) else (e) { ... }; # kept as its file, decoded as it plays
_ = out.play(coin, playback{ gain = 0.8, pan = -0.3, low_pass = 2000 });
val playing := out.play(music, playback{ looping = true, bus = 1, fade_in = 2 });
{
var held := out.lock(); # several changes, one lock
held.value().set_bus(1, 0.5); # music at half
held.value().set_bus_effects(2, bus_effects{ reverb = reverb{ wet = 0.4, room = 0.8 } });
held.value().set_limiter(limiter{ on = true });
held.value().seek(playing, 30) else (e) { ... }; # half a minute in
}
out.stop(playing, 1.5); # faded out over 1.5 s
audio::decode(bytes) reads bytes already in memory in any format, and audio::format_of(bytes) says which, by their first few. audio::save writes a WAV file, of 16-bit samples or floats. stream::open(bytes) reads a compressed file's frames as it's asked for them, and from anywhere it's sought, which the mixer does for a streamed sound; each format's decoder does so for its own. audio_output::devices() lists the devices the system plays to, and audio_output::open(latency, name) opens one of them by its name. audio_output::headless() is an output of no device, mixed only as the program asks by render, as tests and servers want.
A project reads it by requiring this folder, or its remote, and naming malunal.audio, whose module is malunal::audio, among a target's deps:
requires:
- ../audio
targets:
- name: game
type: program
deps: [malunal.audio]
Layout
audio/ is the module malunal::audio, and each format a module beneath it, as malunal::audio::vorbis.
| Path | Holds |
|---|---|
audio.sakura |
sound, loop_range, audio_error, max_frames, tones, and channels mixed down to two |
formats.sakura |
format, which format bytes, or an extension, say, decode, load, and save |
streams.sakura |
stream: a compressed file of any format read as it's asked, rewound, and sought |
tags.sakura |
Loop points of the comments of Vorbis, FLAC, and Opus, and ID3v2 tags passed |
mixer.sakura |
mixer, sound_id, voice, and playback: sounds held, decoded or streamed |
voices.sakura |
Voices played, changed, sought, paused, and stopped; buses, their effects, the master, and the limiter |
mixing.sakura |
Voices mixed: resampled, filtered, panned, ramped, sent, and streams decoded as they play |
effects.sakura |
bus_effects, reverb, and limiter: biquad filters, Freeverb, and the look-ahead limiter |
output.sakura |
audio_output and audio_device: the mixer shared with the device's thread, or headless |
wasapi.sakura |
The device on Windows: WASAPI's shared mode, through COM's tables, chosen by name or following the default |
elsewhere.sakura |
The device elsewhere: none yet |
windows/ |
ole32.dll, kernel32.dll, and avrt.dll's functions, as malunal::audio::windows |
wav/, audio::wav:
| Path | Holds |
|---|---|
wav.sakura |
RIFF's chunks read, samples of each size made floats, smpl's loop read and written, and encode |
ogg/, audio::ogg, which Vorbis and Opus share:
| Path | Holds |
|---|---|
ogg.sakura |
Ogg's pages, checked by their CRCs, one stream's packets, and pages found by their granule positions |
vorbis/, audio::vorbis:
| Path | Holds |
|---|---|
vorbis.sakura |
decoder: the headers, frames read and timed by granule positions, seeking, and decode |
bits.sakura |
A packet's bits, read lowest first, and Vorbis's floats |
codebooks.sakura |
Codebooks: their Huffman codes by table and tree, and their vectors |
setup.sakura |
The identification and setup headers: floors, residues, mappings, and modes |
floors.sakura |
Floor 1's posts read, and its curve drawn |
residues.sakura |
Residues of types 0, 1, and 2, read from the setup header and decoded |
mdct.sakura |
The inverse MDCT, by an FFT of a quarter of the block, and the window's slopes |
blocks.sakura |
An audio packet decoded: channels uncoupled, blocks windowed and overlapped |
flac/, audio::flac:
| Path | Holds |
|---|---|
flac.sakura |
decoder: the metadata, frames read, seeking by the seek table or by searching, and decode |
frames.sakura |
A frame: its header and CRCs, each subframe, its residual, and side channels made whole |
mp3/, audio::mp3:
| Path | Holds |
|---|---|
mp3.sakura |
decoder: frames found, Xing and LAME's gaps cut, seeking, and decode |
layer3.sakura |
A frame of Layer III: side information, the reservoir, Huffman, stereo, the IMDCT, and synthesis |
tables.sakura |
Layer III's tables, as minimp3 keeps them |
opus/, audio::opus, a port of libopus's decoder, whose license is in opus.sakura:
| Path | Holds |
|---|---|
opus.sakura |
decoder: the Ogg Opus headers, packets' frames, the move between SILK, hybrid, and CELT, seeking, and decode |
range.sakura |
The range decoder every frame is coded with |
celt.sakura |
CELT's decoder: energies, the post-filter, and de-emphasis |
celt_alloc.sakura |
CELT's bit allocation |
celt_bands.sakura |
CELT's bands: pulse vectors, splits, stereo, folding, and anti-collapse |
celt_mdct.sakura |
CELT's inverse MDCT, by a mixed-radix FFT |
celt_tables.sakura |
CELT's tables, generated from libopus's |
silk.sakura |
SILK's decoder: side information, pulses, NLSFs to LPC, LTP and LPC synthesis, stereo, and the resampler |
silk_math.sakura |
SILK's fixed-point arithmetic |
silk_tables.sakura |
SILK's tables, generated from libopus's |
What's read
- WAV: PCM of 8 bits, unsigned, and of 16, 24, and 32 bits, signed; and floats of 32 and 64 bits; each plain or in
WAVE_FORMAT_EXTENSIBLE, of up to eight channels. Adatachunk said to be longer than the file is read as far as the file goes, as writers streaming WAV leave its size unwritten. Asmplchunk's first loop is where a voice playing it loops. ADPCM, A-law, and µ-law areunsupported, and other chunks are skipped. - Ogg Vorbis: every Vorbis I stream but those of floor 0, which no encoder has written since before Vorbis 1.0: codebooks of every lookup, floor 1, residues 0, 1, and 2, coupled channels, and both block sizes, of 64 to 8192 samples. Each page's CRC is checked. Frames are cut from the start and end as the first and last pages' granule positions say, so a stream gives exactly the frames it was encoded from. The first Vorbis stream of a file is read; one chained after it, or multiplexed beside it, isn't.
- FLAC: every stream, of one to eight channels, of 4 to 32 bits a sample, at any rate, its blocks fixed or varying in size, each subframe constant, verbatim, of a fixed predictor, or of linear prediction, its residual Rice-coded or raw. Each frame's header is checked by its CRC-8, and the frame by its CRC-16. An ID3v2 tag before it is passed. FLAC within Ogg isn't read.
- MP3: MPEG-1, 2, and 2.5's Layer III, of one channel or two, of any bit rate but the free format, as minimp3, which is in the public domain, decodes it. A Xing or LAME frame says how much the encoder added before the sound and after, which is cut, as FFmpeg cuts it, so a stream gives the frames it was encoded from. An ID3v2 tag before it is passed. Layers I and II aren't read.
- Ogg Opus: every Opus stream of one or two channels, of mapping family 0, decoded as libopus's float build decodes it: SILK's frames, of speech, at 8, 12, or 16 kHz, resampled to 48 kHz as libopus resamples them; CELT's, of music, of 2.5 to 20 ms; hybrid frames of both; frames of 10 to 120 ms a packet; and the move between them, by CELT's redundant frames, or a crossfade. The head's pre-skip is cut from the start, and the end where the last page's granule position says, and its output gain applied. A sound of Opus is always of 48 kHz.
Every sound is 32-bit floats of one channel or two. A file of more channels, up to eight, is mixed down to two as it's read, by ITU-R BS.775's weights: the front's sides whole, the center and each surround at -3 dB to its side, the back's center at -6 dB to each, and the low frequencies left out, scaled so neither side sums past 1. A WAV file's channels are placed by its channel mask, or Windows's default order, and Vorbis's and FLAC's by their orders for their counts.
Where a sound loops is its loop_points: a WAV file's smpl chunk, or the comments of Vorbis, FLAC, and Opus, LOOPSTART and LOOPLENGTH or LOOPEND, in frames, in any case, as RPG Maker and the tools after it write them. Of a file that says nothing, all of it loops.
Mixing
- Sounds are held by a mixer and named by a
sound_id: decoded, byadd, or kept as their file's bytes, byadd_streamed, so each voice decodes what it plays as it plays it, a few thousand frames ahead. A sound of any rate plays at the mixer's. - Voices play a sound as
playbacksays: at again; panned from -1, all left, to 1, all right; at apitch, a multiple of its rate; looping or not; paused or not; on one of 16 buses; faded in over some seconds; filtered, low pass and high pass, as through a wall or a radio; sent, at some gain, to another bus too, as to one of reverb; and waiting some seconds before it's heard, as a far sound is.change,set_gain,set_pan,set_pitch, andpausechange one as it plays,seekmoves it to anywhere in its sound, andstopends it at once or faded out. A voicesilentplays on unheard, its place moving, as one left out of too many does. A voice that ended, or whose sound was removed, names nothing after, though its place plays another. - Gains: a voice is multiplied by its own gain, its bus's, and the master's. A mono voice is panned by the constant power law, so at the middle each side has it at -3 dB, as loud in all as it is from one side; a stereo voice's pan turns down the side it moves from. Whatever changes is ramped across the next frames mixed, from the gains the last frame had, so nothing clicks.
- Resampling: a voice is read at its sound's rate over the mixer's, times its pitch, by cubic Hermite interpolation, Catmull and Rom's spline through the four frames about where it plays. A sound of the mixer's rate at its own pitch is read exactly. A looping voice reads across its loop's end into its start; a streamed one loops by seeking its stream, seamlessly.
- Seeking: a voice is sought by seconds, decoded or streamed, exactly as it plays from its start: a streamed Vorbis stream by halving its pages, FLAC by its seek table, or by searching its frames' headers, and MP3 by its frames, found as it's opened. Opus is sought by halving its pages too, then decoded from half a second before, so its decoder settles, to within a few ten-thousandths of decoding straight through.
- Effects: each bus has
bus_effects, a low and a high pass, and reverb, as Jezar's Freeverb, which is in the public domain, makes it, of eight combs and four all-passes a side, its room's size, damping, and width as asked; its echoes go on after what feeds it ends. Filters are Butterworth's, of two poles, as Robert Bristow-Johnson's cookbook makes them. The mix has a limiter, off at first, which, on, looks ahead itslookahead, 1.5 ms, and turns the mix down before each peak past itsceilingso that nothing passes it, then up again over itsrelease; the mix is that late.
The output
audio_output::open opens a device, at the rate the system mixes it at, and starts a thread that waits on the device's event and fills its buffer, about latency seconds of it, 20 ms unless asked, from the mixer, holding its lock while it mixes. lock holds the mixer for the program, so a game makes a frame's changes under one lock; add, play, and the rest each lock it once.
On Windows the device is a WASAPI render endpoint in shared mode, given frames of two 32-bit floats, which Windows converts to the device's format and maps to its speakers. The thread runs under the Multimedia Class Scheduler Service as "Pro Audio" does. devices lists the endpoints plugged in and on, each by its friendly name and id, and which is the default; open takes either, or none, for the default, which it then follows: every quarter second of what it plays, it asks which is the default, and moves to another the system made so. A device that stops, as unplugged headphones do, is let go and opened again as soon as it can be; the voices wait meanwhile. The thread reads no clock, telling time by the frames it plays. Elsewhere there's no device yet, so open says no_device, and a game plays on with a headless output.
Speed
blossom build, then run malunal.audio.bench, given compressed files, here on a Ryzen 9 9950X3D, the best of three:
| What | Real time |
|---|---|
| 32 voices mixed, half resampled, panned, for 10 s at 48 kHz | 109× |
| WAV of 16 bits, 10 s, written and read | 2200× |
| Ogg Vorbis decoded whole, 68 s of 44.1 kHz stereo music | 700× |
| FLAC decoded whole, 31 files of real encoders | 900× |
| MP3 decoded whole, 127 files of every rate of MPEG-1, 2, and 2.5 | 760× |
| Opus decoded whole, RFC 8251's test vectors, of CELT, hybrid, and SILK | 390× to 660× |
| Opus streamed, at 48 kHz | 355× to 560× |
So a voice costs about 6 ns a frame mixed, and 32 of them about one percent of a core.
Testing
blossom test runs tests/: tones, formats by their bytes and extensions, and channels mixed down; WAV written and read back, of every sample size, of four channels placed by their mask, cut short, refused where compressed, and its smpl loop kept; the mixer's voices at their gains and pans, ramped, ended and looped at their ends and their loop points, resampled and pitched, on buses, faded, sought, delayed, played silent, and streamed, exactly as the sound decoded whole plays; voices and buses filtered, sent to reverb whose echoes go on and die away, and the limiter holding the mix at its ceiling; and a headless output mixed as asked, the default device, where there is one, played to silently until it took 2000 frames, and the system's devices listed and one opened by its name.
The tests' Ogg Vorbis streams are made by a small encoder in tests/streams.sakura, written as tests/pages.sakura packs bits and laces pages, of both block sizes, single and coupled channels, and residues of types 1 and 2, with the frames each should decode to worked out by tests/spec.sakura as the spec defines them, directly: the inverse MDCT as its sum, and the windowed blocks laid on one timeline. Each decodes to within 1e-4 of those, cut where its last granule position says; read in pieces of 13 frames and again from the start, the same; sought anywhere, the same; its comments' loop points read; and changed, cut short, of floor 0, or not Vorbis, refused. FLAC's streams are made by an encoder in tests/flacs.sakura, of every kind of subframe, channel assignment, and residual, of 24 bits, wasted bits, and blocks of every size, and of six channels, each decoded to exactly the samples it was made of, sought by its seek table and by searching. MP3 and Opus are read of tests/files/, tones encoded by LAME and libopus, through FFmpeg, of sines: each near its sines, MP3 sought exactly, and Opus, made again of its packets a page each, sought by its pages, its gain and its comments' loop points read, and what isn't read refused.
What's read was checked further against outside references, which aren't part of the repository:
- Ogg Vorbis: 63 files from 1 KB to 9 MB, Factorio's sounds and music, Ableton Live's previews, and three songs, against Xiph's libvorbisfile: every one the same length, and every sample within 5e-7.
- FLAC: 31 files of real encoders, each decoded to the samples its STREAMINFO's MD5 is of.
- MP3: 73 files of real encoders, and 54 LAME made of every rate of MPEG-1, 2, and 2.5, of one channel and two, of 16 to 160 kilobits a second, each decoded to as many frames as FFmpeg decodes it to, every sample within 6.4e-6 of FFmpeg's.
- Opus: RFC 8251's 12 test vectors, decoded in stereo within one step of 16 bits of libopus's own output, those of SILK alone exactly; and in one channel, 63 dB or nearer to libopus's mix of them; all 24 decoded by a checked build, faulting at none. CELT's frames match FFmpeg's within 1.5e-7.
- Fuzzing: a checked build was given 6300 Ogg Vorbis files with bytes changed, their pages' CRCs worked out again so the changes reach past them, decoded whole and streamed, and faulted at none.
Not yet
- Output on Linux, in Phase 4.
- Opus's concealment: a lost or empty frame decodes as silence, rather than carrying on what came before as libopus does, and a frame's redundant copy, kept for loss, is passed over. Streams of more than two channels, of mapping families 1 and 255, aren't read.
- Chained streams of Ogg, FLAC within Ogg, MP3's free format, and Layers I and II.