diff --git a/crates/processing_audio/src/graph.rs b/crates/processing_audio/src/graph.rs index de2bf53f..2725406e 100644 --- a/crates/processing_audio/src/graph.rs +++ b/crates/processing_audio/src/graph.rs @@ -9,6 +9,7 @@ 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::node::AudioState; use bevy_seedling::prelude::*; use processing_core::error::{ProcessingError, Result}; @@ -40,6 +41,9 @@ pub enum AudioNodeKind { WhiteNoise, /// Pink noise source (`volume`). 0 in / 1 out. PinkNoise, + /// Peak level meter, read with `audio_meter_level`. 1 in / 1 out; the + /// signal passes through unchanged, so it can sit inline or on a tap. + Meter, } /// Channel counts the filters support. @@ -72,6 +76,7 @@ impl AudioNodeKind { AudioNodeKind::Mix => (channels * 2, channels), AudioNodeKind::VolumePan | AudioNodeKind::Freeverb => (2, 2), AudioNodeKind::WhiteNoise | AudioNodeKind::PinkNoise => (0, 1), + AudioNodeKind::Meter => (1, 1), }; AudioPorts { inputs, outputs } } @@ -153,6 +158,10 @@ pub(crate) fn register_nodes(app: &mut App) { widths::<6>(app); widths::<7>(app); widths::<8>(app); + + // seedling registers only the stereo meter + app.register_node::>() + .register_node_state::, PeakMeterState<1>>(); } fn nonzero(channels: u32) -> NonZeroChannelCount { @@ -204,10 +213,35 @@ pub(crate) fn node_create( AudioNodeKind::PinkNoise => { entity.insert(PinkNoiseGenNode::default()); } + AudioNodeKind::Meter => { + entity.insert(PeakMeterNode::<1> { enabled: true }); + } } Ok(entity.id()) } +/// A meter's latest peak as linear amplitude: 0 is silence, 1 is full +/// scale. Reads 0 until the node is running in the audio graph. +pub(crate) fn meter_level(In(node): In, world: &mut World) -> Result { + match world.get::(node) { + Some(ty) if ty.kind == AudioNodeKind::Meter => {} + _ => { + return Err(ProcessingError::InvalidArgument( + "not an AudioNodeKind::Meter node".into(), + )); + } + } + let Some(state) = world.get::>>(node) else { + return Ok(0.0); + }; + let [db] = state.0.peak_gain_db(-120.0); + Ok(if db.is_finite() { + 10f32.powf(db / 20.0) + } else { + 0.0 + }) +} + pub(crate) fn node_destroy(In(node): In, world: &mut World) -> Result<()> { if world.get::(node).is_none() { return Err(ProcessingError::AudioNodeNotFound); @@ -243,6 +277,7 @@ fn with_params( 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::Meter => f(get::>(world, node)?.as_mut()), AudioNodeKind::Svf => { for_channels!(ty.channels, |N| f(get::>(world, node)?.as_mut())) } diff --git a/crates/processing_audio/src/lib.rs b/crates/processing_audio/src/lib.rs index a6bf6ec6..f766e9d2 100644 --- a/crates/processing_audio/src/lib.rs +++ b/crates/processing_audio/src/lib.rs @@ -24,6 +24,8 @@ //! `(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. +//! - **Patch bay.** [`audio_jack_input`] and [`audio_jack_output`] give a +//! metered node per channel; [`audio_jack_levels`] reads them all. //! - **Samples.** [`audio_sample_load`], [`audio_sampler_create`] and //! [`audio_sample_play`]; each sampler has its own outputs to route. //! @@ -37,6 +39,8 @@ mod device; #[cfg(not(target_arch = "wasm32"))] mod graph; #[cfg(not(target_arch = "wasm32"))] +mod patchbay; +#[cfg(not(target_arch = "wasm32"))] mod sample; #[cfg(not(target_arch = "wasm32"))] @@ -86,9 +90,10 @@ mod native { pub use crate::device::{AudioDevice, AudioEvent, AudioInfo, AudioStatus, parse_device}; pub use crate::graph::{AudioNodeKind, AudioPorts}; + pub use crate::patchbay::AudioJackLevels; use crate::device::{self, AudioDeviceState}; - use crate::{graph, sample}; + use crate::{graph, patchbay, sample}; /// What opens the stream at startup. #[derive(Resource, Clone, Copy, Debug, PartialEq, Eq)] @@ -320,6 +325,34 @@ mod native { with_audio(|world| graph::disconnect(In((src, dst, ports.to_vec())), world)) } + /// A meter node's current peak level as linear amplitude (0 silent, 1 + /// full scale). Create one with `AudioNodeKind::Meter` and connect any + /// port to its input. + pub fn audio_meter_level(meter: Entity) -> Result { + with_audio(|world| graph::meter_level(In(meter), world)) + } + + // --- patch bay --- + + /// The jack for input channel `channel` (0-based): a node whose output 0 + /// carries that channel. Connect from it instead of `audio_input()` and + /// its level shows in `audio_jack_levels()`. + pub fn audio_jack_input(channel: u32) -> Result { + with_audio(|world| patchbay::jack_input(In(channel), world)) + } + + /// The jack for output channel `channel` (0-based): connect to its input + /// 0 to send to that output. Several sources are summed. + pub fn audio_jack_output(channel: u32) -> Result { + with_audio(|world| patchbay::jack_output(In(channel), world)) + } + + /// Peak level of every input and output jack. Covers the whole graph + /// width; jacks past the device's channel count read 0. + pub fn audio_jack_levels() -> Result { + with_audio(patchbay::jack_levels) + } + // --- samples --- /// Load and decode a sound file (wav, ogg, flac), blocking until it is diff --git a/crates/processing_audio/src/patchbay.rs b/crates/processing_audio/src/patchbay.rs new file mode 100644 index 00000000..021b72ef --- /dev/null +++ b/crates/processing_audio/src/patchbay.rs @@ -0,0 +1,93 @@ +//! A patch bay: one metered jack per graph input and output channel. +//! +//! Route through jacks instead of `audio_input()` / `audio_output()` and +//! every channel's level can be read without extra wiring. Each jack is a +//! peak meter, which passes its signal through unchanged (audio or DC-coupled +//! CV alike). +//! +//! Jacks cover the whole graph width, which is fixed when audio starts with +//! the sketch, so they stay valid across device switches and unplugging. Jacks past the current +//! device's channel count are silent. + +use bevy::prelude::*; + +use processing_core::error::{ProcessingError, Result}; + +use crate::graph::{self, AudioNodeKind}; + +#[derive(Resource)] +struct PatchBay { + inputs: Vec, + outputs: Vec, +} + +/// Peak levels for every jack, as linear amplitude (0 silent, 1 full scale). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AudioJackLevels { + pub inputs: Vec, + pub outputs: Vec, +} + +/// The patch bay, built on first use. +fn bay(world: &mut World) -> Result<&PatchBay> { + if !world.contains_resource::() { + let input = graph::graph_input(world)?; + let output = graph::graph_output(world)?; + let ins = graph::ports_of(world, input)?.outputs; + let outs = graph::ports_of(world, output)?.inputs; + + let mut inputs = Vec::with_capacity(ins as usize); + for ch in 0..ins { + let jack = graph::node_create(In((AudioNodeKind::Meter, 1)), world)?; + graph::connect(In((input, jack, vec![(ch, 0)])), world)?; + inputs.push(jack); + } + let mut outputs = Vec::with_capacity(outs as usize); + for ch in 0..outs { + let jack = graph::node_create(In((AudioNodeKind::Meter, 1)), world)?; + graph::connect(In((jack, output, vec![(0, ch)])), world)?; + outputs.push(jack); + } + world.insert_resource(PatchBay { inputs, outputs }); + } + Ok(world.resource::()) +} + +fn pick(jacks: &[Entity], channel: u32, side: &'static str) -> Result { + jacks + .get(channel as usize) + .copied() + .ok_or(ProcessingError::AudioPortOutOfRange { + side, + port: channel, + count: jacks.len() as u32, + }) +} + +/// The jack for input `channel` (0-based). Its output 0 carries the signal. +pub(crate) fn jack_input(In(channel): In, world: &mut World) -> Result { + pick(&bay(world)?.inputs, channel, "input jacks") +} + +/// The jack for output `channel` (0-based). Whatever is connected to its +/// input 0 is sent to that output; several sources are summed. +pub(crate) fn jack_output(In(channel): In, world: &mut World) -> Result { + pick(&bay(world)?.outputs, channel, "output jacks") +} + +pub(crate) fn jack_levels(world: &mut World) -> Result { + let (inputs, outputs) = { + let bay = bay(world)?; + (bay.inputs.clone(), bay.outputs.clone()) + }; + let mut levels = |jacks: Vec| -> Result> { + jacks + .into_iter() + .map(|jack| graph::meter_level(In(jack), world)) + .collect() + }; + Ok(AudioJackLevels { + inputs: levels(inputs)?, + outputs: levels(outputs)?, + }) +} diff --git a/crates/processing_audio/src/tests.rs b/crates/processing_audio/src/tests.rs index f80d7068..53f497da 100644 --- a/crates/processing_audio/src/tests.rs +++ b/crates/processing_audio/src/tests.rs @@ -18,7 +18,7 @@ use processing_core::config::{Config, ConfigKey}; use crate::device::{self, AudioDeviceState, AudioStatus}; use crate::graph::{self, AudioNodeKind, AudioPorts}; use crate::native::{self, AudioBackend}; -use crate::sample; +use crate::{patchbay, sample}; const MOCK_RATE: NonZeroU32 = NonZeroU32::new(48_000).unwrap(); const MOCK_CHANNELS: usize = 2; @@ -297,6 +297,66 @@ fn sample_plays_through_a_sampler_to_completion() { assert!(began.elapsed() > std::time::Duration::from_millis(500)); } +#[test] +fn meter_reads_a_signal() { + let mut app = test_app(2); + let world = app.world_mut(); + let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap(); + let meter = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap(); + let silent = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap(); + graph::connect(In((noise, meter, vec![(0, 0)])), world).unwrap(); + + let began = std::time::Instant::now(); + let mut level = 0.0; + while level == 0.0 && began.elapsed() < std::time::Duration::from_secs(3) { + app.update(); + std::thread::sleep(std::time::Duration::from_millis(10)); + level = graph::meter_level(In(meter), app.world_mut()).unwrap(); + } + assert!(level > 0.01, "meter never saw the noise (level {level})"); + assert_eq!( + graph::meter_level(In(silent), app.world_mut()).unwrap(), + 0.0 + ); + assert!(graph::meter_level(In(noise), app.world_mut()).is_err()); +} + +#[test] +fn jacks_pass_signal_through_and_meter_it() { + let mut app = test_app(4); + let world = app.world_mut(); + let out2 = patchbay::jack_output(In(2), world).unwrap(); + assert!(patchbay::jack_output(In(4), world).is_err()); + assert!(patchbay::jack_input(In(3), world).is_ok()); + + // noise -> a meter -> output jack 2: signal on jack 2 proves the first + // meter passes audio through, and the jack meters it + let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap(); + let inline = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap(); + graph::connect(In((noise, inline, vec![(0, 0)])), world).unwrap(); + graph::connect(In((inline, out2, vec![(0, 0)])), world).unwrap(); + + let output = graph::graph_output(world).unwrap(); + let began = std::time::Instant::now(); + let mut levels = patchbay::AudioJackLevels::default(); + while began.elapsed() < std::time::Duration::from_secs(3) { + app.update(); + std::thread::sleep(std::time::Duration::from_millis(10)); + levels = patchbay::jack_levels(app.world_mut()).unwrap(); + if levels.outputs[2] > 0.0 { + break; + } + } + assert_eq!(levels.inputs.len(), 4); + assert_eq!(levels.outputs.len(), 4); + assert!(levels.outputs[2] > 0.01, "no signal on jack 2: {levels:?}"); + assert_eq!(levels.outputs[0], 0.0); + + // and the jack is wired to graph output port 2 + let (j, o) = (node_id(&app, out2), node_id(&app, output)); + assert!(edges(&mut app).contains(&(j, 0, o, 2))); +} + #[test] fn unwired_nodes_are_not_auto_connected() { let mut app = test_app(2); @@ -355,6 +415,33 @@ fn startup_opens_the_stream() { assert_eq!(world.resource::().want_input, None); } +#[test] +fn restart_keeps_the_patch() { + 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(); + graph::connect(In((input, filter, vec![(1, 0)])), world).unwrap(); + graph::connect(In((filter, output, vec![(0, 3)])), world).unwrap(); + app.update(); + let before = edges(&mut app); + assert_eq!(before.len(), 2); + + stop_mock_stream(app.world_mut()); + // the graph can still be edited while the stream is down + let world = app.world_mut(); + let extra = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap(); + graph::connect(In((input, extra, vec![(2, 0)])), world).unwrap(); + app.update(); + + start_mock_stream(app.world_mut()); + app.update(); + let after = edges(&mut app); + assert_eq!(after.len(), 3); + assert!(before.iter().all(|e| after.contains(e))); +} + fn heartbeat(app: &mut App) -> i64 { app.world_mut() .resource_mut::() @@ -378,6 +465,12 @@ fn assert_processing(app: &mut App, context: &str) { #[test] fn restart_with_new_block_sizes_keeps_running() { let mut app = test_app(2); + let world = app.world_mut(); + let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap(); + let filter = graph::node_create(In((AudioNodeKind::Lowpass, 1)), world).unwrap(); + let meter = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap(); + graph::connect(In((noise, filter, vec![(0, 0)])), world).unwrap(); + graph::connect(In((filter, meter, vec![(0, 0)])), world).unwrap(); app.update(); assert_processing(&mut app, "before any restart"); @@ -391,4 +484,13 @@ fn restart_with_new_block_sizes_keeps_running() { assert_processing(&mut app, &format!("after restarting at {frames} frames")); app.update(); } + + let began = Instant::now(); + let mut level = 0.0; + while level == 0.0 && began.elapsed() < Duration::from_secs(3) { + app.update(); + std::thread::sleep(Duration::from_millis(10)); + level = graph::meter_level(In(meter), app.world_mut()).unwrap(); + } + assert!(level > 0.01, "patch lost across restarts (level {level})"); } diff --git a/src/prelude.rs b/src/prelude.rs index 8f39da70..bfaffa39 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -4,9 +4,10 @@ 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, + AudioDevice, AudioEvent, AudioInfo, AudioJackLevels, AudioNodeKind, AudioPorts, AudioStatus, + audio_connect, audio_connect_channel, audio_disconnect, audio_events, audio_info, audio_input, + audio_jack_input, audio_jack_levels, audio_jack_output, audio_list_input_devices, + audio_list_output_devices, audio_meter_level, audio_node_create, audio_node_destroy, audio_node_get, audio_node_ports, audio_node_set, audio_node_set_variant, audio_output, audio_restart, audio_sample_load, audio_sample_play, audio_sample_stop, audio_sampler_create, audio_set_block_frames, audio_set_input_device, audio_set_input_device_index,