10 KiB
audio
Sound read from WAV and Ogg Vorbis, mixed, and played: a mixer of sounds and the voices playing them, and an audio_output playing what it mixes to the system's audio device, on a thread of its own. Long Ogg Vorbis files are streamed, decoded as they play. It's Sakura's, built with blossom, reads std's containers, io, math, thread, and time, and plays through WASAPI on Windows. Its decoders, its mixer, and its output are its own.
import malunal::audio;
var out := audio_output::open() else (e) { ... }; # the default device, at its rate
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.view()) else (e) { ... }; # kept as Ogg Vorbis, decoded as it plays
_ = out.play(coin, playback{ gain = 0.8, pan = -0.3 });
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_pitch(playing, 1.05);
}
out.stop(playing, 1.5); # faded out over 1.5 s
audio::decode(bytes) reads bytes already in memory in either format, and audio::format_of(bytes) says which, by their first few. audio::save writes a WAV file, of 16-bit samples or floats. vorbis::decoder reads an Ogg Vorbis stream's frames as it's asked for them, which the mixer does for a streamed sound. 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, 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 |
mixer.sakura |
mixer, sound_id, voice, and playback: sounds held, decoded or streamed |
voices.sakura |
Voices played, changed, paused, and stopped; buses and the master gain |
mixing.sakura |
Voices mixed: resampled, panned, ramped, and streams decoded as they play |
output.sakura |
audio_output: the mixer shared with the device's thread, or headless |
wasapi.sakura |
The device on Windows: WASAPI's shared mode, through COM's tables |
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, and encode |
vorbis/, audio::vorbis:
| Path | Holds |
|---|---|
vorbis.sakura |
decoder: the headers, frames read and timed by granule positions, and decode |
ogg.sakura |
Ogg's pages, checked by their CRCs, and one stream's packets |
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 |
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. ADPCM, A-law, and µ-law areunsupported, and chunks besidesfmtanddata, assmpl's loop points, 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. Comments are skipped.
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 a Vorbis stream's by Vorbis's order for its count.
Mixing
- Sounds are held by a mixer and named by a
sound_id: decoded, byadd, or kept as their Ogg Vorbis 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; and faded in over some seconds.change,set_gain,set_pan,set_pitch, andpausechange one as it plays, andstopends it at once or faded out. 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. The mix isn't limited: voices summing past 1 clip as the device clips them.
- 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 end into its start; a streamed one loops by decoding its stream again from its start, seamlessly.
The output
audio_output::open opens the system's default device, at the rate the system mixes 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 WASAPI's default 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. A device that stops, as unplugged headphones do, is let go, and the default device opened again as soon as there is one, every quarter second; the voices wait meanwhile. 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, here on a Ryzen 9 9950X3D, the best of three, given one of Factorio's music files, 68 seconds of 44.1 kHz stereo:
| What | Time | Real time |
|---|---|---|
| 32 voices mixed, half resampled, panned, for 10 s at 48 kHz | 94 ms | 105× |
| WAV of 16 bits, 10 s, written and read | 6 ms | 1600× |
| Ogg Vorbis decoded whole | 97 ms | 700× |
| Ogg Vorbis streamed, resampled to 48 kHz | 138 ms | 490× |
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, and refused where compressed; and the mixer's voices at their gains and pans, ramped, ended and looped at their ends, resampled and pitched, on buses, faded, and streamed, exactly as the sound decoded whole plays. A headless output is mixed as asked, and the default device, where there is one, is played to silently until it took 2000 frames.
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; and changed, cut short, of floor 0, or not Vorbis, 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.
- Fuzzing: a checked build was given 6300 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
- MP3, FLAC, and Opus.
- Loop points from files, as WAV's
smplchunk and Vorbis comments give them. - Seeking a streamed voice anywhere but its start.
- Effects: filters, reverb, and a limiter on the mix.
- A device chosen by name, following the default as it changes, and output on Linux.