From 6902e8c81a650d246dd901b620e5c284bf6a6bdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?moon=20dav=C3=A9?= Date: Tue, 1 Dec 2026 00:02:45 -0500 Subject: [PATCH] processing_audio: audio devices and stream, opt-in at init A sketch enables audio with ConfigKey::AudioEnabled before init(). Seedling then builds the context and graph at startup and we open the stream during init(); without the flag no device is opened and the audio functions return AudioNotEnabled. We manage the cpal stream ourselves instead of seedling's CpalPlatformPlugin: - one output and one optional input device (none by default, so no microphone prompt), by name or index; - a named output is never swapped for another device: if it disappears the stream stops, and it resumes on the same graph when the device returns; - device, sample rate and block size can change while running; - status, info and stream events (lost/restored devices, xruns, restarts). Tests run on a mock backend that pulls blocks without audio hardware, including restarts at changing block sizes. --- Cargo.lock | 2 + crates/processing_audio/Cargo.toml | 5 + crates/processing_audio/src/device.rs | 743 ++++++++++++++++++++++++++ crates/processing_audio/src/lib.rs | 221 +++++++- crates/processing_audio/src/tests.rs | 200 +++++++ crates/processing_core/src/config.rs | 14 + crates/processing_core/src/error.rs | 6 + src/lib.rs | 1 + src/prelude.rs | 7 + 9 files changed, 1197 insertions(+), 2 deletions(-) create mode 100644 crates/processing_audio/src/device.rs create mode 100644 crates/processing_audio/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 0929605a..3245a7a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6238,8 +6238,10 @@ dependencies = [ name = "processing_audio" version = "0.4.0" dependencies = [ + "audioadapter-buffers", "bevy", "bevy_seedling", + "processing_core", ] [[package]] diff --git a/crates/processing_audio/Cargo.toml b/crates/processing_audio/Cargo.toml index 94a614d5..9b33b617 100644 --- a/crates/processing_audio/Cargo.toml +++ b/crates/processing_audio/Cargo.toml @@ -6,7 +6,12 @@ rust-version.workspace = true [dependencies] bevy = { workspace = true } +processing_core = { workspace = true } bevy_seedling = { git = "https://github.com/catilac/bevy_seedling", branch = "processing-dev" } +[dev-dependencies] +# For the tests' mock backend, which runs the graph without audio hardware. +audioadapter-buffers = { version = "4.0", default-features = false } + [lints] workspace = true diff --git a/crates/processing_audio/src/device.rs b/crates/processing_audio/src/device.rs new file mode 100644 index 00000000..34e2f575 --- /dev/null +++ b/crates/processing_audio/src/device.rs @@ -0,0 +1,743 @@ +//! Audio device selection and stream lifecycle. +//! +//! This replaces seedling's `CpalPlatformPlugin` so libprocessing decides what +//! happens when devices come and go: +//! +//! - A named output device is never swapped for the system default. If it +//! disappears, the stream stops and we wait for it to come back. With +//! DC-coupled CV on the outputs, falling back to laptop speakers is unsafe. +//! - A lost input device is reconnected when it reappears. +//! - Device, sample rate and block size can all change while running; the +//! audio graph (nodes, edges, samples) survives every restart. +//! +//! The `CpalStream` lives on seedling's audio control thread (the thread that +//! runs `AudioContext::with` closures), in a thread local, because cpal +//! streams are not `Send` on every platform. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::num::NonZeroU32; +use std::time::{Duration, Instant}; + +use bevy::prelude::*; +use bevy_seedling::context::{ + AudioContext, PreStreamRestartEvent, SampleRate, StreamRestartEvent, StreamStartEvent, +}; +use bevy_seedling::firewheel::FirewheelContext; +use bevy_seedling::firewheel::cpal::cpal::ErrorKind; +use bevy_seedling::firewheel::cpal::cpal::traits::DeviceTrait; +use bevy_seedling::firewheel::cpal::{ + CpalConfig, CpalInputConfig, CpalOutputConfig, CpalStream, DeviceId, DeviceInfo, + HostEnumerator, IoStreamError, default_host_enumerator, +}; + +use processing_core::config::{Config, ConfigKey}; +use processing_core::error::{ProcessingError, Result}; + +/// Block size used when none is configured. About 5 ms at 48 kHz. +pub const DEFAULT_BLOCK_FRAMES: u32 = 256; +/// The graph always has at least this many input and output ports, so a +/// patch keeps its connections when switching to a narrower device. +pub const DEFAULT_GRAPH_CHANNELS: u32 = 8; +/// The most graph channels we allow. +pub const MAX_GRAPH_CHANNELS: u32 = 64; +/// How often to look for a lost device. +const PROBE_INTERVAL: Duration = Duration::from_secs(1); +/// How long to wait for the audio thread to start or stop. +const STREAM_TIMEOUT: Duration = Duration::from_millis(500); +/// Oldest events are dropped once this many are waiting. +const MAX_QUEUED_EVENTS: usize = 256; + +/// Which device to use. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AudioDevice { + /// The system default device. + Default, + /// The first device whose name matches: exact (case-insensitive) first, + /// then the first that contains it. + Named(String), +} + +impl AudioDevice { + fn label(&self) -> String { + match self { + AudioDevice::Default => "default".to_string(), + AudioDevice::Named(name) => name.clone(), + } + } +} + +/// Parse a device setting: `"default"` or part of a device name. +/// For inputs, `"none"` means no input device. +pub fn parse_device(value: &str) -> Option { + match value.trim().to_lowercase().as_str() { + "none" | "" => None, + "default" => Some(AudioDevice::Default), + _ => Some(AudioDevice::Named(value.trim().to_string())), + } +} + +/// Whether audio is flowing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AudioStatus { + /// The stream is running. + Running, + /// The wanted output device is missing. Nothing plays until it returns. + OutputLost, +} + +/// Something that happened to the audio stream. Read with `audio_events()`. +#[derive(Clone, Debug, PartialEq)] +pub enum AudioEvent { + OutputLost { + device: String, + }, + OutputRestored { + device: String, + }, + InputLost { + device: String, + }, + InputRestored { + device: String, + }, + /// The stream restarted (device, sample rate or block size changed, or a + /// device came back). Nodes and edges are kept. + StreamRestarted { + sample_rate: u32, + block_frames: u32, + }, + /// The stream could not start; we keep retrying. + StreamFailed { + message: String, + }, + /// The device has more channels than the graph; the extra channels are + /// not reachable. Raise `ConfigKey::AudioGraphChannels` to use them. + DeviceWiderThanGraph { + device_channels: u32, + graph_channels: u32, + }, + /// An input or output buffer under- or overran (an audible glitch). + Xrun { + input: bool, + }, +} + +/// A snapshot of the audio stream. +#[derive(Clone, Debug, PartialEq)] +pub struct AudioInfo { + pub status: AudioStatus, + pub sample_rate: u32, + pub block_frames: u32, + /// Channels the input device provides (0 if no input). + pub device_inputs: u32, + /// Channels the output device provides. + pub device_outputs: u32, + /// Ports on `audio_input()`. Fixed at init. + pub graph_inputs: u32, + /// Ports on `audio_output()`. Fixed at init. + pub graph_outputs: u32, + /// Latency added between input and output, in seconds. + pub input_to_output_latency: f64, + pub output_device: Option, + pub input_device: Option, +} + +#[derive(Clone, Debug, Default)] +struct StreamReport { + sample_rate: u32, + block_frames: u32, + device_inputs: u32, + device_outputs: u32, + input_to_output_latency: f64, + out_device_id: Option, + in_device_id: Option, +} + +#[derive(Resource)] +pub(crate) struct AudioDeviceState { + pub want_output: AudioDevice, + pub want_input: Option, + pub sample_rate: Option, + pub block_frames: u32, + pub graph_inputs: u32, + pub graph_outputs: u32, + status: AudioStatus, + input_lost: bool, + output_name: Option, + input_name: Option, + stream: Option, + events: VecDeque, + last_probe: Option, +} + +impl AudioDeviceState { + pub fn from_config(config: Option<&Config>) -> Self { + let get = |key| config.and_then(|c| c.get(key)).map(|s| s.as_str()); + let want_output = get(ConfigKey::AudioOutputDevice) + .and_then(parse_device) + .unwrap_or(AudioDevice::Default); + let want_input = match get(ConfigKey::AudioInputDevice) { + Some(value) => parse_device(value), + // No microphone unless the sketch asks for one. + None => None, + }; + let parse_u32 = |key| get(key).and_then(|s| s.trim().parse::().ok()); + let min_channels = parse_u32(ConfigKey::AudioGraphChannels) + .unwrap_or(DEFAULT_GRAPH_CHANNELS) + .clamp(1, MAX_GRAPH_CHANNELS); + + Self { + want_output, + want_input, + sample_rate: parse_u32(ConfigKey::AudioSampleRate), + block_frames: parse_u32(ConfigKey::AudioBlockFrames).unwrap_or(DEFAULT_BLOCK_FRAMES), + graph_inputs: min_channels, + graph_outputs: min_channels, + // The stream opens at startup, which sets the real status. A + // missing output there is then reported as `OutputLost`. + status: AudioStatus::Running, + input_lost: false, + output_name: None, + input_name: None, + stream: None, + events: VecDeque::new(), + last_probe: None, + } + } + + /// Widen the graph to fit the devices present right now. Only possible + /// before the audio context exists. + pub fn fit_graph_to_devices(&mut self) { + let host = default_host_enumerator(); + if let Some(ch) = find_device(&host.output_devices(), &self.want_output) + .and_then(|d| device_channels(&host, &d.id, false)) + { + self.graph_outputs = self.graph_outputs.max(ch.min(MAX_GRAPH_CHANNELS)); + } + if let Some(want) = &self.want_input + && let Some(ch) = find_device(&host.input_devices(), want) + .and_then(|d| device_channels(&host, &d.id, true)) + { + self.graph_inputs = self.graph_inputs.max(ch.min(MAX_GRAPH_CHANNELS)); + } + } + + fn push(&mut self, event: AudioEvent) { + if self.events.len() >= MAX_QUEUED_EVENTS { + self.events.pop_front(); + } + self.events.push_back(event); + } + + pub fn drain_events(&mut self) -> Vec { + self.events.drain(..).collect() + } + + pub fn status(&self) -> AudioStatus { + self.status + } + + pub fn info(&self, fallback_rate: Option) -> AudioInfo { + let s = self.stream.clone().unwrap_or_default(); + AudioInfo { + status: self.status, + sample_rate: if self.stream.is_some() { + s.sample_rate + } else { + fallback_rate.unwrap_or(0) + }, + block_frames: if self.stream.is_some() { + s.block_frames + } else { + self.block_frames + }, + device_inputs: s.device_inputs, + device_outputs: s.device_outputs, + graph_inputs: self.graph_inputs, + graph_outputs: self.graph_outputs, + input_to_output_latency: s.input_to_output_latency, + output_device: self.output_name.clone(), + input_device: self.input_name.clone(), + } + } +} + +/// Find a device by selector. +pub(crate) fn find_device<'a>( + devices: &'a [DeviceInfo], + want: &AudioDevice, +) -> Option<&'a DeviceInfo> { + match want { + AudioDevice::Default => devices.iter().find(|d| d.is_default), + AudioDevice::Named(name) => { + let names: Vec<&str> = devices + .iter() + .map(|d| d.name.as_deref().unwrap_or("")) + .collect(); + match_name(&names, name).map(|i| &devices[i]) + } + } +} + +/// Index of the best match for `needle`: an exact, case-insensitive match +/// wins, otherwise the first name that contains it. +pub(crate) fn match_name(names: &[&str], needle: &str) -> Option { + let needle = needle.to_lowercase(); + names + .iter() + .position(|n| n.to_lowercase() == needle) + .or_else(|| { + names + .iter() + .position(|n| n.to_lowercase().contains(&needle)) + }) +} + +fn device_name(info: &DeviceInfo) -> String { + info.name + .clone() + .unwrap_or_else(|| "".into()) +} + +fn device_channels(host: &HostEnumerator, id: &DeviceId, input: bool) -> Option { + let device = host.get_device(id)?; + let config = if input { + device.default_input_config().ok()? + } else { + device.default_output_config().ok()? + }; + Some(config.channels() as u32) +} + +/// Sorted, numbered device names, like `midi_list_ports`. +pub(crate) fn list_devices(input: bool) -> Vec { + let host = default_host_enumerator(); + let devices = if input { + host.input_devices() + } else { + host.output_devices() + }; + sorted_names(&devices) + .into_iter() + .enumerate() + .map(|(i, name)| format!("{i}: {name}")) + .collect() +} + +fn sorted_names(devices: &[DeviceInfo]) -> Vec { + let mut names: Vec = devices.iter().map(device_name).collect(); + names.sort(); + names +} + +/// Resolve an index into the sorted device list to a device selector. +pub(crate) fn device_by_index(index: usize, input: bool) -> Result { + let host = default_host_enumerator(); + let devices = if input { + host.input_devices() + } else { + host.output_devices() + }; + sorted_names(&devices) + .into_iter() + .nth(index) + .map(AudioDevice::Named) + .ok_or(ProcessingError::AudioDeviceIndexNotFound(index)) +} + +/// Check that a named device exists right now, so typos fail loudly instead +/// of looking like a lost device. +pub(crate) fn check_device_exists(want: &AudioDevice, input: bool) -> Result<()> { + let AudioDevice::Named(name) = want else { + return Ok(()); + }; + let host = default_host_enumerator(); + let devices = if input { + host.input_devices() + } else { + host.output_devices() + }; + if find_device(&devices, want).is_some() { + return Ok(()); + } + let available = sorted_names(&devices); + let available = if available.is_empty() { + "none".to_string() + } else { + available.join(", ") + }; + Err(ProcessingError::AudioDeviceNotFound( + name.clone(), + available, + )) +} + +// --- stream ownership on the audio control thread --- + +thread_local! { + static STREAM: RefCell> = const { RefCell::new(None) }; +} + +struct Health { + output_ok: bool, + input_ok: bool, + xruns: Vec, +} + +fn poll_health(context: &mut AudioContext) -> Option { + context.with(|_| { + STREAM.with_borrow_mut(|stream| { + let stream = stream.as_mut()?; + let mut xruns = Vec::new(); + for error in stream.poll_status() { + let (input, err) = match &error { + IoStreamError::Input(e) => (true, e), + IoStreamError::Output(e) => (false, e), + }; + match err.kind() { + ErrorKind::Xrun => xruns.push(input), + ErrorKind::DeviceChanged => {} + _ => warn!("audio stream: {error}"), + } + } + Some(Health { + output_ok: stream.output_stream_ok(), + input_ok: stream.input_stream_ok(), + xruns, + }) + }) + }) +} + +fn drop_stream(context: &mut AudioContext) { + context.with(|cx| STREAM.with_borrow_mut(|stream| release_stream(cx, stream))); +} + +/// Drop the stream and wait for its processor to come back, so the context +/// can be activated again. +fn release_stream(cx: &mut FirewheelContext, slot: &mut Option) { + if slot.take().is_some() { + wait_until_inactive(cx); + } +} + +/// Wait for a stopped stream's processor to be handed back to the context. +/// The audio thread returns it on its own schedule, and Firewheel refuses to +/// activate until it has. +pub(crate) fn wait_until_inactive(cx: &mut FirewheelContext) { + let began = Instant::now(); + while cx.is_active() { + if began.elapsed() > STREAM_TIMEOUT { + warn!("audio processor still active {STREAM_TIMEOUT:?} after its stream stopped"); + return; + } + std::thread::sleep(Duration::from_millis(1)); + } +} + +fn open_stream( + context: &mut AudioContext, + config: CpalConfig, +) -> std::result::Result { + context.with(move |cx| { + STREAM.with_borrow_mut(|slot| { + // The old stream must be gone before the context can be activated again. + release_stream(cx, slot); + let stream = CpalStream::new(cx, config).map_err(|e| e.to_string())?; + let info = stream.info(); + let report = StreamReport { + sample_rate: info.sample_rate.get(), + block_frames: info.max_block_frames.get(), + device_inputs: info.num_stream_in_channels, + device_outputs: info.num_stream_out_channels, + input_to_output_latency: info.input_to_output_latency_seconds, + out_device_id: info.out_device_id.clone(), + in_device_id: info.in_device_id.clone(), + }; + *slot = Some(stream); + Ok(report) + }) + }) +} + +// --- systems --- + +/// Open the stream at startup. Always publishes a `SampleRate` and +/// `StreamStartEvent`, even with no device, so seedling finishes setting up +/// the graph and the device can be picked up later. +pub(crate) fn start_stream(world: &mut World) { + start_or_restart(world); + let state = world.resource::(); + if state.status == AudioStatus::OutputLost { + let device = state.want_output.label(); + warn!("audio output {device:?} not found; waiting for it to appear"); + } + if !world.contains_resource::() { + let rate = world + .resource::() + .sample_rate + .and_then(NonZeroU32::new) + .unwrap_or(NonZeroU32::new(48_000).unwrap()); + world.insert_resource(SampleRate::new(rate)); + world.trigger(StreamStartEvent { sample_rate: rate }); + } +} + +/// Watch the stream each frame: report glitches, notice lost devices, and +/// look for them to come back. +pub(crate) fn manage_stream(world: &mut World) { + let health = poll_health(&mut world.resource_mut::()); + + if let Some(health) = health { + let mut state = world.resource_mut::(); + for input in health.xruns { + state.push(AudioEvent::Xrun { input }); + } + if !health.input_ok && !state.input_lost { + state.input_lost = true; + let device = state.input_name.take().unwrap_or_default(); + state.push(AudioEvent::InputLost { device }); + } + if !health.output_ok { + mark_output_lost(&mut state); + drop_stream(&mut world.resource_mut::()); + } + } + + let state = world.resource::(); + let waiting = + state.status == AudioStatus::OutputLost || (state.input_lost && state.want_input.is_some()); + if waiting + && state + .last_probe + .is_none_or(|t| t.elapsed() >= PROBE_INTERVAL) + { + let back = wanted_devices_present(state); + world.resource_mut::().last_probe = Some(Instant::now()); + if back { + start_or_restart(world); + } + } +} + +/// Apply new device settings right away (from an API call). +pub(crate) fn manage_restart_now(world: &mut World) { + start_or_restart(world); + world.flush(); +} + +fn mark_output_lost(state: &mut AudioDeviceState) { + if state.status != AudioStatus::OutputLost { + state.status = AudioStatus::OutputLost; + let device = state + .output_name + .take() + .unwrap_or_else(|| state.want_output.label()); + state.push(AudioEvent::OutputLost { device }); + } + state.stream = None; +} + +/// True when restarting now would get us something we are missing. +fn wanted_devices_present(state: &AudioDeviceState) -> bool { + let host = default_host_enumerator(); + let output_present = find_device(&host.output_devices(), &state.want_output).is_some(); + if state.status == AudioStatus::OutputLost { + return output_present; + } + match &state.want_input { + Some(want) if state.input_lost => { + output_present && find_device(&host.input_devices(), want).is_some() + } + _ => false, + } +} + +fn start_or_restart(world: &mut World) { + let host = default_host_enumerator(); + let outputs = host.output_devices(); + let inputs = host.input_devices(); + + let (want_output, want_input, sample_rate, block_frames, graph_inputs, graph_outputs) = { + let s = world.resource::(); + ( + s.want_output.clone(), + s.want_input.clone(), + s.sample_rate, + s.block_frames, + s.graph_inputs, + s.graph_outputs, + ) + }; + + let Some(output) = find_device(&outputs, &want_output).cloned() else { + // Never fall back to another output: stop and wait for this one. + mark_output_lost(&mut world.resource_mut::()); + drop_stream(&mut world.resource_mut::()); + return; + }; + let input = want_input + .as_ref() + .and_then(|want| find_device(&inputs, want)) + .cloned(); + + let config = CpalConfig { + output: CpalOutputConfig { + device_id: Some(output.id.clone()), + desired_sample_rate: sample_rate, + desired_block_frames: Some(block_frames), + // Never play on another device. If ours vanishes between + // enumerating and opening, the open fails and we wait for it. + fallback: false, + ..default() + }, + input: input.as_ref().map(|input| CpalInputConfig { + device_id: Some(input.id.clone()), + desired_block_frames: Some(block_frames), + fallback: false, + fail_on_no_input: false, + ..default() + }), + }; + + let was_running = world.contains_resource::(); + if was_running { + world.trigger(PreStreamRestartEvent); + } + + let opened = open_stream(&mut world.resource_mut::(), config); + let report = match opened { + Ok(report) if report.out_device_id.as_ref() == Some(&output.id) => report, + Ok(_) => { + // cpal swapped in another device behind our back (the wanted one + // vanished mid-open). Stop rather than play somewhere unexpected. + drop_stream(&mut world.resource_mut::()); + mark_output_lost(&mut world.resource_mut::()); + return; + } + Err(message) => { + let mut state = world.resource_mut::(); + mark_output_lost(&mut state); + state.push(AudioEvent::StreamFailed { message }); + return; + } + }; + + let rate = NonZeroU32::new(report.sample_rate).unwrap_or(NonZeroU32::MIN); + match world.get_resource::() { + Some(current) => { + let previous_rate = current.get(); + current.set(rate); + world.trigger(StreamRestartEvent { + previous_rate, + current_rate: rate, + }); + } + None => { + world.insert_resource(SampleRate::new(rate)); + world.trigger(StreamStartEvent { sample_rate: rate }); + } + } + + let mut state = world.resource_mut::(); + let output_name = device_name(&output); + if state.status == AudioStatus::OutputLost && state.stream.is_none() && was_running { + state.push(AudioEvent::OutputRestored { + device: output_name.clone(), + }); + } + let input_name = input + .as_ref() + .filter(|i| report.in_device_id.as_ref() == Some(&i.id)) + .map(device_name); + match (&input_name, state.input_lost) { + (Some(name), true) => { + state.input_lost = false; + state.push(AudioEvent::InputRestored { + device: name.clone(), + }); + } + (None, false) if want_input.is_some() => { + state.input_lost = true; + let device = want_input.as_ref().map(|w| w.label()).unwrap_or_default(); + state.push(AudioEvent::InputLost { device }); + } + _ => {} + } + if was_running { + state.push(AudioEvent::StreamRestarted { + sample_rate: report.sample_rate, + block_frames: report.block_frames, + }); + } + for (device_channels, graph_channels) in [ + (report.device_outputs, graph_outputs), + (report.device_inputs, graph_inputs), + ] { + if device_channels > graph_channels { + state.push(AudioEvent::DeviceWiderThanGraph { + device_channels, + graph_channels, + }); + } + } + state.status = AudioStatus::Running; + state.output_name = Some(output_name); + state.input_name = input_name; + state.stream = Some(report); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_names_exact_then_partial() { + let names = [ + "MacBook Pro Speakers", + "ES-9", + "ES-9 Extra", + "BlackHole 2ch", + ]; + assert_eq!(match_name(&names, "es-9"), Some(1)); + assert_eq!(match_name(&names, "extra"), Some(2)); + assert_eq!(match_name(&names, "BLACKHOLE"), Some(3)); + assert_eq!(match_name(&names, "missing"), None); + // an exact match beats an earlier partial one + let names = ["Synth Out", "Synth"]; + assert_eq!(match_name(&names, "synth"), Some(1)); + } + + #[test] + fn parses_device_settings() { + assert_eq!(parse_device("default"), Some(AudioDevice::Default)); + assert_eq!(parse_device(" Default "), Some(AudioDevice::Default)); + assert_eq!(parse_device("none"), None); + assert_eq!( + parse_device("ES-9"), + Some(AudioDevice::Named("ES-9".to_string())) + ); + } + + #[test] + fn config_sets_initial_state() { + let mut config = Config::new(); + config.set(ConfigKey::AudioOutputDevice, "ES-9".into()); + config.set(ConfigKey::AudioInputDevice, "none".into()); + config.set(ConfigKey::AudioBlockFrames, "128".into()); + config.set(ConfigKey::AudioGraphChannels, "16".into()); + let state = AudioDeviceState::from_config(Some(&config)); + assert_eq!(state.want_output, AudioDevice::Named("ES-9".into())); + assert_eq!(state.want_input, None); + assert_eq!(state.block_frames, 128); + assert_eq!(state.graph_inputs, 16); + assert_eq!(state.graph_outputs, 16); + + let state = AudioDeviceState::from_config(None); + assert_eq!(state.want_output, AudioDevice::Default); + assert_eq!(state.want_input, None); + assert_eq!(state.block_frames, DEFAULT_BLOCK_FRAMES); + assert_eq!(state.graph_outputs, DEFAULT_GRAPH_CHANNELS); + } +} diff --git a/crates/processing_audio/src/lib.rs b/crates/processing_audio/src/lib.rs index b9620636..0d43edb5 100644 --- a/crates/processing_audio/src/lib.rs +++ b/crates/processing_audio/src/lib.rs @@ -1,10 +1,227 @@ +//! Low-level audio for libprocessing, built on bevy_seedling and Firewheel. +//! +//! A sketch decides up front whether it has audio: set +//! [`ConfigKey::AudioEnabled`](processing_core::config::ConfigKey::AudioEnabled) +//! to `"true"` before `init()`. Then the audio graph is built and the stream +//! opened during `init()`. Without it no device is opened, nothing runs per +//! frame, and the audio functions other than device listing return +//! `AudioNotEnabled`. +//! +//! The building blocks: +//! +//! - **Devices.** One output device and one optional input device (none +//! unless asked for), chosen with +//! [`ConfigKey`](processing_core::config::ConfigKey)`::Audio*` before +//! `init()` or with the `audio_set_*` functions while running. Unplugging a +//! device stops the stream and never moves audio to another output; +//! plugging it back in resumes on the same patch. See [`audio_events`]. + use bevy::prelude::*; -use bevy_seedling::prelude::*; +#[cfg(not(target_arch = "wasm32"))] +mod device; + +#[cfg(not(target_arch = "wasm32"))] +pub use native::*; + +/// Adds audio if [`ConfigKey::AudioEnabled`] is `"true"`, and does nothing +/// otherwise. Reads its settings from the +/// [`Config`](processing_core::config::Config) resource, so add it after +/// that is inserted. +/// +/// [`ConfigKey::AudioEnabled`]: processing_core::config::ConfigKey::AudioEnabled pub struct AudioPlugin; impl Plugin for AudioPlugin { + #[cfg(not(target_arch = "wasm32"))] fn build(&self, app: &mut App) { - app.add_plugins(SeedlingPlugins); + use processing_core::config::{Config, ConfigKey}; + + let enabled = app + .world() + .get_resource::() + .and_then(|c| c.get(ConfigKey::AudioEnabled)) + .is_some_and(|v| v.trim().eq_ignore_ascii_case("true")); + if enabled { + native::build(app, native::AudioBackend::Cpal); + } } + + #[cfg(target_arch = "wasm32")] + fn build(&self, _app: &mut App) {} } + +#[cfg(not(target_arch = "wasm32"))] +mod native { + use std::time::Duration; + + use bevy::prelude::*; + use bevy_seedling::context::{AudioContextConfig, SampleRate}; + use bevy_seedling::node::DiffRate; + use bevy_seedling::platform::cpal::CpalPlatformPlugin; + use bevy_seedling::prelude::*; + + use processing_core::app_mut; + use processing_core::config::Config; + use processing_core::error::{ProcessingError, Result}; + + pub use crate::device::{AudioDevice, AudioEvent, AudioInfo, AudioStatus, parse_device}; + + use crate::device::{self, AudioDeviceState}; + + /// What opens the stream at startup. + #[derive(Resource, Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum AudioBackend { + /// Real devices. + Cpal, + /// A thread that pulls blocks with no hardware, for tests. + #[cfg(test)] + Mock, + } + + /// Register seedling and our systems. Seedling builds the context and + /// graph at `PreStartup`, and we open the stream at `PostStartup`, so + /// audio is running by the end of `init()`. + pub(crate) fn build(app: &mut App, backend: AudioBackend) { + let mut state = AudioDeviceState::from_config(app.world().get_resource::()); + // Firewheel's graph width is fixed when the context is built, so + // size it for the devices present now. + if backend == AudioBackend::Cpal { + state.fit_graph_to_devices(); + } + + let channels = |n: u32| ChannelCount::new(n).expect("graph width is clamped"); + let context_config = AudioContextConfig(FirewheelConfig { + num_graph_inputs: channels(state.graph_inputs), + num_graph_outputs: channels(state.graph_outputs), + // The default -70 dB input gate would zero quiet blocks; keep + // the input path clean for CV. + clamp_graph_inputs_below: None, + channel_capacity: 128, + ..default() + }); + + // No default buses, limiter or pools: the sketch builds the graph. + app.insert_resource(AudioGraphTemplate::Empty) + .insert_resource(context_config) + // Send parameter changes every update, not every 10 ms. + .insert_resource(DiffRate(Duration::ZERO)) + .insert_resource(state) + .insert_resource(backend); + + // We open and manage the stream ourselves (see `device`). + app.add_plugins(SeedlingPlugins.build().disable::()); + app.add_systems( + PostStartup, + start_stream.in_set(SeedlingStartupSystems::StreamInitialization), + ); + + if backend == AudioBackend::Cpal { + app.add_systems( + Last, + device::manage_stream.after(SeedlingSystems::PollStream), + ); + } + } + + fn start_stream(world: &mut World) { + match *world.resource::() { + AudioBackend::Cpal => device::start_stream(world), + #[cfg(test)] + AudioBackend::Mock => crate::tests::start_mock_stream(world), + } + } + + fn with_world(f: impl FnOnce(&mut World) -> Result) -> Result { + app_mut(|app| f(app.world_mut())) + } + + /// For functions that need audio, which exists if the sketch enabled it. + fn with_audio(f: impl FnOnce(&mut World) -> Result) -> Result { + with_world(|world| { + if !world.contains_resource::() { + return Err(ProcessingError::AudioNotEnabled); + } + f(world) + }) + } + + /// Change device settings and restart the stream now; the graph is kept. + fn reconfigure(f: impl FnOnce(&mut AudioDeviceState)) -> Result<()> { + with_audio(|world| { + f(&mut world.resource_mut::()); + device::manage_restart_now(world); + Ok(()) + }) + } + + // --- devices --- + + /// Output devices, numbered in the order `audio_set_output_device_index` uses. + pub fn audio_list_output_devices() -> Result> { + Ok(device::list_devices(false)) + } + + /// Input devices, numbered in the order `audio_set_input_device_index` uses. + pub fn audio_list_input_devices() -> Result> { + Ok(device::list_devices(true)) + } + + /// Switch the output device. A named device must exist right now; if it + /// later disappears, the stream waits for it instead of switching away. + pub fn audio_set_output_device(device: AudioDevice) -> Result<()> { + device::check_device_exists(&device, false)?; + reconfigure(|s| s.want_output = device) + } + + pub fn audio_set_output_device_index(index: usize) -> Result<()> { + audio_set_output_device(device::device_by_index(index, false)?) + } + + /// Switch the input device, or pass `None` for no input. + pub fn audio_set_input_device(device: Option) -> Result<()> { + if let Some(device) = &device { + device::check_device_exists(device, true)?; + } + reconfigure(|s| s.want_input = device) + } + + pub fn audio_set_input_device_index(index: usize) -> Result<()> { + audio_set_input_device(Some(device::device_by_index(index, true)?)) + } + + /// Preferred sample rate, or `None` for the device's default. Changing it + /// resets reverb tails and stops playing samples. + pub fn audio_set_sample_rate(rate: Option) -> Result<()> { + reconfigure(|s| s.sample_rate = rate) + } + + /// Block size in frames. Smaller is lower latency but costs more CPU. + pub fn audio_set_block_frames(frames: u32) -> Result<()> { + reconfigure(|s| s.block_frames = frames.max(16)) + } + + /// Restart the stream with the current settings. + pub fn audio_restart() -> Result<()> { + reconfigure(|_| {}) + } + + pub fn audio_status() -> Result { + with_audio(|world| Ok(world.resource::().status())) + } + + pub fn audio_info() -> Result { + with_audio(|world| { + let rate = world.get_resource::().map(|r| r.get().get()); + Ok(world.resource::().info(rate)) + }) + } + + /// Everything that happened to the stream since the last call. + pub fn audio_events() -> Result> { + with_audio(|world| Ok(world.resource_mut::().drain_events())) + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests; diff --git a/crates/processing_audio/src/tests.rs b/crates/processing_audio/src/tests.rs new file mode 100644 index 00000000..bf7c06ae --- /dev/null +++ b/crates/processing_audio/src/tests.rs @@ -0,0 +1,200 @@ +//! Graph tests on a mock backend: no audio hardware needed. + +use std::num::NonZeroU32; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use audioadapter_buffers::direct::InterleavedSlice; +use bevy::prelude::*; +use bevy_seedling::context::SampleRate; +use bevy_seedling::firewheel::backend::BackendProcessInfo; +use bevy_seedling::firewheel::node::StreamStatus; +use bevy_seedling::firewheel::{ActivateInfo, FirewheelContext}; +use bevy_seedling::prelude::*; + +use processing_core::config::{Config, ConfigKey}; + +use crate::device::{self, AudioDeviceState, AudioStatus}; +use crate::native::{self, AudioBackend}; + +const MOCK_RATE: NonZeroU32 = NonZeroU32::new(48_000).unwrap(); +const MOCK_CHANNELS: usize = 2; + +/// Tells the running mock processor thread to drop its processor and exit. +#[derive(Resource)] +struct MockStream(Arc); + +/// The mock backend's stream: run the graph on a thread that pulls blocks in +/// real time, like seedling's `MockBackendPlugin`, at the configured block +/// size. Opened at startup; tests restart it with `stop_mock_stream` and this, +/// which drop the processor and activate the context again like a device +/// restart does. +pub(crate) fn start_mock_stream(world: &mut World) { + let block_frames = world.resource::().block_frames as usize; + let stop = world + .resource_mut::() + .with(|cx| (!cx.is_active()).then(|| spawn_mock_processor(cx, block_frames))); + if let Some(stop) = stop { + world.insert_resource(MockStream(stop)); + } + if !world.contains_resource::() { + world.insert_resource(SampleRate::new(MOCK_RATE)); + world.trigger(bevy_seedling::context::StreamStartEvent { + sample_rate: MOCK_RATE, + }); + } +} + +pub(crate) fn stop_mock_stream(world: &mut World) { + if let Some(MockStream(stop)) = world.remove_resource::() { + stop.store(true, Ordering::Relaxed); + world + .resource_mut::() + .with(device::wait_until_inactive); + } +} + +fn spawn_mock_processor(cx: &mut FirewheelContext, block_frames: usize) -> Arc { + let mut processor = cx + .activate(ActivateInfo { + sample_rate: MOCK_RATE, + max_block_frames: NonZeroU32::new(block_frames as u32).unwrap(), + num_stream_in_channels: MOCK_CHANNELS as u32, + num_stream_out_channels: MOCK_CHANNELS as u32, + input_to_output_latency_seconds: 0.0, + }) + .unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let stopped = stop.clone(); + std::thread::spawn(move || { + let block = Duration::from_secs_f64(block_frames as f64 / MOCK_RATE.get() as f64); + let input = vec![0f32; block_frames * MOCK_CHANNELS]; + let mut output = vec![0f32; block_frames * MOCK_CHANNELS]; + let began = Instant::now(); + // Checked before every block, so a stop right after a start drops + // the processor before it has run, as a failing device can. + while !stopped.load(Ordering::Relaxed) { + let now = Instant::now(); + let input = InterleavedSlice::new(&input, MOCK_CHANNELS, block_frames).unwrap(); + let mut output = + InterleavedSlice::new_mut(&mut output, MOCK_CHANNELS, block_frames).unwrap(); + processor.process( + &input, + &mut output, + BackendProcessInfo { + frames: block_frames, + process_timestamp: Some(now), + duration_since_stream_start: now - began, + input_stream_status: StreamStatus::empty(), + output_stream_status: StreamStatus::empty(), + dropped_frames: 0, + process_to_playback_delay: None, + }, + ); + std::thread::sleep(block); + } + }); + stop +} + +fn base_app(config: Config) -> App { + let mut app = App::new(); + app.insert_resource(config).add_plugins(( + MinimalPlugins, + AssetPlugin { + // the repo's assets folder, for the sample test + file_path: concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets").into(), + ..default() + }, + bevy::transform::TransformPlugin, + )); + app +} + +/// An app with audio as `init()` leaves it: started, on the mock backend. +fn test_app(graph_channels: u32) -> App { + let mut config = Config::new(); + config.set(ConfigKey::AudioGraphChannels, graph_channels.to_string()); + let mut app = base_app(config); + native::build(&mut app, AudioBackend::Mock); + app.finish(); + app.cleanup(); + app.update(); + app.update(); + app +} + +/// Restart the mock stream, as a device or setting change does. +fn restart(world: &mut World) { + stop_mock_stream(world); + start_mock_stream(world); +} + +#[test] +fn audio_is_off_unless_enabled() { + let mut app = base_app(Config::new()); + app.add_plugins(crate::AudioPlugin); + app.finish(); + app.cleanup(); + app.update(); + let world = app.world_mut(); + assert!(!world.contains_resource::()); + assert!(!world.contains_resource::()); +} + +#[test] +fn startup_opens_the_stream() { + let mut app = test_app(8); + let world = app.world_mut(); + assert!(world.contains_resource::()); + assert_eq!( + world.resource::().status(), + AudioStatus::Running + ); + assert!( + world + .resource_mut::() + .with(|cx| cx.is_active()) + ); + // no microphone unless asked for + assert_eq!(world.resource::().want_input, None); +} + +fn heartbeat(app: &mut App) -> i64 { + app.world_mut() + .resource_mut::() + .with(|cx| cx.heartbeat()) +} + +/// Wait for the audio thread to process a block. A processor that panicked +/// (such as on a block-size assertion) never does. +fn assert_processing(app: &mut App, context: &str) { + let start = heartbeat(app); + let began = Instant::now(); + while heartbeat(app) == start { + assert!( + began.elapsed() < Duration::from_secs(2), + "audio thread stopped processing {context}" + ); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn restart_with_new_block_sizes_keeps_running() { + let mut app = test_app(2); + app.update(); + assert_processing(&mut app, "before any restart"); + + for frames in [64, 512, 128, 1024, 256] { + // Restart without an update in between, as a device change does. + let world = app.world_mut(); + world.resource_mut::().block_frames = frames; + restart(world); + // And once more right away, likely before the processor has run. + restart(world); + assert_processing(&mut app, &format!("after restarting at {frames} frames")); + app.update(); + } +} diff --git a/crates/processing_core/src/config.rs b/crates/processing_core/src/config.rs index 208a44d4..2462b867 100644 --- a/crates/processing_core/src/config.rs +++ b/crates/processing_core/src/config.rs @@ -5,6 +5,20 @@ use std::collections::HashMap; pub enum ConfigKey { AssetRootPath, LogLevel, + /// Set to "true" to enable audio. Without it, no audio device is + /// opened and the audio functions return `AudioNotEnabled`. + AudioEnabled, + /// Audio output device: part of its name, or "default". + AudioOutputDevice, + /// Audio input device: part of its name, "default", or "none" (the + /// default, so no microphone is opened unless asked for). + AudioInputDevice, + /// Preferred audio sample rate in Hz. + AudioSampleRate, + /// Preferred audio block size in frames. + AudioBlockFrames, + /// Minimum number of audio graph input and output channels. + AudioGraphChannels, } // TODO: Consider Box instead of String diff --git a/crates/processing_core/src/error.rs b/crates/processing_core/src/error.rs index 95567476..3f1ca4a7 100644 --- a/crates/processing_core/src/error.rs +++ b/crates/processing_core/src/error.rs @@ -80,4 +80,10 @@ pub enum ProcessingError { FontNotFound, #[error("Font load error: {0}")] FontLoadError(String), + #[error("No audio device matching {0:?}; available devices: {1}")] + AudioDeviceNotFound(String, String), + #[error("Audio device {0} not found")] + AudioDeviceIndexNotFound(usize), + #[error("Audio isn't enabled; set ConfigKey::AudioEnabled to \"true\" before init()")] + AudioNotEnabled, } diff --git a/src/lib.rs b/src/lib.rs index 717a24ca..a89855a6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,6 +51,7 @@ fn create_app(config: Config) -> App { app.add_plugins(plugins); app.add_plugins(processing_midi::MidiPlugin); + app.add_plugins(processing_audio::AudioPlugin); app.add_plugins(processing_input::InputPlugin); app.add_plugins(processing_render::ProcessingRenderPlugin); diff --git a/src/prelude.rs b/src/prelude.rs index 22b4b160..edfa89e7 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -2,6 +2,13 @@ pub use bevy::input::keyboard::KeyCode; pub use bevy::input::mouse::MouseButton; pub use bevy::prelude::default; pub use bevy::render::render_resource::TextureFormat; +#[cfg(not(target_arch = "wasm32"))] +pub use processing_audio::{ + AudioDevice, AudioEvent, AudioInfo, AudioStatus, audio_events, audio_info, + audio_list_input_devices, audio_list_output_devices, audio_restart, audio_set_block_frames, + audio_set_input_device, audio_set_input_device_index, audio_set_output_device, + audio_set_output_device_index, audio_set_sample_rate, audio_status, parse_device, +}; pub use processing_core::{config::*, constants, error}; pub use processing_input::*; #[cfg(not(target_arch = "wasm32"))]