Custom Nodes
What Is a Node?
Nodes in Legato are individual units responsible for audio processing. You can extend the included nodes at the start of the application runtime. This allows users the ability to easily modify the framework to meet their usecase.
When should you use a custom node?
The DSL is somewhat limiting, and this is by design. I do not want users to have to learn an entirely
new language that they will never use in another context! It is simply for quick, git trackable application topologies.
Custom nodes are generally not too hard to implement, and sidestep a lot of the more challenging Rust features. I would suggest looking at a few basic nodes for reference, such as onepole.rs and sweep.rs.
Here are a few signs that it may be time for you to write a custom node:
- You want to add a
Nodewith new processing abilities - You want to express a concept not found in the DSL
- You need fine-tuned control over a node
- You want to use or link another library for audio processing
- You need complicated logic with additional threads or other synchronization primitives
Developing Custom Nodes
Custom nodes have the following requirements:
- Design the node and
impl Nodefor it. The Sweep node (shipped inlegato::nodes::audio::sweep) is a relatively uncomplicated example.
use std::time::Duration;
use legato::prelude::*;
/// Keep all of the owned state for the node here
pub struct Sweep {
phase: f32,
range: [f32; 2],
duration: Duration,
elapsed: usize,
ports: Ports,
}
impl Sweep {
pub fn new(range: &[f32], duration: Duration, chans: usize) -> Self {
let mut new_range = [0.0; 2];
new_range.copy_from_slice(range);
Self {
phase: 0.0,
range: new_range,
duration,
elapsed: 0,
// This defines the arity for your node and enough space for its outputs.
// `default_out()` lets a bare `sweep >> node` read from them.
ports: PortBuilder::default().audio_out(chans).default_out().build(),
}
}
}
impl Node for Sweep {
fn process(&mut self, ctx: &mut AudioContext, _: &Inputs, ao: &mut [&mut [f32]]) {
// The [`AudioContext`] contains shared state, such as global config, and shared resources like samples or LUT
let config = ctx.get_config();
let fs = config.sample_rate as f32;
let block_size = ctx.get_config().block_size;
let mut min = self.range[0];
let max = self.range[1];
min = min.clamp(1.0, max);
for n in 0..block_size {
let t = (self.elapsed as f32 / fs).min(self.duration.as_secs_f32());
let freq = min * ((max / min).powf(t / self.duration.as_secs_f32()));
self.elapsed += 1;
self.phase += freq / fs;
self.phase = self.phase.fract();
let sample = (self.phase * std::f32::consts::TAU).sin();
// Write our to each channel
for chan in ao.iter_mut() {
chan[n] = sample;
}
}
}
// The Executor calls this on construction to find this Node's arity
fn ports(&self) -> &Ports {
&self.ports
}
// Additionally, we have the optional handle_message function for message passing...
}
- Implement
NodeDefinition, which gives the node a name, its required/optional DSL parameters, and a factory function that builds it from parsed params.
impl NodeDefinition for Sweep {
const NAME: &'static str = "sweep";
const DESCRIPTION: &'static str = "Frequency sweep oscillator over a configurable range";
const REQUIRED_PARAMS: &'static [&'static str] = &[];
const OPTIONAL_PARAMS: &'static [&'static str] = &["duration", "range", "chans"];
fn create(
_rb: &mut ResourceBuilderView,
p: &DSLParams,
) -> Result<Box<dyn DynNode>, ValidationError> {
let chans = p.get_usize("chans")?.unwrap_or(2);
let duration = p
.get_duration_ms("duration")?
.unwrap_or(Duration::from_secs_f32(5.0));
let range = p.get_array_f32("range")?.unwrap_or([40., 48_000.].into());
Ok(Box::new(Self::new(&range, duration, chans)))
}
}
- Register the node with the builder and add it to your desired namespace.
let builder = builder.register_node("audio", Sweep::spec());
- You can now use your node in the DSL, spawn it many times, create reusable patches, etc.
If you feel that the node you made is quite general, feel free to submit a PR!
Patterns
Thread Synchronization with Custom Nodes
If you are adding additional functionality to your custom nodes, you may find yourself needing to synchronize with another threads.
To handle this, Legato has the handles feature, which lets you store arbitrary data that was created during a factory function call.
Here is a quick example, where our knob will be pulling in data via a SPSC. This pattern does extend to other synchronization primitives, but you will want to only use wait-free, non-locking implementations, or else you may cause clicks and pops in the audio thread!
use legato::{handles::ExportsHandle, prelude::*};
/// Outputs the latest value pushed from the application.
pub struct Knob {
rx: rtrb::Consumer<f32>,
value: f32,
ports: Ports,
}
impl Node for Knob {
// Kind of naive as this is block based, but you get the picture
fn process(&mut self, _: &mut AudioContext, _: &Inputs, ao: &mut [&mut [f32]]) {
while let Ok(v) = self.rx.pop() {
self.value = v;
}
ao[0].fill(self.value);
}
fn ports(&self) -> &Ports {
&self.ports
}
}
impl NodeDefinition for Knob {
const NAME: &'static str = "knob";
const DESCRIPTION: &'static str = "Outputs a value pushed from the application";
const REQUIRED_PARAMS: &'static [&'static str] = &[];
const OPTIONAL_PARAMS: &'static [&'static str] = &["capacity"];
fn create(
rb: &mut ResourceBuilderView,
p: &DSLParams,
) -> Result<Box<dyn DynNode>, ValidationError> {
let capacity = p.get_usize("capacity")?.unwrap_or(16);
let (tx, rx) = rtrb::RingBuffer::new(capacity);
// We export the handle here, it is now stored as a Box<dyn Any>, so we've lost type information
rb.export_handle(tx)?;
Ok(Box::new(Knob {
rx,
value: 0.0,
ports: PortBuilder::default().audio_out(1).default_out().build(),
}))
}
}
// Lets the application ask for the handle by node type instead of naming `rtrb::Producer<f32>`.
impl ExportsHandle for Knob {
type Handle = rtrb::Producer<f32>;
}
The handle is then stored under the node's alias and can be fetched with the below API.
After building, we can grab the handle, but we must specify the type and check it, as we've lost this information!
let (app, mut frontend) = LegatoBuilder::<Unconfigured>::new(config)
.register_node("user", Knob::spec())
.build_dsl(r#"
user { knob: cutoff }
{ cutoff }
"#)?;
let mut cutoff = frontend.take_handle_of::<Knob>("cutoff")?;
std::thread::spawn(move || {
cutoff.push(0.5).ok();
});
Handles are taken once. If two parts of your application need the same end, you can share it with an Arc primitive, but again
please check and make sure that you are using wait/lock-free primitives.
Many instances
The factory runs once per spawned instance, so knob * 3 has three separate factory calls and each will yield a consumer.
The take_handles_of API returns every handle under a path, in the order they were created:
let (app, mut frontend) = LegatoBuilder::<Unconfigured>::new(config)
.register_node("user", Knob::spec())
.build_dsl(r#"
user { knob * 3 }
audio { track_mixer: mix { tracks: 3, chans_per_track: 1 } }
knob(*) >> mix[0..3]
{ mix }
"#)?;
// [("knob.0", _), ("knob.1", _), ("knob.2", _)]
let mut knobs = frontend.take_handles_of::<Knob>("knob")?;
knobs[1].1.push(10.0).ok(); // only the second node hears this