diff --git a/Cargo.lock b/Cargo.lock index 3245a7a6..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" @@ -6900,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 9b33b617..48ad5a4a 100644 --- a/crates/processing_audio/Cargo.toml +++ b/crates/processing_audio/Cargo.toml @@ -7,7 +7,9 @@ rust-version.workspace = true [dependencies] bevy = { workspace = true } processing_core = { workspace = true } -bevy_seedling = { git = "https://github.com/catilac/bevy_seedling", branch = "processing-dev" } +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. 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 0d43edb5..3642889c 100644 --- a/crates/processing_audio/src/lib.rs +++ b/crates/processing_audio/src/lib.rs @@ -15,11 +15,25 @@ //! `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::*; #[cfg(not(target_arch = "wasm32"))] mod device; +#[cfg(not(target_arch = "wasm32"))] +mod graph; #[cfg(not(target_arch = "wasm32"))] pub use native::*; @@ -66,8 +80,10 @@ mod native { 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)] @@ -111,9 +127,13 @@ mod native { // 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), + ( + start_stream.in_set(SeedlingStartupSystems::StreamInitialization), + graph::tag_graph_io.after(SeedlingStartupSystems::StreamInitialization), + ), ); if backend == AudioBackend::Cpal { @@ -221,6 +241,78 @@ mod native { 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")))] diff --git a/crates/processing_audio/src/tests.rs b/crates/processing_audio/src/tests.rs index bf7c06ae..7bce6f83 100644 --- a/crates/processing_audio/src/tests.rs +++ b/crates/processing_audio/src/tests.rs @@ -9,13 +9,14 @@ 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::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(); @@ -131,6 +132,132 @@ fn restart(world: &mut 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()); @@ -141,6 +268,7 @@ fn audio_is_off_unless_enabled() { let world = app.world_mut(); assert!(!world.contains_resource::()); assert!(!world.contains_resource::()); + assert!(graph::graph_output(world).is_err()); } #[test] @@ -157,6 +285,8 @@ fn startup_opens_the_stream() { .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); } diff --git a/crates/processing_core/src/error.rs b/crates/processing_core/src/error.rs index 3f1ca4a7..e626cc6f 100644 --- a/crates/processing_core/src/error.rs +++ b/crates/processing_core/src/error.rs @@ -86,4 +86,14 @@ pub enum ProcessingError { 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/prelude.rs b/src/prelude.rs index edfa89e7..8540f7b0 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -4,10 +4,13 @@ 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, + 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::*;