diff --git a/Cargo.lock b/Cargo.lock index 0929605a..06fef501 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3159,6 +3159,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fft-convolver" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dc2475d152b174858819508db05e86ae8df4542aeb1b2b21ef5a0dda3e64bf6" +dependencies = [ + "realfft", + "rtsan-standalone", + "thiserror 2.0.20", +] + [[package]] name = "file-id" version = "0.2.3" @@ -3283,6 +3294,7 @@ dependencies = [ "bevy_ecs", "bevy_platform", "bevy_reflect", + "fft-convolver", "firewheel-core", "num-traits", "smallvec", @@ -5377,6 +5389,16 @@ dependencies = [ "libm", ] +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + [[package]] name = "num_enum" version = "0.7.6" @@ -6238,8 +6260,10 @@ dependencies = [ name = "processing_audio" version = "0.4.0" dependencies = [ + "audioadapter-buffers", "bevy", "bevy_seedling", + "processing_core", ] [[package]] @@ -6898,6 +6922,36 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "rtsan-standalone" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fd1b6d61d69481a68e555916d3a52213846f5c2d2140bdc74ebc308e2338fc3" +dependencies = [ + "rtsan-standalone-macros", + "rtsan-standalone-sys", +] + +[[package]] +name = "rtsan-standalone-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8320af894782374141c8e0d4521ee613a8f24d7ab08b6ad359881311e37b9ef" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "rtsan-standalone-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "362a9c531f731e574a870cdb28ee7d81178ba7a87ed54380eb9b8d8f0c3b5301" +dependencies = [ + "num_cpus", + "tempfile", +] + [[package]] name = "rubato" version = "0.14.1" diff --git a/crates/processing_audio/Cargo.toml b/crates/processing_audio/Cargo.toml index 94a614d5..48ad5a4a 100644 --- a/crates/processing_audio/Cargo.toml +++ b/crates/processing_audio/Cargo.toml @@ -6,7 +6,14 @@ rust-version.workspace = true [dependencies] bevy = { workspace = true } -bevy_seedling = { git = "https://github.com/catilac/bevy_seedling", branch = "processing-dev" } +processing_core = { workspace = true } +bevy_seedling = { git = "https://github.com/catilac/bevy_seedling", branch = "processing-dev", features = [ + "effects", +] } + +[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/graph.rs b/crates/processing_audio/src/graph.rs new file mode 100644 index 00000000..de2bf53f --- /dev/null +++ b/crates/processing_audio/src/graph.rs @@ -0,0 +1,528 @@ +//! A generic audio node graph: create nodes, wire individual ports, set +//! parameters by name. +//! +//! Every connection names its ports explicitly. Seedling's automatic +//! speaker up/down-mixing is never used, so a signal on channel 5 stays on +//! channel 5. That matters for DC-coupled CV as much as for audio. + +use bevy::prelude::*; +use bevy::reflect::enums::{DynamicEnum, DynamicVariant}; +use bevy::reflect::{GetPath, PartialReflect, TypeInfo}; +use bevy_seedling::firewheel::dsp::mix::Mix; +use bevy_seedling::prelude::*; + +use processing_core::error::{ProcessingError, Result}; + +use crate::device::AudioDeviceState; + +/// The node types the graph can create. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum AudioNodeKind { + /// Gain on `channels` channels (`volume`). A VCA per channel. + Volume, + /// Stereo gain and pan (`volume`, `pan`). Always 2 in / 2 out. + VolumePan, + /// Crossfades two `channels`-wide signals: inputs `0..channels` are the + /// first signal, `channels..2*channels` the second (`mix`, `volume`). + Mix, + /// State-variable filter (`cutoff_hz`, `q_factor`, `gain`, + /// `filter_type`), 1 to 8 channels. + Svf, + /// One-pole lowpass (`cutoff_hz`), 1 to 8 channels. + Lowpass, + /// One-pole highpass (`cutoff_hz`), 1 to 8 channels. + Highpass, + /// One-pole bandpass (`cutoff_hz`), 1 to 8 channels. + Bandpass, + /// Stereo reverb (`room_size`, `damping`, `width`). Always 2 in / 2 out. + Freeverb, + /// White noise source (`volume`). 0 in / 1 out. + WhiteNoise, + /// Pink noise source (`volume`). 0 in / 1 out. + PinkNoise, +} + +/// Channel counts the filters support. +pub const MAX_FILTER_CHANNELS: u32 = 8; + +/// The port counts of an audio handle, known as soon as it is created (the +/// seedling node is only acquired on the next update). +#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)] +pub struct AudioPorts { + pub inputs: u32, + pub outputs: u32, +} + +/// Which concrete node an entity holds, so parameters can be found. +#[derive(Component, Clone, Copy, Debug)] +pub(crate) struct AudioNodeType { + kind: AudioNodeKind, + channels: u32, +} + +impl AudioNodeKind { + /// Port counts for this kind at the given width. + pub fn ports(self, channels: u32) -> AudioPorts { + let (inputs, outputs) = match self { + AudioNodeKind::Volume + | AudioNodeKind::Svf + | AudioNodeKind::Lowpass + | AudioNodeKind::Highpass + | AudioNodeKind::Bandpass => (channels, channels), + AudioNodeKind::Mix => (channels * 2, channels), + AudioNodeKind::VolumePan | AudioNodeKind::Freeverb => (2, 2), + AudioNodeKind::WhiteNoise | AudioNodeKind::PinkNoise => (0, 1), + }; + AudioPorts { inputs, outputs } + } + + fn check_channels(self, channels: u32) -> Result { + let max = match self { + AudioNodeKind::Svf + | AudioNodeKind::Lowpass + | AudioNodeKind::Highpass + | AudioNodeKind::Bandpass => MAX_FILTER_CHANNELS, + AudioNodeKind::Volume | AudioNodeKind::Mix => 32, + // fixed width; `channels` is ignored + _ => return Ok(1), + }; + if (1..=max).contains(&channels) { + Ok(channels) + } else { + Err(ProcessingError::InvalidArgument(format!( + "{self:?} supports 1 to {max} channels, got {channels}" + ))) + } + } +} + +/// Filters are generic over their channel count; match a runtime count to +/// the const generic. +macro_rules! for_channels { + ($channels:expr, |$n:ident| $body:expr) => { + match $channels { + 1 => { + const $n: usize = 1; + $body + } + 2 => { + const $n: usize = 2; + $body + } + 3 => { + const $n: usize = 3; + $body + } + 4 => { + const $n: usize = 4; + $body + } + 5 => { + const $n: usize = 5; + $body + } + 6 => { + const $n: usize = 6; + $body + } + 7 => { + const $n: usize = 7; + $body + } + 8 => { + const $n: usize = 8; + $body + } + _ => unreachable!("channel count checked on creation"), + } + }; +} + +/// Register the filter widths seedling doesn't (it registers stereo only). +pub(crate) fn register_nodes(app: &mut App) { + fn widths(app: &mut App) { + app.register_node::>() + .register_node::>() + .register_node::>() + .register_node::>(); + } + widths::<1>(app); + widths::<3>(app); + widths::<4>(app); + widths::<5>(app); + widths::<6>(app); + widths::<7>(app); + widths::<8>(app); +} + +fn nonzero(channels: u32) -> NonZeroChannelCount { + NonZeroChannelCount::new(channels).expect("channel count checked on creation") +} + +pub(crate) fn node_create( + In((kind, channels)): In<(AudioNodeKind, u32)>, + world: &mut World, +) -> Result { + let channels = kind.check_channels(channels)?; + let common = ( + ChannelMapping::Discrete, + // Only edges the sketch makes exist; nothing is routed to `MainBus`. + NoAutoConnect, + kind.ports(channels), + AudioNodeType { kind, channels }, + ); + let mut entity = world.spawn(common); + let ch = nonzero(channels); + match kind { + AudioNodeKind::Volume => { + entity.insert((VolumeNode::default(), VolumeNodeConfig { channels: ch })); + } + AudioNodeKind::VolumePan => { + entity.insert(VolumePanNode::default()); + } + AudioNodeKind::Mix => { + entity.insert((MixNode::default(), MixNodeConfig { channels: ch })); + } + AudioNodeKind::Svf => for_channels!(channels, |N| { + entity.insert(SvfNode::::default()); + }), + AudioNodeKind::Lowpass => for_channels!(channels, |N| { + entity.insert(FastLowpassNode::::default()); + }), + AudioNodeKind::Highpass => for_channels!(channels, |N| { + entity.insert(FastHighpassNode::::default()); + }), + AudioNodeKind::Bandpass => for_channels!(channels, |N| { + entity.insert(FastBandpassNode::::default()); + }), + AudioNodeKind::Freeverb => { + entity.insert(FreeverbNode::default()); + } + AudioNodeKind::WhiteNoise => { + entity.insert(WhiteNoiseGenNode::default()); + } + AudioNodeKind::PinkNoise => { + entity.insert(PinkNoiseGenNode::default()); + } + } + Ok(entity.id()) +} + +pub(crate) fn node_destroy(In(node): In, world: &mut World) -> Result<()> { + if world.get::(node).is_none() { + return Err(ProcessingError::AudioNodeNotFound); + } + world.despawn(node); + Ok(()) +} + +/// Run `f` on the node's parameter struct, marking it changed so seedling +/// sends the new values to the audio thread. +fn with_params( + world: &mut World, + node: Entity, + f: impl FnOnce(&mut dyn Reflect) -> Result, +) -> Result { + let ty = *world + .get::(node) + .ok_or(ProcessingError::AudioNodeNotFound)?; + + fn get<'w, C: Component + Reflect>( + world: &'w mut World, + node: Entity, + ) -> Result> { + world + .get_mut::(node) + .ok_or(ProcessingError::AudioNodeNotFound) + } + + match ty.kind { + AudioNodeKind::Volume => f(get::(world, node)?.as_mut()), + AudioNodeKind::VolumePan => f(get::(world, node)?.as_mut()), + AudioNodeKind::Mix => f(get::(world, node)?.as_mut()), + AudioNodeKind::Freeverb => f(get::(world, node)?.as_mut()), + AudioNodeKind::WhiteNoise => f(get::(world, node)?.as_mut()), + AudioNodeKind::PinkNoise => f(get::(world, node)?.as_mut()), + AudioNodeKind::Svf => { + for_channels!(ty.channels, |N| f(get::>(world, node)?.as_mut())) + } + AudioNodeKind::Lowpass => for_channels!(ty.channels, |N| f(get::>( + world, node + )? + .as_mut())), + AudioNodeKind::Highpass => for_channels!(ty.channels, |N| f(get::>( + world, node + )? + .as_mut())), + AudioNodeKind::Bandpass => for_channels!(ty.channels, |N| f(get::>( + world, node + )? + .as_mut())), + } +} + +fn field<'a>(params: &'a mut dyn Reflect, param: &str) -> Result<&'a mut dyn PartialReflect> { + params + .reflect_path_mut(param) + .map_err(|_| ProcessingError::AudioParamNotFound(param.to_string())) +} + +/// Set a number on a field: `f32`/`f64` directly, `Volume` as linear gain, +/// `Mix` as 0 (first) to 1 (second), `bool` as non-zero. +pub(crate) fn set_number(field: &mut dyn PartialReflect, value: f32) -> bool { + if let Some(f) = field.try_downcast_mut::() { + *f = value; + } else if let Some(f) = field.try_downcast_mut::() { + *f = value as f64; + } else if let Some(v) = field.try_downcast_mut::() { + *v = Volume::Linear(value); + } else if let Some(m) = field.try_downcast_mut::() { + *m = Mix::new(value.clamp(0.0, 1.0)); + } else if let Some(b) = field.try_downcast_mut::() { + *b = value != 0.0; + } else { + return false; + } + true +} + +pub(crate) fn node_set( + In((node, param, value)): In<(Entity, String, f32)>, + world: &mut World, +) -> Result<()> { + with_params(world, node, |params| { + if set_number(field(params, ¶m)?, value) { + Ok(()) + } else { + Err(ProcessingError::InvalidArgument(format!( + "{param:?} is not a number; try audio_node_set_variant" + ))) + } + }) +} + +/// Set an enum field to one of its unit variants by name, e.g. +/// `filter_type` = `"Highpass"` (case-insensitive). +pub(crate) fn set_variant( + field: &mut dyn PartialReflect, + variant: &str, +) -> std::result::Result<(), String> { + let Some(TypeInfo::Enum(info)) = field.get_represented_type_info() else { + return Err("is not an enum".into()); + }; + let Some(name) = info + .variant_names() + .iter() + .find(|n| n.eq_ignore_ascii_case(variant)) + else { + return Err(format!( + "has no variant {variant:?}; expected one of {}", + info.variant_names().join(", ") + )); + }; + field + .try_apply(&DynamicEnum::new(*name, DynamicVariant::Unit)) + .map_err(|e| e.to_string()) +} + +pub(crate) fn node_set_variant( + In((node, param, variant)): In<(Entity, String, String)>, + world: &mut World, +) -> Result<()> { + with_params(world, node, |params| { + set_variant(field(params, ¶m)?, &variant) + .map_err(|e| ProcessingError::InvalidArgument(format!("{param:?} {e}"))) + }) +} + +pub(crate) fn node_get(In((node, param)): In<(Entity, String)>, world: &mut World) -> Result { + // Reading through `with_params` marks the node changed; that only costs + // one redundant diff, so keep a single code path. + with_params(world, node, |params| { + let field = field(params, ¶m)?; + if let Some(f) = field.try_downcast_ref::() { + Ok(*f) + } else if let Some(f) = field.try_downcast_ref::() { + Ok(*f as f32) + } else if let Some(v) = field.try_downcast_ref::() { + Ok(v.linear()) + } else if let Some(m) = field.try_downcast_ref::() { + Ok(m.get()) + } else if let Some(b) = field.try_downcast_ref::() { + Ok(if *b { 1.0 } else { 0.0 }) + } else { + Err(ProcessingError::InvalidArgument(format!( + "{param:?} is not a number" + ))) + } + }) +} + +// --- graph I/O and edges --- + +/// Give the graph input and output entities their port counts. Runs once +/// the I/O entities exist. +pub(crate) fn tag_graph_io( + mut commands: Commands, + state: Res, + input: Query, Without)>, + output: Query, Without)>, +) { + for e in &input { + commands.entity(e).insert(AudioPorts { + inputs: 0, + outputs: state.graph_inputs, + }); + } + for e in &output { + commands.entity(e).insert(AudioPorts { + inputs: state.graph_outputs, + outputs: 0, + }); + } +} + +pub(crate) fn graph_input(world: &mut World) -> Result { + world + .query_filtered::>() + .single(world) + .map_err(|_| ProcessingError::AudioNodeNotFound) +} + +pub(crate) fn graph_output(world: &mut World) -> Result { + world + .query_filtered::>() + .single(world) + .map_err(|_| ProcessingError::AudioNodeNotFound) +} + +pub(crate) fn ports_of(world: &World, node: Entity) -> Result { + world + .get::(node) + .copied() + .ok_or(ProcessingError::AudioNodeNotFound) +} + +/// Check every `(src_port, dst_port)` pair against the nodes' port counts. +pub(crate) fn check_ports(src: AudioPorts, dst: AudioPorts, ports: &[(u32, u32)]) -> Result<()> { + if ports.is_empty() { + return Err(ProcessingError::InvalidArgument( + "no ports given; pass (src_port, dst_port) pairs".into(), + )); + } + for &(out, inp) in ports { + if out >= src.outputs { + return Err(ProcessingError::AudioPortOutOfRange { + side: "source outputs", + port: out, + count: src.outputs, + }); + } + if inp >= dst.inputs { + return Err(ProcessingError::AudioPortOutOfRange { + side: "destination inputs", + port: inp, + count: dst.inputs, + }); + } + } + Ok(()) +} + +pub(crate) fn connect( + In((src, dst, ports)): In<(Entity, Entity, Vec<(u32, u32)>)>, + world: &mut World, +) -> Result<()> { + check_ports(ports_of(world, src)?, ports_of(world, dst)?, &ports)?; + world.commands().entity(src).connect_with(dst, &ports); + world.flush(); + Ok(()) +} + +pub(crate) fn disconnect( + In((src, dst, ports)): In<(Entity, Entity, Vec<(u32, u32)>)>, + world: &mut World, +) -> Result<()> { + check_ports(ports_of(world, src)?, ports_of(world, dst)?, &ports)?; + world.commands().entity(src).disconnect_with(dst, &ports); + world.flush(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn port_counts_per_kind() { + assert_eq!( + AudioNodeKind::Svf.ports(3), + AudioPorts { + inputs: 3, + outputs: 3 + } + ); + assert_eq!( + AudioNodeKind::Mix.ports(2), + AudioPorts { + inputs: 4, + outputs: 2 + } + ); + assert_eq!( + AudioNodeKind::WhiteNoise.ports(5), + AudioPorts { + inputs: 0, + outputs: 1 + } + ); + assert!(AudioNodeKind::Svf.check_channels(9).is_err()); + assert!(AudioNodeKind::Lowpass.check_channels(0).is_err()); + } + + #[test] + fn rejects_out_of_range_ports() { + let eight = AudioPorts { + inputs: 8, + outputs: 8, + }; + let mono = AudioPorts { + inputs: 1, + outputs: 1, + }; + assert!(check_ports(eight, mono, &[(7, 0)]).is_ok()); + assert!(matches!( + check_ports(eight, mono, &[(8, 0)]), + Err(ProcessingError::AudioPortOutOfRange { port: 8, .. }) + )); + assert!(matches!( + check_ports(eight, mono, &[(0, 1)]), + Err(ProcessingError::AudioPortOutOfRange { port: 1, .. }) + )); + assert!(check_ports(eight, mono, &[]).is_err()); + } + + #[test] + fn sets_numbers_and_variants_by_reflection() { + let mut svf = SvfNode::<1>::default(); + let params: &mut dyn Reflect = &mut svf; + assert!(set_number( + params.reflect_path_mut("cutoff_hz").unwrap(), + 440.0 + )); + assert!(set_number(params.reflect_path_mut("gain").unwrap(), 0.5)); + set_variant(params.reflect_path_mut("filter_type").unwrap(), "highpass").unwrap(); + assert!(set_variant(params.reflect_path_mut("filter_type").unwrap(), "nope").is_err()); + assert_eq!(svf.cutoff_hz, 440.0); + assert_eq!(svf.gain, Volume::Linear(0.5)); + assert_eq!( + svf.filter_type, + bevy_seedling::firewheel::nodes::svf::SvfType::Highpass + ); + + let mut mix = MixNode::default(); + let params: &mut dyn Reflect = &mut mix; + assert!(set_number(params.reflect_path_mut("mix").unwrap(), 0.25)); + assert_eq!(mix.mix.get(), 0.25); + } +} diff --git a/crates/processing_audio/src/lib.rs b/crates/processing_audio/src/lib.rs index b9620636..3642889c 100644 --- a/crates/processing_audio/src/lib.rs +++ b/crates/processing_audio/src/lib.rs @@ -1,10 +1,319 @@ +//! 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`]. +//! - **Graph I/O.** [`audio_input`] and [`audio_output`] have one port per +//! device channel (at least 8), so every jack on an interface is +//! addressable on its own. +//! - **Nodes.** [`audio_node_create`] makes filters, gains, mixers, reverb and +//! noise; [`audio_node_set`] sets any numeric parameter by name. +//! - **Edges.** [`audio_connect`] always takes explicit +//! `(source_port, destination_port)` pairs. There is no implicit +//! up/down-mixing, limiter, DC blocking or input gate anywhere, so +//! DC-coupled CV passes through untouched. +//! +//! Graph changes are applied on the next frame update; device changes apply +//! immediately. + use bevy::prelude::*; -use bevy_seedling::prelude::*; +#[cfg(not(target_arch = "wasm32"))] +mod device; +#[cfg(not(target_arch = "wasm32"))] +mod graph; + +#[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}; + pub use crate::graph::{AudioNodeKind, AudioPorts}; + + use crate::device::{self, AudioDeviceState}; + use crate::graph; + + /// 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::()); + graph::register_nodes(app); + app.add_systems( + PostStartup, + ( + start_stream.in_set(SeedlingStartupSystems::StreamInitialization), + graph::tag_graph_io.after(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())) + } + + // --- graph --- + + /// The graph's input: one output port per input channel. + pub fn audio_input() -> Result { + with_audio(graph::graph_input) + } + + /// The graph's output: one input port per output channel. + pub fn audio_output() -> Result { + with_audio(graph::graph_output) + } + + /// Create a node. `channels` sets the width of `Volume`, `Mix` and the + /// filters, and is ignored by fixed-width nodes. + pub fn audio_node_create(kind: AudioNodeKind, channels: u32) -> Result { + with_audio(|world| graph::node_create(In((kind, channels)), world)) + } + + /// Remove a node and all its connections. + pub fn audio_node_destroy(node: Entity) -> Result<()> { + with_audio(|world| graph::node_destroy(In(node), world)) + } + + /// A node's port counts. + pub fn audio_node_ports(node: Entity) -> Result { + with_audio(|world| { + world + .get::(node) + .copied() + .ok_or(processing_core::error::ProcessingError::AudioNodeNotFound) + }) + } + + /// Set a numeric parameter by field name, e.g. `"cutoff_hz"`. Gains + /// (`"volume"`, `"gain"`) are linear: 0 is silence, 1 is unity. + pub fn audio_node_set(node: Entity, param: &str, value: f32) -> Result<()> { + with_audio(|world| graph::node_set(In((node, param.to_string(), value)), world)) + } + + /// Set an enum parameter by variant name, e.g. `"filter_type"`, `"Highpass"`. + pub fn audio_node_set_variant(node: Entity, param: &str, variant: &str) -> Result<()> { + with_audio(|world| { + graph::node_set_variant(In((node, param.to_string(), variant.to_string())), world) + }) + } + + /// Read a numeric parameter. + pub fn audio_node_get(node: Entity, param: &str) -> Result { + with_audio(|world| graph::node_get(In((node, param.to_string())), world)) + } + + /// Connect `src` output ports to `dst` input ports, one + /// `(src_port, dst_port)` pair per wire. + pub fn audio_connect(src: Entity, dst: Entity, ports: &[(u32, u32)]) -> Result<()> { + with_audio(|world| graph::connect(In((src, dst, ports.to_vec())), world)) + } + + /// Connect a single wire. + pub fn audio_connect_channel( + src: Entity, + src_port: u32, + dst: Entity, + dst_port: u32, + ) -> Result<()> { + audio_connect(src, dst, &[(src_port, dst_port)]) + } + + /// Remove the given wires. + pub fn audio_disconnect(src: Entity, dst: Entity, ports: &[(u32, u32)]) -> Result<()> { + with_audio(|world| graph::disconnect(In((src, dst, ports.to_vec())), world)) } } + +#[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..7bce6f83 --- /dev/null +++ b/crates/processing_audio/src/tests.rs @@ -0,0 +1,330 @@ +//! 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::{NodeID, 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::graph::{self, AudioNodeKind, AudioPorts}; +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); +} + +fn node_id(app: &App, e: Entity) -> NodeID { + app.world() + .get::(e) + .expect("node acquired") + .0 +} + +/// Every edge in the Firewheel graph as (src, src_port, dst, dst_port). +fn edges(app: &mut App) -> Vec<(NodeID, u32, NodeID, u32)> { + let mut edges = app.world_mut().resource_mut::().with(|cx| { + cx.edges() + .map(|e| (e.src_node, e.src_port, e.dst_node, e.dst_port)) + .collect::>() + }); + edges.sort_by_key(|&(_, sp, _, dp)| (sp, dp)); + edges +} + +#[test] +fn graph_width_follows_config() { + let mut app = test_app(8); + let world = app.world_mut(); + let input = graph::graph_input(world).unwrap(); + let output = graph::graph_output(world).unwrap(); + assert_eq!(world.get::(input).unwrap().outputs, 8); + assert_eq!(world.get::(output).unwrap().inputs, 8); + + let (ins, outs) = world.resource_mut::().with(|cx| { + let i = cx.node_info(cx.graph_in_node_id()).unwrap(); + let o = cx.node_info(cx.graph_out_node_id()).unwrap(); + ( + i.info.channel_config.num_outputs.get(), + o.info.channel_config.num_inputs.get(), + ) + }); + assert_eq!((ins, outs), (8, 8)); +} + +#[test] +fn connect_makes_exactly_the_given_edges() { + let mut app = test_app(8); + let world = app.world_mut(); + let input = graph::graph_input(world).unwrap(); + let output = graph::graph_output(world).unwrap(); + let filter = graph::node_create(In((AudioNodeKind::Lowpass, 1)), world).unwrap(); + + // in 5 -> filter -> out 7, and in 4 -> out 4 untouched (CV passthrough) + graph::connect(In((input, filter, vec![(5, 0)])), world).unwrap(); + graph::connect(In((filter, output, vec![(0, 7)])), world).unwrap(); + graph::connect(In((input, output, vec![(4, 4)])), world).unwrap(); + app.update(); + + let (i, f, o) = ( + node_id(&app, input), + node_id(&app, filter), + node_id(&app, output), + ); + assert_eq!( + edges(&mut app), + vec![(f, 0, o, 7), (i, 4, o, 4), (i, 5, f, 0)] + ); + + let world = app.world_mut(); + graph::disconnect(In((input, output, vec![(4, 4)])), world).unwrap(); + app.update(); + assert_eq!(edges(&mut app), vec![(f, 0, o, 7), (i, 5, f, 0)]); +} + +#[test] +fn out_of_range_ports_are_errors() { + let mut app = test_app(8); + let world = app.world_mut(); + let input = graph::graph_input(world).unwrap(); + let filter = graph::node_create(In((AudioNodeKind::Svf, 2)), world).unwrap(); + assert!(graph::connect(In((input, filter, vec![(8, 0)])), world).is_err()); + assert!(graph::connect(In((input, filter, vec![(0, 2)])), world).is_err()); + assert!(graph::connect(In((input, filter, vec![(7, 1)])), world).is_ok()); +} + +#[test] +fn set_param_by_name() { + let mut app = test_app(2); + let world = app.world_mut(); + let svf = graph::node_create(In((AudioNodeKind::Svf, 3)), world).unwrap(); + graph::node_set(In((svf, "cutoff_hz".into(), 1234.0)), world).unwrap(); + graph::node_set_variant(In((svf, "filter_type".into(), "Bandpass".into())), world).unwrap(); + assert_eq!( + graph::node_get(In((svf, "cutoff_hz".into())), world).unwrap(), + 1234.0 + ); + let node = world.get::>(svf).unwrap(); + assert_eq!( + node.filter_type, + bevy_seedling::firewheel::nodes::svf::SvfType::Bandpass + ); + assert!(graph::node_set(In((svf, "nope".into(), 1.0)), world).is_err()); + + let vol = graph::node_create(In((AudioNodeKind::Volume, 8)), world).unwrap(); + graph::node_set(In((vol, "volume".into(), 0.5)), world).unwrap(); + assert_eq!( + world.get::(vol).unwrap().volume, + Volume::Linear(0.5) + ); +} + +#[test] +fn unwired_nodes_are_not_auto_connected() { + let mut app = test_app(2); + let world = app.world_mut(); + // a MainBus for seedling's auto-connect to target, if it kicked in + let output = graph::graph_output(world).unwrap(); + let bus = world + .spawn((MainBus, VolumeNode::default(), ChannelMapping::Discrete)) + .id(); + world.commands().entity(bus).connect(output); + world.flush(); + let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap(); + for _ in 0..3 { + app.update(); + } + + let n = node_id(&app, noise); + let leaks: Vec<_> = edges(&mut app).into_iter().filter(|e| e.0 == n).collect(); + assert!(leaks.is_empty(), "unwired nodes got edges: {leaks:?}"); +} + +#[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::()); + assert!(graph::graph_output(world).is_err()); +} + +#[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()) + ); + let output = graph::graph_output(world).unwrap(); + assert_eq!(world.get::(output).unwrap().inputs, 8); + // 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..e626cc6f 100644 --- a/crates/processing_core/src/error.rs +++ b/crates/processing_core/src/error.rs @@ -80,4 +80,20 @@ 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, + #[error("Audio node not found")] + AudioNodeNotFound, + #[error("Audio port {port} out of range on {side}; the node has {count}")] + AudioPortOutOfRange { + side: &'static str, + port: u32, + count: u32, + }, + #[error("Audio node has no parameter {0:?}")] + AudioParamNotFound(String), } diff --git a/src/lib.rs b/src/lib.rs index 82c9b73d..48e65099 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,6 +54,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..8540f7b0 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -2,6 +2,16 @@ 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, AudioNodeKind, AudioPorts, AudioStatus, audio_connect, + audio_connect_channel, audio_disconnect, audio_events, audio_info, audio_input, + audio_list_input_devices, audio_list_output_devices, audio_node_create, audio_node_destroy, + audio_node_get, audio_node_ports, audio_node_set, audio_node_set_variant, audio_output, + 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"))]