Skip to content

Commit 68a255e

Browse files
committed
processing_audio: level meters and patch bay
Adds a mono peak meter node, read as linear amplitude, and a patch bay: one metered jack per graph input and output channel. Routing through jacks instead of the graph I/O makes every channel's level readable without extra wiring, and a meter passes its signal through unchanged (audio or CV).
1 parent 5c9e820 commit 68a255e

5 files changed

Lines changed: 267 additions & 5 deletions

File tree

‎crates/processing_audio/src/graph.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use bevy::prelude::*;
44
use bevy::reflect::enums::{DynamicEnum, DynamicVariant};
55
use bevy::reflect::{GetPath, PartialReflect, TypeInfo};
66
use bevy_seedling::firewheel::dsp::mix::Mix;
7+
use bevy_seedling::node::AudioState;
78
use bevy_seedling::prelude::*;
89

910
use processing_core::error::{ProcessingError, Result};
@@ -22,6 +23,9 @@ pub enum AudioNodeKind {
2223
Freeverb,
2324
WhiteNoise,
2425
PinkNoise,
26+
/// Peak level meter, read with `audio_meter_level`. 1 in / 1 out; the
27+
/// signal passes through unchanged, so it can sit inline or on a tap.
28+
Meter,
2529
}
2630

2731
/// Supported filter widths.
@@ -52,6 +56,7 @@ impl AudioNodeKind {
5256
AudioNodeKind::Mix => (channels * 2, channels),
5357
AudioNodeKind::VolumePan | AudioNodeKind::Freeverb => (2, 2),
5458
AudioNodeKind::WhiteNoise | AudioNodeKind::PinkNoise => (0, 1),
59+
AudioNodeKind::Meter => (1, 1),
5560
};
5661
AudioPorts { inputs, outputs }
5762
}
@@ -132,6 +137,10 @@ pub(crate) fn register_nodes(app: &mut App) {
132137
widths::<6>(app);
133138
widths::<7>(app);
134139
widths::<8>(app);
140+
141+
// seedling registers only the stereo meter
142+
app.register_node::<PeakMeterNode<1>>()
143+
.register_node_state::<PeakMeterNode<1>, PeakMeterState<1>>();
135144
}
136145

137146
fn nonzero(channels: u32) -> NonZeroChannelCount {
@@ -183,10 +192,35 @@ pub(crate) fn node_create(
183192
AudioNodeKind::PinkNoise => {
184193
entity.insert(PinkNoiseGenNode::default());
185194
}
195+
AudioNodeKind::Meter => {
196+
entity.insert(PeakMeterNode::<1> { enabled: true });
197+
}
186198
}
187199
Ok(entity.id())
188200
}
189201

