plat/audio.rs#
Source: lib/plat/audio.rs
audio -- sound output: streams the app fills, short sounds from memory or files, the
system's own sounds
Stream::open(&Config) -> Result<Stream, AudioError> the app pushes samples into the
stream's ring (write / write_i16; never blocks, takes what fits),
the platform drains it on its audio thread
Stream::open_fill(&Config, fill) fill(&mut [f32]) -> bool tops up the device's buffer
instead (false: this was the last buffer)
s.write(&[f32]) / s.write_i16(&[i16]) -> frames taken; s.writable(), s.queued()
s.start() / s.pause() / s.stop() (empties the ring) / s.finish() (ends once all is played)
s.set_volume(0 ..= 1), s.state() -> State, s.latency_ms(), s.played(), s.underruns(),
s.device(), s.device_changes()
play(&Sound) -> Result<Voice, AudioError> a short sound through the shared mixer; voice.set_volume(v),
(G7b) set_gains(left, right) (lib/game's spatial audio pans with it), stop(), playing();
play_gains(&Sound, left, right): with those gains from its first sample on
play_file(path) a WAV or Ogg Vorbis file through the VFS (app://, data://, ..)
Sound::wav(bytes) / ogg / decode / load(path) / tone(freq, ms)
sound(SOUND_*) -> bool the system's own sound for an event (dialog_sounds(): whether the
platform plays one when a message dialog opens)
available() -> bool an output device / sound service exists here
Samples are f32 in -1 ..= 1, interleaved frames (WAVE channel order: 1 mono, 2 left / right,
6 = 5.1); the device side always runs in f32 at the stream's rate (the system converts the
rate and the channels where needed; the browser's context rate is converted here).
One model everywhere: the ring. The app writes, a platform thread drains -- this works on
all four targets, where a callback on the audio thread does not: the browser's audio runs in
an AudioWorklet that cannot call into the app's WASM instance, so it is fed from a buffer
anyway. The ring also keeps app code (allocation, locks, the UI's pace) off the real-time
thread. open_fill is the same stream without a ring: fill runs on the audio thread
(Windows, Linux, Android) or in the browser worker's pump, and must not block.
Latency: Config::latency_ms (default 40) is split between the device buffer (half, 10 ..= 100
ms) and the ring (the rest; writable() keeps the ring within it); a fill stream gives all of it
to the device buffer. An app that writes from UI timers (16 ms frames) wants >= 50 ms.
A stream starts playing at once (silence until data arrives); pause() first to prefill.
Platforms: Windows WASAPI shared mode, event-driven on its own thread, the default device
followed through IMMNotificationClient (win_audio.rs); Linux the PulseAudio native protocol
(pipewire-pulse on current desktops, WSLg's server), the server moves the stream to a new
default device itself (linux_audio.rs); the browser WebAudio, an AudioWorklet fed from a
SharedArrayBuffer ring or posted buffers, started after a user gesture (State::Blocked
before; web_audio.rs, web/audio.js); Android AAudio through the JNI host (android_audio.rs,
android/bridge.c). macOS and iOS have no backend yet. No device or service:
AudioError::Unavailable.
play() mixes into one stream of 48 kHz stereo that opens on demand and ends after 2 s of
silence (each sound converted to 48 kHz once, while it plays). System sounds: Windows the
sound scheme's aliases (PlaySound: SystemAsterisk, SystemExclamation, SystemHand,
SystemQuestion, .Default, Notification.Default), Linux the freedesktop sound theme
(dialog-information, dialog-warning, dialog-error, dialog-question, bell, message-new-instant
as .oga / .ogg / .wav, the theme of org.gnome.desktop.sound, only while its event-sounds
are on), Android the notification sound and ToneGenerator beeps, the browser short generated
tones (as Linux without a theme). jfgui_AUDIO_DRYRUN=1 / set_dry_run: sound() only prints
"sound: NAME".
Permissions: an app with a manifest needs `audio.output` (policy.rs, docs/PERMISSIONS.md) for
every sound: open / open_fill / play / play_file give AudioError::Denied, sound() false
(also in a dry run), available() false; the refusal is recorded once per run as
"PERMDENY audio.output".
/// the default beep (Windows ".Default", freedesktop "bell")
SOUND_DEFAULT: u32 = 0
/// information (SystemAsterisk, dialog-information)
SOUND_INFO: u32 = 1
/// a warning (SystemExclamation, dialog-warning)
SOUND_WARNING: u32 = 2
/// an error (SystemHand, dialog-error)
SOUND_ERROR: u32 = 3
/// a question (SystemQuestion, dialog-question)
SOUND_QUESTION: u32 = 4
/// a notification (Notification.Default, message-new-instant)
SOUND_NOTIFY: u32 = 5
enum AudioErrorwhy audio is not possibleUnavailable-- no output device or sound service hereInvalid-- a rate or channel count out of rangeFormat-- not a sound file read here (WAV PCM / float, Ogg Vorbis) or a damaged oneIo-- the file could not be readFailed(i32)-- the system refused (its code: an HRESULT, a PulseAudio error, an AAudio result)Denied-- the app's permissions lackaudio.output
enum Statewhat a stream doesStarting-- the device is being opened (browser: until its host answers)PlayingPausedStopped-- stop(): the ring emptied; start() plays againEnded-- finish() or a fill that returned false: everything was played (start() plays again)Blocked-- the browser waits for a user gesture before it plays soundLost-- no device right now (the old one went away); the stream plays again when one appears
struct Config<'a>what a stream playsrate: u32-- frames per second (8000 ..= 192000)channels: u16-- interleaved channels (1 ..= 8)latency_ms: u32-- the latency aimed for, device buffer and ring together (10 ..= 1000 ms)name: &'a str-- the stream's name in the system's mixer ("" = the app's name)
impl Config<'static>
const fn new(rate: u32, channels: u16) -> Config<'static>rate and channels, 40 ms, the app's namestruct Streaman output stream
impl Stream
fn open(cfg: &Config) -> Result<Stream, AudioError>a stream the app writes into (starts playing at once: silence until data arrives)fn open_fill<F: FnMut(&mut [f32]) -> bool + Send + 'static>(cfg: &Config, fill: F) -> Result<Stream, AudioError>a stream that calls fill to top up the device's buffer (on the platform's audio thread or the browser worker's pump; the buffer comes zeroed); fill returns false after its last bufferfn rate(&self) -> u32frames per secondfn channels(&self) -> u16fn write(&mut self, samples: &[f32]) -> usizeinterleaved samples into the ring -> whole frames taken (at most writable(); 0 for a fill stream)fn write_i16(&mut self, samples: &[i16]) -> usizethe same for 16-bit samplesfn writable(&self) -> usizeframes write() takes nowfn queued(&self) -> usizeframes waiting in the ringfn start(&self)play (again): after pause(), stop() or the endfn pause(&self)hold: the queued frames stayfn stop(&self)stop and drop what is queued (ring and device buffer)fn finish(&self)no more data: the stream ends (State::Ended) once the ring is playedfn set_volume(&self, v: f32)0 silent ..= 1 as written (applied here, ramped over one buffer)fn volume(&self) -> f32fn state(&self) -> Statefn latency_ms(&self) -> f32what is written now is heard after about this long (ring, device buffer, the device's own latency; ms)fn played(&self) -> u64frames played so far (handed to the device minus its buffer)fn underruns(&self) -> u32how often the ring ran dry while data was coming (and the device's own count where it reports one)fn device(&self) -> Stringthe output device's name ("" not known yet)fn device_changes(&self) -> u32how often the stream followed a new default device (or the server moved it)fn server_id(&self) -> u32(tests) the server's id of the stream: PulseAudio's sink input index (u32::MAX: none)fn test_device_change(&self)(tests) act as if the default device changed (Windows: reopen on the default device) or the server went away (Linux: the connection is dropped and made anew); the stream plays on, device_changes() counts it. Elsewhere nothing happens.struct Sounddecoded PCM: interleaved f32 samples (cheap to clone: shared)
impl Sound
fn new(rate: u32, channels: u16, samples: Vec<f32>) -> Result<Sound, AudioError>interleaved samples (1 ..= 8 channels, 1 kHz ..= 384 kHz)fn wav(bytes: &[u8]) -> Result<Sound, AudioError>a RIFF WAVE file (PCM 8 / 16 / 24 / 32 bits, float 32 / 64)fn ogg(bytes: &[u8]) -> Result<Sound, AudioError>an Ogg Vorbis file (.ogg, .oga)fn decode(bytes: &[u8]) -> Result<Sound, AudioError>WAV or Ogg Vorbis, told apart by their first bytesfn load(path: &str) -> Result<Sound, AudioError>a sound file through the VFS (app://, data://, a path, ..)fn tone(freq: f32, ms: u32) -> Sounda sine of freq Hz, ms long, 48 kHz mono, at half scale with 5 ms fadesfn rate(&self) -> u32fn channels(&self) -> u16fn frames(&self) -> usizefn samples(&self) -> &[f32]fn duration_ms(&self) -> u32fn to_wav(&self) -> Vec<u8>as a 16-bit PCM WAVE filestruct Voicea sound play() started; dropping the handle lets it play on
impl Voice
fn stop(&self)end it nowfn playing(&self) -> boolstill playing (or waiting for the device)fn set_volume(&self, v: f32)0 ..= 1fn set_gains(&self, left: f32, right: f32)(G7b) the gains of the left and the right channel, 0 ..= 1 each (a mono sound goes to both, a stereo sound keeps its channels): what lib/game's spatial audio pans with. From the mixer's next buffer on, as set_volume, which sets bothstruct MixTest(tests, G7b) the mixer of play() without a device: the same code, buffer by buffer, 48 kHz stereo (what lib/game's spatial audio is checked against, sample for sample). Needs noaudio.output: nothing is played
impl MixTest
fn new() -> MixTestfn play(&mut self, s: &Sound) -> Voicea voice as play() starts one: it is mixed from the next render onfn render(&mut self, frames: usize) -> Vec<f32>the nextframesframes (stereo, interleaved) as the device's next bufferfn voices(&self) -> usizevoices still in the mixerfn rate(&self) -> u32the mixer's ratefn play(s: &Sound) -> Result<Voice, AudioError>play a sound once, mixed with the other sounds of play() (dropping the Voice lets it play on) -> Err(Unavailable) without an output, Err(Denied) withoutaudio.outputfn play_gains(s: &Sound, left: f32, right: f32) -> Result<Voice, AudioError>(G7b) play() with the gains of the left and the right channel from its first sample on (Voice::set_gains; lib/game's spatial audio starts a far sound quiet, not at full volume for a buffer)fn play_file(path: &str) -> Result<Voice, AudioError>play a WAV or Ogg Vorbis file once (see play; withoutaudio.outputthe file is not read)fn set_dry_run(on: bool)true: sound() only prints "sound: NAME" (headless runs; also jfgui_AUDIO_DRYRUN=1)fn sound_name(kind: u32) -> &'static strthe name of a SOUND_* kind ("default", "information", "warning", "error", "question", "notify"; "" for others)fn sound(kind: u32) -> boolthe system's sound for an event (SOUND_*) -> false: nothing played (unknown kind, sounds switched off by the system, no output, noaudio.output)fn dialog_sounds() -> boolwhether message dialogs play the system's sound when they open (Windows like MessageBox; Linux desktops while event sounds are on; not Android, not the browser)fn available() -> boolan output device / sound service exists here (a quick probe; false withoutaudio.output, nothing recorded)fn level(samples: &[f32], channels: usize, ch: usize, rate: u32, freq: f32) -> f32(tests) the amplitude of the sine at freq in channel ch of interleaved frames (Goertzel, Hann window: a full-scale sine reads 1.0)fn resample(samples: &[f32], channels: usize, from: u32, to: u32) -> Vec<f32>(tests) samples converted from one rate to another by the streams' resamplerfn ring_check(n: usize, piece: usize, take: usize, threaded: bool) -> bool(tests) the ring of a push stream: n samples written in pieces ofpieceand read in pieces oftake, by turns or (threaded, Windows / Linux / macOS / iOS) by a writer thread while this one reads -> whether every sample arrived once and in order. The reader gives up after 20 s (a loaded machine): then it tells the writer to stop, which may wait at a full ring, and the check fails instead of waiting for it foreverfn ring_check_within(n: usize, piece: usize, take: usize, threaded: bool, limit_us: u64) -> bool(tests) ring_check with the reader's time limit in µs (a short one: the writer must stop)fn theme_path(kind: u32) -> Option<String>(Linux) (tests, Linux) the sound theme's file for a SOUND_* kind (".disabled": switched off)