Interaction
Purposefully Unopinionated
Legato aims to leave UI up to the developer.
This means you can write your own UI with Webview technologies, frameworks like ICED, Bevvy, or EGUI, or even easily make terminal applications with Ratatui.
There will likely be a UI editor in the future but this is not immediately planned and works a bit against the intention of the project.
Controlling your Applications
In summary, you have ~6 ways to change values in the runtime:
Message Passing
These are drained once per audio block.
Simply send a message to your node like so:
let (app, mut frontend) = LegatoBuilder::<Unconfigured>::new(config)
.build_dsl(&graph)?;
frontend.send_node_msg(
"example",
NodeMessage::SetParam(ParamPayload {
param_name: "freq",
value: RtValue::F32(440.0),
}),
)?;
send_node_msg returns FrontendError::NodeNotFound for an unknown alias, and FrontendError::QueueFull if the audio thread hasn't drained the message queue (512 slots) yet. A message for a param the node doesn't know is ignored.
You'll notice that we are sending RtValue to the audio thread. These are designed so that they will not allocate or drop from the runtime, potentially causing clicks or pops.
Param Store
Additionally, you can use the param node to get a smoothed f32 value.
This is good for say something like a gain value, referenced by mutliple nodes.
Internally this uses atomics, and mirrors what various VST frameworks use.
frontend.set_param("freq", 440.0)?; // outputs 440.0 audio rate at the next block
// Or look the key up once, e.g. for a UI slider
let key = frontend.get_param_key("freq")?;
frontend.set_param_by_key(key, 220.0)?;
let current = frontend.get_param_by_key(key)?;
External Input
You can add an audio rate external input with a SPSC, like so:
let (producer, consumer) = rtrb::RingBuffer::new(4096 * 4); // 4 frames of headroom
let (app, _) = LegatoBuilder::<Unconfigured>::new(config)
// Adding the audio input here
.register_audio_input("one", consumer, 1, config.block_size)
.build_dsl(&graph)?;
AudioInterface::builder(&host, config)
// Starts the input thread. Skip this if managing your own input.
.input(InputSpec {
producer,
chans: 1,
device: DeviceSelection::Default,
})
.build(app)
.expect("Failed to start audio")
.run_forever(); // Blocks here
Loading External Buffers
We can also load in external buffers from another thread. These are then reference counted and therefore safe to use in the runtime*.
Samples are decoded with ffmpeg, so an ffmpeg binary must be on your PATH. load_sample returns AudioSampleError::FfmpegNotFound if it isn't, PathNotFound for a missing file, and FailedDecoding with ffmpeg's error otherwise.
let (app, mut frontend) = LegatoBuilder::new(config)
.set_midi_runtime(midi_rt_fe)
.build_dsl(&graph)
.expect("graph should build");
frontend
.load_sample(
"main",
Path::new("../samples/string.wav"),
2,
config.sample_rate as u32,
)
.expect("Could not load sample!");
MIDI Applications
Full MIDI specification is still quite a bit aways, but for the time being you can control your applications with a MIDI runtime like so:
let midi_rt_fe = start_midi_thread(
256,
"my_port",
MidiPortKind::Index(0), // or MidiPortKind::Named("Keystep")
MidiPortKind::Index(0),
"my_port",
)?;
let (app, mut frontend) = LegatoBuilder::new(config)
.set_midi_runtime(midi_rt_fe)
.build_dsl(&graph)
.expect("graph should build");
With no MIDI hardware attached, MidiPortKind::Index(0) returns MidiError::InvalidPort. On macOS and Linux, MidiPortKind::Virtual creates a port named port_name that a DAW or another app can connect to instead.
And later in your graph, you can use the MIDI nodes like so:
// ...
midi {
poly_voice { chan: 0, voices: 3 }
}
// We use port striding here to target multiple voices
poly_voice[0:10:3] >> voice(*).gate
poly_voice[1:10:3] >> voice(*).freq
Node States and Batches
You may find yourself wanting to create more high-level abstractions on top of the Legato runtime, such as instruments, effects.
We will briefly discuss a few more APIs and DSL features that can assist with this.
Node State
Nodes have the following internal states:
- active: it runs normally, as expected, no keyword required in the DSL
muted: still runs internally, for instance a sine would increment phase, but we do not output anythingbypassed: we take thedefault_inaudio inputs and simply bypass them out, you have to double check your input and output arities- fading: when moving between the various states, Legato adds a small cross fade to remove any pops or clicks that might occur. You don't have to handle or define this yourself.
We can then use the DSL to declare the initial state like so:
audio {
mute sine { freq: 440.0 }
}
This is quite helpful, as we can reuse our selection syntax to mute, enable, or bypass large sections of our graphs. This helps us compose things like effects racks and instruments.
It's worth noting that muted nodes will still have the same computational work done, as they still continue processing internally.
use legato::node_state::NodeState;
frontend.set_state("room", NodeState::Active)?;
frontend.set_state("voice(2).osc", NodeState::Muted)?;
frontend.set_state("voice.2.tone", NodeState::Bypassed)?;
// Multiple voices lands in the same block, more detail further on...
frontend.set_state("voice(*).osc", NodeState::Muted)?;
frontend.set_state("room", NodeState::Suspended)?;
It's worth noting however, that the arity must match when using NodeState::Bypassed.
If we have an oscillator with no default_in ports, and one audio out port, and try to bypass, we will
have an arity mismatch and receive an error:
frontend.set_state("voice(0).osc", NodeState::Bypassed)
// Err: 'voice.0.osc' cannot be bypassed: bypass copies each input marked with
// `PortBuilder::default_in()` to the matching default output, but it marks
// 0 inputs for 1 default outputs
You can sort of think of this in the same way as how some DAWs have instruments that don't take in any incoming audio, and you also have effects that process incoming audio. We do the same, but more explicitly, as Legato nodes can have other channels for sample accurate modulation.
For example, a stereo distortion node might prefer to define its ports like so, so that it can
be bypassed. Notice how the default_in() builder call captures the last registered ports.
Since this arity matches the .audio_out() call, we can bypass this node.
PortBuilder::default()
.audio_in(2)
.default_in() // bypass passes these through
.control_in_named(&["drive", "tone"])
.audio_out(2)
.build()
Atomic Message Batches
You'll notice that were were updating single parameters at a time. This could potentially race the audio thread and give unexpected patches or outcomes.
To solve this, we can use a few different batching APIs, which can take numerous parameter updates and apply them in the same transaction.
Under the hood, these will create an atomically reference counted array of parameters. The audio thread will drain this, and send the array back to the frontend.
This ensures that this drop/deallocation only takes place on the UI thread, not our realtime safe audio thread, preventing pops and clicks.
Here we mute two of our voices and raise the resonance on the one that is left, and both
changes land in the same block using the batch(|b|) API:
frontend.batch(|b| {
b.mute("voice(1..3)")?;
b.set("voice(0).tone", "q", 2.0)?;
Ok::<_, FrontendError>(())
})?;
If any update in the batch fails, for instance a typo in a node name, nothing is sent.
Reusable Presets
Once we've made a batch, we can hold onto it and send it as many times as we like. Sending shares the batch rather than copying it, and it won't be dropped as long as there is a reference.
Here is an example where we will define a handful of presets, turn them into batches once, and apply them later:
use legato::{FrontendError, LegatoFrontend, batch::MessageBatch};
struct Preset {
voices: usize, // how many voices play
cutoff: f32,
q: f32,
room: bool,
}
const PRESETS: [Preset; 3] = [
Preset { voices: 1, cutoff: 600.0, q: 0.7, room: false },
Preset { voices: 2, cutoff: 1200.0, q: 1.5, room: true },
Preset { voices: 3, cutoff: 3000.0, q: 0.5, room: true },
];
fn preset(frontend: &LegatoFrontend, p: &Preset) -> Result<MessageBatch, FrontendError> {
frontend.build_batch(|b| {
for i in 0..3 {
let voice = format!("voice({i})");
if i < p.voices {
b.activate(&voice)?;
} else {
b.mute(&voice)?;
}
}
b.set("voice(*).tone", "q", p.q)?;
b.set_param("cut", p.cutoff)?;
if p.room {
b.activate("room")?;
} else {
b.bypass("room")?;
}
Ok(())
})
}
let presets = PRESETS
.iter()
.map(|p| preset(&frontend, p))
.collect::<Result<Vec<_>, _>>()?;
frontend.send_batch(&presets[0])?;
// Later, e.g. from a button
frontend.send_batch(&presets[2])?;
Custom Nodes
If you need additional control inside the audio thread, and the above to not suffice if may be time for a custom node.
You can read more about this in the custom nodes section.