202+
/// A meter's latest peak as linear amplitude: 0 is silence, 1 is full
203+
/// scale. Reads 0 until the node is running in the audio graph.
204+
pub(crate) fn meter_level(In(node): In<Entity>, world: &mut World) -> Result<f32> {
205+
match world.get::<AudioNodeType>(node) {
206+
Some(ty) if ty.kind == AudioNodeKind::Meter => {}
207+
_ => {
208+
return Err(ProcessingError::InvalidArgument(
209+
"not an AudioNodeKind::Meter node".into(),
210+
));
211+
}
212+
}
213+
let Some(state) = world.get::<AudioState<PeakMeterState<1>>>(node) else {
214+
return Ok(0.0);
215+
};
216+
let [db] = state.0.peak_gain_db(-120.0);
217+
Ok(if db.is_finite() {
218+
10f32.powf(db / 20.0)
219+
} else {
220+
0.0
221+
})
222+
}
223+
190224
pub(crate) fn node_destroy(In(node): In<Entity>, world: &mut World) -> Result<()> {
191225
if world.get::<AudioNodeType>(node).is_none() {
192226
return Err(ProcessingError::AudioNodeNotFound);
@@ -221,6 +255,7 @@ fn with_params<T>(
221255
AudioNodeKind::Freeverb => f(get::<FreeverbNode>(world, node)?.as_mut()),
222256
AudioNodeKind::WhiteNoise => f(get::<WhiteNoiseGenNode>(world, node)?.as_mut()),
223257
AudioNodeKind::PinkNoise => f(get::<PinkNoiseGenNode>(world, node)?.as_mut()),
258+
AudioNodeKind::Meter => f(get::<PeakMeterNode<1>>(world, node)?.as_mut()),
224259
AudioNodeKind::Svf => {
225260
for_channels!(ty.channels, |N| f(get::<SvfNode<N>>(world, node)?.as_mut()))
226261
}

‎crates/processing_audio/src/lib.rs‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ mod device;
1111
#[cfg(not(target_arch = "wasm32"))]
1212
mod graph;
1313
#[cfg(not(target_arch = "wasm32"))]
14+
mod patchbay;
15+
#[cfg(not(target_arch = "wasm32"))]
1416
mod sample;
1517

1618
#[cfg(not(target_arch = "wasm32"))]
@@ -55,9 +57,10 @@ mod native {
5557

5658
pub use crate::device::{AudioDevice, AudioEvent, AudioInfo, AudioStatus, parse_device};
5759
pub use crate::graph::{AudioNodeKind, AudioPorts};
60+
pub use crate::patchbay::AudioJackLevels;
5861

5962
use crate::device::{self, AudioDeviceState};
60-
use crate::{graph, sample};
63+
use crate::{graph, patchbay, sample};
6164

6265
#[derive(Resource, Clone, Copy, Debug, PartialEq, Eq)]
6366
pub(crate) enum AudioBackend {
@@ -259,6 +262,34 @@ mod native {
259262
with_audio(|world| graph::disconnect(In((src, dst, ports.to_vec())), world))
260263
}
261264

265+
/// A meter node's current peak level as linear amplitude (0 silent, 1
266+
/// full scale). Create one with `AudioNodeKind::Meter` and connect any
267+
/// port to its input.
268+
pub fn audio_meter_level(meter: Entity) -> Result<f32> {
269+
with_audio(|world| graph::meter_level(In(meter), world))
270+
}
271+
272+
// --- patch bay ---
273+
274+
/// The jack for input channel `channel` (0-based): a node whose output 0
275+
/// carries that channel. Connect from it instead of `audio_input()` and
276+
/// its level shows in `audio_jack_levels()`.
277+
pub fn audio_jack_input(channel: u32) -> Result<Entity> {
278+
with_audio(|world| patchbay::jack_input(In(channel), world))
279+
}
280+
281+
/// The jack for output channel `channel` (0-based): connect to its input
282+
/// 0 to send to that output. Several sources are summed.
283+
pub fn audio_jack_output(channel: u32) -> Result<Entity> {
284+
with_audio(|world| patchbay::jack_output(In(channel), world))
285+
}
286+
287+
/// Peak level of every input and output jack. Covers the whole graph
288+
/// width; jacks past the device's channel count read 0.
289+
pub fn audio_jack_levels() -> Result<AudioJackLevels> {
290+
with_audio(patchbay::jack_levels)
291+
}
292+
262293
// --- samples ---
263294

264295
pub fn audio_sample_load(path: impl Into<PathBuf>) -> Result<Entity> {
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
//! A patch bay: one metered jack per graph input and output channel.
2+
//!
3+
//! Route through jacks instead of `audio_input()` / `audio_output()` and
4+
//! every channel's level can be read without extra wiring. Each jack is a
5+
//! peak meter, which passes its signal through unchanged (audio or DC-coupled
6+
//! CV alike).
7+
//!
8+
//! Jacks cover the whole graph width, which is fixed when audio starts with
9+
//! the sketch, so they stay valid across device switches and unplugging. Jacks past the current
10+
//! device's channel count are silent.
11+
12+
use bevy::prelude::*;
13+
14+
use processing_core::error::{ProcessingError, Result};
15+
16+
use crate::graph::{self, AudioNodeKind};
17+
18+
#[derive(Resource)]
19+
struct PatchBay {
20+
inputs: Vec<Entity>,
21+
outputs: Vec<Entity>,
22+
}
23+
24+
/// Peak levels for every jack, as linear amplitude (0 silent, 1 full scale).
25+
#[derive(Clone, Debug, Default, PartialEq)]
26+
pub struct AudioJackLevels {
27+
pub inputs: Vec<f32>,
28+
pub outputs: Vec<f32>,
29+
}
30+
31+
/// The patch bay, built on first use.
32+
fn bay(world: &mut World) -> Result<&PatchBay> {
33+
if !world.contains_resource::<PatchBay>() {
34+
let input = graph::graph_input(world)?;
35+
let output = graph::graph_output(world)?;
36+
let ins = graph::ports_of(world, input)?.outputs;
37+
let outs = graph::ports_of(world, output)?.inputs;
38+
39+
let mut inputs = Vec::with_capacity(ins as usize);
40+
for ch in 0..ins {
41+
let jack = graph::node_create(In((AudioNodeKind::Meter, 1)), world)?;
42+
graph::connect(In((input, jack, vec![(ch, 0)])), world)?;
43+
inputs.push(jack);
44+
}
45+
let mut outputs = Vec::with_capacity(outs as usize);
46+
for ch in 0..outs {
47+
let jack = graph::node_create(In((AudioNodeKind::Meter, 1)), world)?;
48+
graph::connect(In((jack, output, vec![(0, ch)])), world)?;
49+
outputs.push(jack);
50+
}
51+
world.insert_resource(PatchBay { inputs, outputs });
52+
}
53+
Ok(world.resource::<PatchBay>())
54+
}
55+
56+
fn pick(jacks: &[Entity], channel: u32, side: &'static str) -> Result<Entity> {
57+
jacks
58+
.get(channel as usize)
59+
.copied()
60+
.ok_or(ProcessingError::AudioPortOutOfRange {
61+
side,
62+
port: channel,
63+
count: jacks.len() as u32,
64+
})
65+
}
66+
67+
/// The jack for input `channel` (0-based). Its output 0 carries the signal.
68+
pub(crate) fn jack_input(In(channel): In<u32>, world: &mut World) -> Result<Entity> {
69+
pick(&bay(world)?.inputs, channel, "input jacks")
70+
}
71+
72+
/// The jack for output `channel` (0-based). Whatever is connected to its
73+
/// input 0 is sent to that output; several sources are summed.
74+
pub(crate) fn jack_output(In(channel): In<u32>, world: &mut World) -> Result<Entity> {
75+
pick(&bay(world)?.outputs, channel, "output jacks")
76+
}
77+
78+
pub(crate) fn jack_levels(world: &mut World) -> Result<AudioJackLevels> {
79+
let (inputs, outputs) = {
80+
let bay = bay(world)?;
81+
(bay.inputs.clone(), bay.outputs.clone())
82+
};
83+
let mut levels = |jacks: Vec<Entity>| -> Result<Vec<f32>> {
84+
jacks
85+
.into_iter()
86+
.map(|jack| graph::meter_level(In(jack), world))
87+
.collect()
88+
};
89+
Ok(AudioJackLevels {
90+
inputs: levels(inputs)?,
91+
outputs: levels(outputs)?,
92+
})
93+
}

‎crates/processing_audio/src/tests.rs‎

Lines changed: 103 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use processing_core::config::{Config, ConfigKey};
1616
use crate::device::{self, AudioDeviceState, AudioStatus};
1717
use crate::graph::{self, AudioNodeKind, AudioPorts};
1818
use crate::native::{self, AudioBackend};
19-
use crate::sample;
19+
use crate::{patchbay, sample};
2020

2121
const MOCK_RATE: NonZeroU32 = NonZeroU32::new(48_000).unwrap();
2222
const MOCK_CHANNELS: usize = 2;
@@ -283,6 +283,66 @@ fn sample_plays_through_a_sampler_to_completion() {
283283
assert!(began.elapsed() > std::time::Duration::from_millis(500));
284284
}
285285

286+
#[test]
287+
fn meter_reads_a_signal() {
288+
let mut app = test_app(2);
289+
let world = app.world_mut();
290+
let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap();
291+
let meter = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap();
292+
let silent = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap();
293+
graph::connect(In((noise, meter, vec![(0, 0)])), world).unwrap();
294+
295+
let began = std::time::Instant::now();
296+
let mut level = 0.0;
297+
while level == 0.0 && began.elapsed() < std::time::Duration::from_secs(3) {
298+
app.update();
299+
std::thread::sleep(std::time::Duration::from_millis(10));
300+
level = graph::meter_level(In(meter), app.world_mut()).unwrap();
301+
}
302+
assert!(level > 0.01, "meter never saw the noise (level {level})");
303+
assert_eq!(
304+
graph::meter_level(In(silent), app.world_mut()).unwrap(),
305+
0.0
306+
);
307+
assert!(graph::meter_level(In(noise), app.world_mut()).is_err());
308+
}
309+
310+
#[test]
311+
fn jacks_pass_signal_through_and_meter_it() {
312+
let mut app = test_app(4);
313+
let world = app.world_mut();
314+
let out2 = patchbay::jack_output(In(2), world).unwrap();
315+
assert!(patchbay::jack_output(In(4), world).is_err());
316+
assert!(patchbay::jack_input(In(3), world).is_ok());
317+
318+
// noise -> a meter -> output jack 2: signal on jack 2 proves the first
319+
// meter passes audio through, and the jack meters it
320+
let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap();
321+
let inline = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap();
322+
graph::connect(In((noise, inline, vec![(0, 0)])), world).unwrap();
323+
graph::connect(In((inline, out2, vec![(0, 0)])), world).unwrap();
324+
325+
let output = graph::graph_output(world).unwrap();
326+
let began = std::time::Instant::now();
327+
let mut levels = patchbay::AudioJackLevels::default();
328+
while began.elapsed() < std::time::Duration::from_secs(3) {
329+
app.update();
330+
std::thread::sleep(std::time::Duration::from_millis(10));
331+
levels = patchbay::jack_levels(app.world_mut()).unwrap();
332+
if levels.outputs[2] > 0.0 {
333+
break;
334+
}
335+
}
336+
assert_eq!(levels.inputs.len(), 4);
337+
assert_eq!(levels.outputs.len(), 4);
338+
assert!(levels.outputs[2] > 0.01, "no signal on jack 2: {levels:?}");
339+
assert_eq!(levels.outputs[0], 0.0);
340+
341+
// and the jack is wired to graph output port 2
342+
let (j, o) = (node_id(&app, out2), node_id(&app, output));
343+
assert!(edges(&mut app).contains(&(j, 0, o, 2)));
344+
}
345+
286346
#[test]
287347
fn unwired_nodes_are_not_auto_connected() {
288348
let mut app = test_app(2);
@@ -341,6 +401,33 @@ fn startup_opens_the_stream() {
341401
assert_eq!(world.resource::<AudioDeviceState>().want_input, None);
342402
}
343403

404+
#[test]
405+
fn restart_keeps_the_patch() {
406+
let mut app = test_app(8);
407+
let world = app.world_mut();
408+
let input = graph::graph_input(world).unwrap();
409+
let output = graph::graph_output(world).unwrap();
410+
let filter = graph::node_create(In((AudioNodeKind::Lowpass, 1)), world).unwrap();
411+
graph::connect(In((input, filter, vec![(1, 0)])), world).unwrap();
412+
graph::connect(In((filter, output, vec![(0, 3)])), world).unwrap();
413+
app.update();
414+
let before = edges(&mut app);
415+
assert_eq!(before.len(), 2);
416+
417+
stop_mock_stream(app.world_mut());
418+
// the graph can still be edited while the stream is down
419+
let world = app.world_mut();
420+
let extra = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap();
421+
graph::connect(In((input, extra, vec![(2, 0)])), world).unwrap();
422+
app.update();
423+
424+
start_mock_stream(app.world_mut());
425+
app.update();
426+
let after = edges(&mut app);
427+
assert_eq!(after.len(), 3);
428+
assert!(before.iter().all(|e| after.contains(e)));
429+
}
430+
344431
fn heartbeat(app: &mut App) -> i64 {
345432
app.world_mut()
346433
.resource_mut::<AudioContext>()
@@ -362,6 +449,12 @@ fn assert_processing(app: &mut App, context: &str) {
362449
#[test]
363450
fn restart_with_new_block_sizes_keeps_running() {
364451
let mut app = test_app(2);
452+
let world = app.world_mut();
453+
let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap();
454+
let filter = graph::node_create(In((AudioNodeKind::Lowpass, 1)), world).unwrap();
455+
let meter = graph::node_create(In((AudioNodeKind::Meter, 1)), world).unwrap();
456+
graph::connect(In((noise, filter, vec![(0, 0)])), world).unwrap();
457+
graph::connect(In((filter, meter, vec![(0, 0)])), world).unwrap();
365458
app.update();
366459
assert_processing(&mut app, "before any restart");
367460

@@ -374,4 +467,13 @@ fn restart_with_new_block_sizes_keeps_running() {
374467
assert_processing(&mut app, &format!("after restarting at {frames} frames"));
375468
app.update();
376469
}
470+
471+
let began = Instant::now();
472+
let mut level = 0.0;
473+
while level == 0.0 && began.elapsed() < Duration::from_secs(3) {
474+
app.update();
475+
std::thread::sleep(Duration::from_millis(10));
476+
level = graph::meter_level(In(meter), app.world_mut()).unwrap();
477+
}
478+
assert!(level > 0.01, "patch lost across restarts (level {level})");
377479
}

‎src/prelude.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ pub use bevy::prelude::default;
44
pub use bevy::render::render_resource::TextureFormat;
55
#[cfg(not(target_arch = "wasm32"))]
66
pub use processing_audio::{
7-
AudioDevice, AudioEvent, AudioInfo, AudioNodeKind, AudioPorts, AudioStatus, audio_connect,
8-
audio_connect_channel, audio_disconnect, audio_events, audio_info, audio_input,
9-
audio_list_input_devices, audio_list_output_devices, audio_node_create, audio_node_destroy,
7+
AudioDevice, AudioEvent, AudioInfo, AudioJackLevels, AudioNodeKind, AudioPorts, AudioStatus,
8+
audio_connect, audio_connect_channel, audio_disconnect, audio_events, audio_info, audio_input,
9+
audio_jack_input, audio_jack_levels, audio_jack_output, audio_list_input_devices,
10+
audio_list_output_devices, audio_meter_level, audio_node_create, audio_node_destroy,
1011
audio_node_get, audio_node_ports, audio_node_set, audio_node_set_variant, audio_output,
1112
audio_restart, audio_sample_load, audio_sample_play, audio_sample_stop, audio_sampler_create,
1213
audio_set_block_frames, audio_set_input_device, audio_set_input_device_index,

0 commit comments

Comments
 (0)