truce_plugin/lib.rs
1//! User-facing plugin traits + internal bridge.
2//!
3//! This crate is the plugin author's entry point. The single
4//! `impl PluginLogic for MyPlugin { ... }` block covers both
5//! audio-thread DSP and main-thread GUI, with sample precision
6//! routed through the prelude (see `truce::prelude` /
7//! `truce::prelude64`).
8//!
9//! `truce-plugin` depends on `truce-gui-types` (light: layout,
10//! render trait, widget regions) - not the full `truce-gui`.
11//! Plugin authors who supply a custom editor (egui, iced, slint,
12//! raw window handle) end up with `truce-plugin` in their dep
13//! tree but not the built-in editor's tiny-skia + baseview +
14//! truce-font stack.
15//!
16//! ## Three traits, one source of truth
17//!
18//! - [`PluginLogic`] - what plugin authors implement for `f32`-buffer plugins.
19//! - [`PluginLogic64`] - what plugin authors implement for `f64`-buffer plugins.
20//! - [`PluginLogicCore`] - generic-over-`S` trait the format wrappers consume.
21//!
22//! The two leaf traits are stamped from one
23//! `plugin_logic_leaf_trait!` `macro_rules!` definition (further
24//! down this file) so their method surfaces stay in lock-step. Each leaf
25//! gets a blanket impl that forwards every method to
26//! `PluginLogicCore<S>` with the matching `S`. Wrappers
27//! (`StaticShell`, `HotShell`, the format crates) bind on
28//! `PluginLogicCore<S>` and don't care which leaf the user impl'd.
29//!
30//! ## What this buys
31//!
32//! Plugin authors writing `impl PluginLogic for Synth { ... }`
33//! never name a precision. The `truce::prelude64` re-export aliases
34//! `PluginLogic64` as `PluginLogic` in the user's scope, so the
35//! same impl header reads the same regardless of which prelude is
36//! in use. The `<S>` token that used to live on the impl header is
37//! gone - the prelude carries the precision choice.
38
39use truce_core::buffer::AudioBuffer;
40use truce_core::bus::BusLayout;
41use truce_core::denormal::DenormalGuard;
42use truce_core::editor::Editor;
43use truce_core::events::EventList;
44use truce_core::process::{ProcessContext, ProcessStatus};
45use truce_core::state::{ForeignState, MigratedState, StateLoadError};
46use truce_gui_types::interaction::WidgetRegion;
47use truce_gui_types::widgets::WidgetType;
48use truce_params::sample::Sample;
49
50// ---------------------------------------------------------------------------
51// PluginLogicCore - generic trait, what format wrappers consume
52// ---------------------------------------------------------------------------
53
54/// Wrapper-facing plugin trait, generic over the audio sample type.
55///
56/// Format wrappers (`StaticShell`, `HotShell`, CLAP / VST3 / etc.)
57/// bind on `PluginLogicCore<S>`. Plugin authors don't implement this
58/// directly - they implement [`PluginLogic`] (`f32`) or
59/// [`PluginLogic64`] (`f64`), and the blanket impls below route them
60/// into `PluginLogicCore`.
61///
62/// Method docs live on the leaf traits ([`PluginLogic`] /
63/// [`PluginLogic64`]); the shape mirrors them exactly.
64pub trait PluginLogicCore<S: Sample = f32>: Send + 'static {
65 #[must_use]
66 fn supports_in_place() -> bool
67 where
68 Self: Sized;
69
70 #[must_use]
71 fn bus_layouts() -> Vec<BusLayout>
72 where
73 Self: Sized;
74
75 fn reset(&mut self, sample_rate: f64, max_block_size: usize);
76
77 fn process(
78 &mut self,
79 buffer: &mut AudioBuffer<S>,
80 events: &EventList,
81 context: &mut ProcessContext,
82 ) -> ProcessStatus;
83
84 fn save_state(&self) -> Vec<u8>;
85 /// Lock-free state-save opt-in. See [`PluginLogic::snapshot_into`].
86 /// Called on the audio thread each block when supported; the shell
87 /// publishes the result into a `SnapshotSlot` the host reads without
88 /// the plugin lock. Default `false`; the leaf bridge overrides it.
89 fn snapshot_into(&self, buf: &mut Vec<u8>) -> bool {
90 let _ = buf;
91 false
92 }
93 /// Restore plugin-specific state. See [`PluginLogic::load_state`].
94 ///
95 /// # Errors
96 ///
97 /// Forwards whatever the user impl returns - typically a malformed
98 /// blob error decoded by `bincode` / `serde` / similar.
99 fn load_state(&mut self, data: &[u8]) -> Result<(), StateLoadError>;
100 /// Translate foreign state into truce shape. See
101 /// [`PluginLogic::migrate_state`].
102 #[must_use]
103 fn migrate_state(foreign: &ForeignState) -> Option<MigratedState>
104 where
105 Self: Sized;
106 fn state_changed(&mut self);
107 fn latency(&self) -> u32;
108 fn tail(&self) -> u32;
109}
110
111/// Precision-keyed editor factory, bridged from the leaf traits.
112///
113/// `plugin!` / `export_static!` / `export_plugin!` build the editor from
114/// the concrete logic type without naming which leaf trait
115/// ([`PluginLogic`] vs [`PluginLogic64`]) it implements. Keyed on `S`
116/// only so the two per-leaf blanket impls don't overlap - the editor and
117/// param store are precision-independent.
118///
119/// This lives off [`PluginLogicCore`] on purpose: it carries an
120/// associated `Params` type and a receiverless `editor`, either of which
121/// would make `PluginLogicCore` non-object-safe and break the
122/// hot-reload loader's type-erased `Box<dyn PluginLogicCore<S>>`. Only
123/// concrete code (the shells' macros) ever names it, never `dyn`.
124pub trait PluginEditor<S: Sample> {
125 /// The plugin's parameter struct; mirrors the leaf's `Params`.
126 type Params: truce_params::Params;
127
128 /// Build the editor from the lock-free param store. Receiverless, so
129 /// the wrapper constructs it while the audio thread runs, without the
130 /// plugin lock.
131 fn editor(params: std::sync::Arc<Self::Params>) -> Box<dyn Editor>;
132}
133
134// ---------------------------------------------------------------------------
135// Leaf traits - what plugin authors implement
136// ---------------------------------------------------------------------------
137
138/// Define a sample-pinned leaf trait. Two invocations:
139/// `PluginLogic` (f32) and [`PluginLogic64`] (f64). The trait
140/// definition has to be a macro because we want the two trait
141/// surfaces to stay in exact lock-step - adding a new method means
142/// updating one place, not three (the macro, plus two trait
143/// declarations).
144///
145/// Doc-hidden because it's a single-purpose internal macro, not an
146/// API users should reach for.
147#[doc(hidden)]
148#[macro_export]
149macro_rules! plugin_logic_leaf_trait {
150 ($(#[$attr:meta])* $vis:vis trait $name:ident<sample = $sample:ty>) => {
151 $(#[$attr])*
152 $vis trait $name: Send + 'static {
153 /// The plugin's parameter struct (`#[derive(Params)]`). Named
154 /// here so the editor can be built from an `Arc<Self::Params>`
155 /// without borrowing the plugin - see [`Self::editor`].
156 type Params: $crate::__plugin_logic_deps::Params;
157
158 /// Opt into zero-copy in-place I/O. When this returns `true`,
159 /// the format wrapper skips its safety memcpy on host-aliased
160 /// buffers and hands the plugin the raw shared memory through
161 /// `AudioBuffer::in_out_mut(ch)`. The plugin must check
162 /// `AudioBuffer::is_in_place(ch)` per channel before reading
163 /// `input(ch)`.
164 ///
165 /// Default `false`: the wrapper copies aliased inputs into
166 /// scratch so `input(ch)` and `output(ch)` are always
167 /// disjoint. Costs one memcpy per aliased channel per block.
168 #[must_use]
169 fn supports_in_place() -> bool
170 where
171 Self: Sized,
172 {
173 false
174 }
175
176 /// Supported audio bus configurations. The host picks one;
177 /// the others are rejected at bus-config time before
178 /// `process` is ever called. Default: stereo in, stereo out.
179 #[must_use]
180 fn bus_layouts() -> Vec<$crate::__plugin_logic_deps::BusLayout>
181 where
182 Self: Sized,
183 {
184 vec![$crate::__plugin_logic_deps::BusLayout::stereo()]
185 }
186
187 /// Reset for a new sample rate / block size. Called before
188 /// the first `process` and any time the host reconfigures.
189 fn reset(&mut self, sample_rate: f64, max_block_size: usize);
190
191 /// Process one block of audio. Real-time - no allocations,
192 /// locks, or I/O.
193 fn process(
194 &mut self,
195 buffer: &mut $crate::__plugin_logic_deps::AudioBuffer<$sample>,
196 events: &$crate::__plugin_logic_deps::EventList,
197 context: &mut $crate::__plugin_logic_deps::ProcessContext,
198 ) -> $crate::__plugin_logic_deps::ProcessStatus;
199
200 /// Serialize plugin-specific state (DSP state, not params -
201 /// those are saved automatically). Default: delegates to
202 /// [`Self::snapshot_into`] (empty when neither is
203 /// overridden).
204 ///
205 /// Runs on a host or GUI thread while the audio thread is
206 /// paused at a block boundary (the wrapper's plugin lock),
207 /// so reading any field is safe - but an audio block that
208 /// arrives mid-save waits for this to return. Keep it
209 /// cheap: copy bytes out, don't compute or compress here.
210 /// To take this off the plugin lock entirely, override
211 /// [`Self::snapshot_into`] instead.
212 fn save_state(&self) -> Vec<u8> {
213 let mut buf = Vec::new();
214 let _ = self.snapshot_into(&mut buf);
215 buf
216 }
217
218 /// Opt into lock-free state save. Serialize the same bytes
219 /// [`Self::save_state`] would into `buf` (cleared first;
220 /// capacity is retained across calls so a steady state is
221 /// allocation-free).
222 ///
223 /// The return value is a *static capability*, not a
224 /// per-block flag: `true` means "this plugin publishes
225 /// snapshots", `false` means "it never does" (the default).
226 /// Once you return `true` you must return `true` for the
227 /// plugin's whole lifetime - if the custom state empties out,
228 /// clear `buf` and still return `true` (an empty blob), don't
229 /// return `false`. The shell latches the opt-in on the first
230 /// published block; a later `false` is a contract violation
231 /// that would otherwise leave the host reading a stale
232 /// snapshot forever.
233 ///
234 /// Called on the **audio thread** after each process block,
235 /// under the same real-time rules as `process` - bounded, no
236 /// unbounded allocation. The wrapper publishes the result
237 /// into a lock-free slot the host reads without ever taking
238 /// the plugin lock, so saving state while audio runs never
239 /// stalls the audio thread. Overriding this is the
240 /// preferred way to serialize custom state; the default
241 /// [`Self::save_state`] delegates here.
242 fn snapshot_into(&self, buf: &mut Vec<u8>) -> bool {
243 let _ = buf;
244 false
245 }
246
247 /// Restore plugin-specific state.
248 ///
249 /// Runs on the audio thread between blocks, with the same
250 /// exclusive access `process()` has - writing any field
251 /// is safe.
252 ///
253 /// # Errors
254 ///
255 /// Return `Err(StateLoadError)` when the blob is malformed
256 /// or otherwise can't be interpreted - the format wrapper
257 /// logs the failure (and on hosts that support it, surfaces
258 /// it to the DAW).
259 fn load_state(
260 &mut self,
261 _data: &[u8],
262 ) -> Result<(), $crate::__plugin_logic_deps::StateLoadError> {
263 Ok(())
264 }
265
266 /// Called on the audio thread immediately after
267 /// [`Self::load_state`] returns. Invalidate or recompute any
268 /// caches the next `process()` reads. Default: no-op.
269 fn state_changed(&mut self) {}
270
271 /// Translate foreign state - a previous framework's blob,
272 /// or a truce envelope saved under a different plugin id -
273 /// into truce params + extra, so a plugin ported to truce
274 /// keeps its users' old sessions and presets. Runs on the
275 /// host thread; receiverless so it can't touch (or alias)
276 /// the live instance. Return `None` for bytes you don't
277 /// recognize - the wrapper then reports load failure to
278 /// the host, exactly as if this hook didn't exist.
279 ///
280 /// One-shot by construction: the next save writes a normal
281 /// truce envelope, so this never becomes a permanent
282 /// dual-format reader. Keyed formats (AU / LV2 / AAX) only
283 /// see foreign bytes when `truce.toml` declares the legacy
284 /// keys to probe (`[plugin.legacy_state]`).
285 #[must_use]
286 fn migrate_state(
287 _foreign: &$crate::__plugin_logic_deps::ForeignState,
288 ) -> Option<$crate::__plugin_logic_deps::MigratedState>
289 where
290 Self: Sized,
291 {
292 None
293 }
294
295 /// Report latency in samples for plugin delay compensation.
296 fn latency(&self) -> u32 {
297 0
298 }
299
300 /// Report tail time in samples (audio produced after input
301 /// stops - reverbs, delays). `u32::MAX` for infinite tail.
302 fn tail(&self) -> u32 {
303 0
304 }
305
306 // ---- GUI ----
307
308 /// Construct the editor for this plugin. Required.
309 ///
310 /// There is no auto-fallback - every plugin explicitly
311 /// names which renderer it wants. For the built-in
312 /// widget layout, call
313 /// `truce_gui::default_editor(params, layout)`; for
314 /// custom renderers, construct an `EguiEditor` /
315 /// `IcedEditor` / `SlintEditor` / hand-rolled `Editor`
316 /// here. The choice of renderer crate the plugin's
317 /// `Cargo.toml` pulls IS the choice of editor.
318 ///
319 /// An associated function, not a method: it receives the
320 /// lock-free `Arc<Self::Params>` store the wrapper already
321 /// holds, so the host can open the editor while audio is
322 /// running without ever taking the plugin lock. Editors bind
323 /// only to the param store (plus meters / transport, all
324 /// lock-free); custom DSP state is read at runtime through
325 /// the editor bridge, not at construction.
326 fn editor(
327 params: ::std::sync::Arc<Self::Params>,
328 ) -> Box<dyn $crate::__plugin_logic_deps::Editor>;
329 }
330 };
331}
332
333// Re-export the dependencies the leaf-trait macro substitutes by path,
334// under one `pub` doc-hidden module so user crates that invoke the
335// macro don't need to import each truce-core type by hand.
336#[doc(hidden)]
337pub mod __plugin_logic_deps {
338 pub use truce_core::buffer::AudioBuffer;
339 pub use truce_core::bus::BusLayout;
340 pub use truce_core::editor::Editor;
341 pub use truce_core::events::EventList;
342 pub use truce_core::process::{ProcessContext, ProcessStatus};
343 pub use truce_core::state::{ForeignState, MigratedState, StateLoadError};
344 pub use truce_params::Params;
345}
346
347plugin_logic_leaf_trait! {
348 /// The `f32`-buffer user-facing plugin trait.
349 ///
350 /// Plugin authors implement this in a single `impl` block when
351 /// their audio path is `f32` end-to-end (the default - matches
352 /// the host wire format for nearly all DAWs and formats).
353 /// `truce::prelude` and `truce::prelude32` re-export this name
354 /// directly; `truce::prelude64m` does too (the `m` mixed-precision
355 /// prelude keeps the audio buffer at `f32` and only switches the
356 /// `param.read()` precision).
357 ///
358 /// Required: [`Self::reset`], [`Self::process`], [`Self::editor`].
359 /// Everything else has a default. The editor is constructed
360 /// explicitly - layout-only plugins typically call
361 /// `truce_gui::default_editor(params, layout())` (where `layout()`
362 /// is a plain inherent method on the plugin struct, not part of the
363 /// trait).
364 ///
365 /// ## Params vs. DSP state
366 ///
367 /// The struct you implement this on holds two different kinds of
368 /// data, and the method receivers reflect the split:
369 ///
370 /// - **Params** - the user-facing values in your `#[derive(Params)]`
371 /// struct, held as `Arc<Self::Params>`. Atomic-backed and `Sync`,
372 /// shared lock-free with the host and the editor.
373 /// - **DSP state** - everything else on the struct: filter memory,
374 /// phase accumulators, voice buffers, delay lines. Plain and
375 /// non-atomic, mutated every sample, exclusive to the audio thread.
376 ///
377 /// `process` / `reset` / `load_state` take `&mut self` because they
378 /// mutate DSP state; `save_state` / `snapshot_into` take `&self`
379 /// because they read it. `editor` takes neither - it is an
380 /// associated function over the param store, because a GUI is a
381 /// *view* that binds only params (plus lock-free meters / transport)
382 /// and never touches DSP state, so it can be built without the
383 /// plugin lock. DSP state can't move into params: making per-sample
384 /// filter memory atomic-shared would put a synchronized access on
385 /// the hottest path, and it isn't a "parameter" anyway.
386 pub trait PluginLogic<sample = f32>
387}
388
389plugin_logic_leaf_trait! {
390 /// The `f64`-buffer user-facing plugin trait. Same surface as
391 /// [`PluginLogic`] but with the audio buffer pinned to `f64`.
392 ///
393 /// Plugin authors don't usually name this directly - `truce::prelude64`
394 /// re-exports it as `PluginLogic`, so the impl header reads the
395 /// same regardless of which precision the prelude chose. Pick
396 /// `truce::prelude64` (and thus this leaf) when the DSP path runs
397 /// in `f64` end-to-end and the wrapper-boundary widen/narrow
398 /// memcpy is worth the cleaner DSP code.
399 pub trait PluginLogic64<sample = f64>
400}
401
402// ---------------------------------------------------------------------------
403// Bridges - each leaf forwards every method to PluginLogicCore<S>
404// ---------------------------------------------------------------------------
405
406/// Define a blanket `impl<T: $leaf> PluginLogicCore<$sample> for T`
407/// that forwards every trait method to `<T as $leaf>::method(...)`.
408/// One source-of-truth for both `(PluginLogic, f32)` and
409/// `(PluginLogic64, f64)` bridges.
410macro_rules! plugin_logic_bridge {
411 ($leaf:ident, $sample:ty) => {
412 impl<T: $leaf> PluginLogicCore<$sample> for T {
413 fn supports_in_place() -> bool
414 where
415 Self: Sized,
416 {
417 <Self as $leaf>::supports_in_place()
418 }
419
420 fn bus_layouts() -> Vec<BusLayout>
421 where
422 Self: Sized,
423 {
424 <Self as $leaf>::bus_layouts()
425 }
426
427 fn reset(&mut self, sample_rate: f64, max_block_size: usize) {
428 <Self as $leaf>::reset(self, sample_rate, max_block_size);
429 }
430
431 fn process(
432 &mut self,
433 buffer: &mut AudioBuffer<$sample>,
434 events: &EventList,
435 context: &mut ProcessContext,
436 ) -> ProcessStatus {
437 // FTZ/DAZ (or FZ on AArch64) for the duration of
438 // the user's process body. Denormals on filter
439 // feedback paths stall the core; the guard pays
440 // ~two MXCSR writes per block to avoid that.
441 let _denormal_guard = DenormalGuard::new();
442 <Self as $leaf>::process(self, buffer, events, context)
443 }
444
445 fn save_state(&self) -> Vec<u8> {
446 <Self as $leaf>::save_state(self)
447 }
448
449 fn snapshot_into(&self, buf: &mut Vec<u8>) -> bool {
450 <Self as $leaf>::snapshot_into(self, buf)
451 }
452
453 fn load_state(&mut self, data: &[u8]) -> Result<(), StateLoadError> {
454 <Self as $leaf>::load_state(self, data)
455 }
456
457 fn state_changed(&mut self) {
458 <Self as $leaf>::state_changed(self);
459 }
460
461 fn migrate_state(foreign: &ForeignState) -> Option<MigratedState>
462 where
463 Self: Sized,
464 {
465 <Self as $leaf>::migrate_state(foreign)
466 }
467
468 fn latency(&self) -> u32 {
469 <Self as $leaf>::latency(self)
470 }
471
472 fn tail(&self) -> u32 {
473 <Self as $leaf>::tail(self)
474 }
475 }
476
477 impl<T: $leaf> PluginEditor<$sample> for T {
478 type Params = <T as $leaf>::Params;
479
480 fn editor(params: std::sync::Arc<Self::Params>) -> Box<dyn Editor> {
481 <Self as $leaf>::editor(params)
482 }
483 }
484 };
485}
486
487plugin_logic_bridge!(PluginLogic, f32);
488plugin_logic_bridge!(PluginLogic64, f64);
489
490// ---------------------------------------------------------------------------
491// Default hit test - referenced by leaf macro expansions
492// ---------------------------------------------------------------------------
493
494/// Default hit test: circular for knobs, rectangular for everything
495/// else, skip meters. Used by the leaf traits' `hit_test` defaults.
496#[must_use]
497pub fn default_hit_test(widgets: &[WidgetRegion], x: f32, y: f32) -> Option<usize> {
498 for (i, w) in widgets.iter().enumerate() {
499 if w.widget_type == WidgetType::Meter {
500 continue;
501 }
502 if w.widget_type == WidgetType::Knob {
503 let dx = x - w.cx;
504 let dy = y - w.cy;
505 if dx * dx + dy * dy <= w.radius * w.radius {
506 return Some(i);
507 }
508 } else if x >= w.x && x <= w.x + w.w && y >= w.y && y <= w.y + w.h {
509 return Some(i);
510 }
511 }
512 None
513}