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//! Plus one layer of sugar: [`PurePluginLogic`] / [`PurePluginLogic64`]
23//! for plugins with no DSP state, blanket-implemented into the
24//! matching leaf so everything downstream sees a normal `PluginLogic`
25//! with `DspState = ()`.
26//!
27//! The two leaf traits are stamped from one
28//! `plugin_logic_leaf_trait!` `macro_rules!` definition (further
29//! down this file) so their method surfaces stay in lock-step. Each leaf
30//! gets a blanket impl that forwards every method to
31//! `PluginLogicCore<S>` with the matching `S`. Wrappers
32//! (`StaticShell`, `HotShell`, the format crates) bind on
33//! `PluginLogicCore<S>` and don't care which leaf the user impl'd.
34//!
35//! ## What this buys
36//!
37//! Plugin authors writing `impl PluginLogic for Synth { ... }`
38//! never name a precision. The `truce::prelude64` re-export aliases
39//! `PluginLogic64` as `PluginLogic` in the user's scope, so the
40//! same impl header reads the same regardless of which prelude is
41//! in use. The `<S>` token that used to live on the impl header is
42//! gone - the prelude carries the precision choice.
43
44use truce_core::buffer::AudioBuffer;
45use truce_core::bus::BusLayout;
46use truce_core::config::AudioConfig;
47use truce_core::denormal::DenormalGuard;
48use truce_core::editor::Editor;
49use truce_core::events::EventList;
50use truce_core::process::{ProcessContext, ProcessStatus};
51use truce_core::state::{ForeignState, MigratedState, StateLoadError};
52use truce_gui_types::interaction::WidgetRegion;
53use truce_gui_types::widgets::WidgetType;
54use truce_params::sample::Sample;
55
56// ---------------------------------------------------------------------------
57// PluginLogicCore - generic trait, what format wrappers consume
58// ---------------------------------------------------------------------------
59
60/// Wrapper-facing plugin trait, generic over the audio sample type.
61///
62/// Format wrappers (`StaticShell`, `HotShell`, CLAP / VST3 / etc.)
63/// bind on `PluginLogicCore<S>`. Plugin authors don't implement this
64/// directly - they implement [`PluginLogic`] (`f32`) or
65/// [`PluginLogic64`] (`f64`), and the blanket impls below route them
66/// into `PluginLogicCore`.
67///
68/// Method docs live on the leaf traits ([`PluginLogic`] /
69/// [`PluginLogic64`]); the shape mirrors them exactly.
70pub trait PluginLogicCore<S: Sample = f32>: 'static {
71 /// The plugin's parameter struct; mirrors the leaf's `Params`.
72 type Params: truce_params::Params;
73 /// The mutable per-block audio state. Owned by the shell, not by
74 /// `Self` (the descriptor). `Send` because the shell moves it across
75 /// threads; `'static` because the shell may outlive any borrow. No
76 /// layout trait is required: the hot-reload shell fingerprints the
77 /// type at load time from its `type_name` / `size_of` / `align_of`.
78 type DspState: Send + 'static;
79
80 /// Whether the hot-reload shell may preserve live DSP state across a
81 /// code-only reload. Default `true` (best-effort layout probe).
82 /// Override to `false` on a state that must always re-init on reload.
83 const PRESERVE_DSP_STATE: bool = true;
84
85 #[must_use]
86 fn supports_in_place() -> bool {
87 false
88 }
89
90 /// Supported audio bus configurations. The host picks one. Default:
91 /// the standard audio effect - stereo and mono - so it appears on
92 /// both track widths. Override for instruments, surround, sidechains.
93 #[must_use]
94 fn bus_layouts() -> Vec<BusLayout> {
95 BusLayout::stereo_and_mono()
96 }
97
98 /// Build initial state from params. See [`PluginLogic::init`].
99 fn init(params: &Self::Params, cx: &InitContext) -> Self::DspState;
100
101 fn reset(state: &mut Self::DspState, params: &Self::Params, config: &AudioConfig);
102
103 fn process(
104 state: &mut Self::DspState,
105 params: &Self::Params,
106 buffer: &mut AudioBuffer<S>,
107 events: &EventList,
108 context: &mut ProcessContext,
109 ) -> ProcessStatus;
110
111 fn save_state(state: &Self::DspState) -> Vec<u8> {
112 let _ = state;
113 Vec::new()
114 }
115 /// Lock-free state-save opt-in. See [`PluginLogic::snapshot_into`].
116 fn snapshot_into(state: &Self::DspState, buf: &mut Vec<u8>) -> bool {
117 let _ = (state, buf);
118 false
119 }
120 /// Snapshot generation token. See [`PluginLogic::snapshot_version`].
121 fn snapshot_version(state: &Self::DspState) -> Option<u64> {
122 let _ = state;
123 None
124 }
125 /// Inline snapshot buffer pre-warm hint. See
126 /// [`PluginLogic::snapshot_prealloc_hint`].
127 #[must_use]
128 fn snapshot_prealloc_hint() -> usize {
129 truce_core::snapshot::SNAPSHOT_PREALLOC
130 }
131 /// Restore plugin-specific state. See [`PluginLogic::load_state`].
132 ///
133 /// # Errors
134 ///
135 /// Forwards whatever the user impl returns - typically a malformed
136 /// blob error decoded by `bincode` / `serde` / similar.
137 fn load_state(state: &mut Self::DspState, data: &[u8]) -> Result<(), StateLoadError> {
138 let _ = (state, data);
139 Ok(())
140 }
141 /// Translate foreign state into truce shape. See
142 /// [`PluginLogic::migrate_state`].
143 #[must_use]
144 fn migrate_state(foreign: &ForeignState) -> Option<MigratedState> {
145 let _ = foreign;
146 None
147 }
148 fn state_changed(state: &mut Self::DspState, params: &Self::Params) {
149 let _ = (state, params);
150 }
151 fn latency(state: &Self::DspState) -> u32 {
152 let _ = state;
153 0
154 }
155 fn tail(state: &Self::DspState) -> u32 {
156 let _ = state;
157 0
158 }
159}
160
161/// Precision-keyed editor factory, bridged from the leaf traits.
162///
163/// `plugin!` / `export_static!` / `export_plugin!` build the editor from
164/// the concrete logic type without naming which leaf trait
165/// ([`PluginLogic`] vs [`PluginLogic64`]) it implements. Keyed on `S`
166/// only so the two per-leaf blanket impls don't overlap - the editor and
167/// param store are precision-independent.
168///
169/// This lives off [`PluginLogicCore`] on purpose: it carries an
170/// associated `Params` type and a receiverless `editor`, either of which
171/// would make `PluginLogicCore` non-object-safe and break the
172/// hot-reload loader's type-erased `Box<dyn PluginLogicCore<S>>`. Only
173/// concrete code (the shells' macros) ever names it, never `dyn`.
174pub trait PluginEditor<S: Sample> {
175 /// The plugin's parameter struct; mirrors the leaf's `Params`.
176 type Params: truce_params::Params;
177
178 /// Build the editor from the lock-free param store. Receiverless, so
179 /// the wrapper constructs it while the audio thread runs, without the
180 /// plugin lock.
181 fn editor(params: std::sync::Arc<Self::Params>) -> Box<dyn Editor>;
182}
183
184// ---------------------------------------------------------------------------
185// Leaf traits - what plugin authors implement
186// ---------------------------------------------------------------------------
187
188/// Define a sample-pinned leaf trait. Two invocations:
189/// `PluginLogic` (f32) and [`PluginLogic64`] (f64). The trait
190/// definition has to be a macro because we want the two trait
191/// surfaces to stay in exact lock-step - adding a new method means
192/// updating one place, not three (the macro, plus two trait
193/// declarations).
194///
195/// Doc-hidden because it's a single-purpose internal macro, not an
196/// API users should reach for.
197#[doc(hidden)]
198#[macro_export]
199macro_rules! plugin_logic_leaf_trait {
200 ($(#[$attr:meta])* $vis:vis trait $name:ident<sample = $sample:ty>) => {
201 $(#[$attr])*
202 $vis trait $name: 'static {
203 /// The plugin's parameter struct (`#[derive(Params)]`).
204 /// Shared, immutable during a block - it arrives by
205 /// reference every call from the shell, which owns the
206 /// `Arc`. Never stored in [`Self::DspState`].
207 type Params: $crate::__plugin_logic_deps::Params;
208
209 /// The mutable per-block audio state - filter memory, voice
210 /// buffers, phase accumulators. A plain struct, distinct from
211 /// the descriptor `Self` (except for the small-effect
212 /// `type DspState = Self` shape). A plugin with no audio state
213 /// implements the stateless leaf trait instead of this one and
214 /// never names a `DspState`. Owned by the shell, so it can
215 /// outlive a code swap.
216 /// `Default` is how the state is born: the default
217 /// [`Self::init`] returns `Self::DspState::default()`, so most
218 /// plugins never write `init` - they `#[derive(Default)]` (or
219 /// hand-write `Default` when a fresh state has non-zero fields)
220 /// and override `init` only when construction needs params.
221 /// No layout trait is required - the hot-reload shell
222 /// fingerprints the type at load time from its `type_name` /
223 /// `size_of` / `align_of`.
224 type DspState: ::core::default::Default + Send + 'static;
225
226 /// Whether the hot-reload shell may preserve live DSP state
227 /// across a code-only reload. Default `true`: the shell keeps
228 /// the state when a best-effort layout probe (`type_name` +
229 /// `size_of` + `align_of`) matches, so a reverb tail survives
230 /// an edit-and-reload, and re-inits when it differs. Set to
231 /// `false` on a state that must always re-init on reload.
232 const PRESERVE_DSP_STATE: bool = true;
233
234 /// Opt into zero-copy in-place I/O. When this returns `true`,
235 /// the format wrapper skips its safety memcpy on host-aliased
236 /// buffers and hands the plugin the raw shared memory through
237 /// `AudioBuffer::in_out_mut(ch)`. The plugin must check
238 /// `AudioBuffer::is_in_place(ch)` per channel before reading
239 /// `input(ch)`.
240 ///
241 /// Default `false`: the wrapper copies aliased inputs into
242 /// scratch so `input(ch)` and `output(ch)` are always
243 /// disjoint. Costs one memcpy per aliased channel per block.
244 #[must_use]
245 fn supports_in_place() -> bool {
246 false
247 }
248
249 /// Supported audio bus configurations. The host picks one;
250 /// the others are rejected at bus-config time before
251 /// `process` is ever called. Default: the standard audio
252 /// effect - stereo and mono - so it shows on both track widths.
253 #[must_use]
254 fn bus_layouts() -> Vec<$crate::__plugin_logic_deps::BusLayout> {
255 $crate::__plugin_logic_deps::BusLayout::stereo_and_mono()
256 }
257
258 /// Build the initial audio state from params. Replaces the
259 /// old `new` constructor: the descriptor is stateless, so
260 /// state is born here and owned by the shell. Not real-time
261 /// safe - allocate freely.
262 ///
263 /// Default: `Self::DspState::default()`. Override only when
264 /// construction genuinely needs to read params; a fixed
265 /// initial state belongs in the state type's `Default` impl
266 /// instead.
267 fn init(
268 params: &Self::Params,
269 cx: &$crate::__plugin_logic_deps::InitContext,
270 ) -> Self::DspState {
271 let _ = (params, cx);
272 ::core::default::Default::default()
273 }
274
275 /// Reset for a new sample rate / block size / processing
276 /// mode. Clear `state`'s filters / delay lines; read
277 /// `config.process_mode` to size buffers for an offline
278 /// render (allocation belongs here, off the audio thread) -
279 /// see [`AudioConfig`](truce_core::config::AudioConfig).
280 ///
281 /// Params plumbing is NOT your job: the shell calls
282 /// `params.set_sample_rate(config.sample_rate)` and
283 /// `params.snap_smoothers()` before invoking this, so the
284 /// body only handles state the plugin itself owns. Default:
285 /// no-op, right for a stateless plugin (`DspState = ()`).
286 fn reset(
287 state: &mut Self::DspState,
288 params: &Self::Params,
289 config: &$crate::__plugin_logic_deps::AudioConfig,
290 ) {
291 let _ = (state, params, config);
292 }
293
294 /// Process one block of audio. Real-time - no allocations,
295 /// locks, or I/O. `state` is exclusively owned this block;
296 /// `params` is shared and immutable.
297 fn process(
298 state: &mut Self::DspState,
299 params: &Self::Params,
300 buffer: &mut $crate::__plugin_logic_deps::AudioBuffer<$sample>,
301 events: &$crate::__plugin_logic_deps::EventList,
302 context: &mut $crate::__plugin_logic_deps::ProcessContext,
303 ) -> $crate::__plugin_logic_deps::ProcessStatus;
304
305 /// Serialize plugin-specific state (DSP state, not params -
306 /// those are saved automatically).
307 ///
308 /// **Prefer [`Self::snapshot_into`].** That is the
309 /// real-time-safe path and the one CLAP / VST3 / AU actually
310 /// persist from - [`Self::snapshot_into`]'s default delegates
311 /// here, so overriding only `save_state` still round-trips. The
312 /// catch: it then runs on the **audio thread** each changed
313 /// block, so keep it cheap (copy bytes out; no compute or
314 /// compress) and reach for `snapshot_into` (or the off-thread
315 /// `InitContext::snapshot_publisher()` for MB-scale state) for
316 /// anything non-trivial. Default: empty (no extra state).
317 fn save_state(state: &Self::DspState) -> Vec<u8> {
318 let _ = state;
319 Vec::new()
320 }
321
322 /// Opt into lock-free state save. `buf` arrives **cleared**,
323 /// with its capacity retained across calls so a steady state
324 /// is allocation-free; fill it with the same bytes
325 /// [`Self::save_state`] would produce (append freely - it is
326 /// never carried over from the previous block).
327 ///
328 /// The return value is a *static capability*, not a
329 /// per-block flag: `true` means "this plugin publishes
330 /// snapshots", `false` means "it never does". Once you return
331 /// `true` you must return `true` for the plugin's whole
332 /// lifetime - if the custom state empties out, return `true`
333 /// with `buf` left empty (an empty blob), don't return `false`.
334 /// The shell latches the opt-in on the first published block; a
335 /// later `false` is a contract violation that would otherwise
336 /// leave the host reading a stale snapshot forever.
337 ///
338 /// Called on the **audio thread** after each process block
339 /// whose [`Self::snapshot_version`] changed, under the same
340 /// real-time rules as `process` - bounded, no unbounded
341 /// allocation. The wrapper publishes the result into a
342 /// lock-free slot the host reads without ever taking the
343 /// plugin lock, so saving state while audio runs never stalls
344 /// the audio thread.
345 ///
346 /// **Default.** Delegates to [`Self::save_state`], so a plugin
347 /// that overrides only the legacy `save_state` still publishes
348 /// through this slot - at the cost of running `save_state` on
349 /// the audio thread. A plugin overriding neither publishes
350 /// nothing (its empty `save_state`).
351 ///
352 /// **Size regime.** This inline lane copies the whole buffer
353 /// on every *changed* block, so it is for **KB-scale** state (a
354 /// file path, a view mode, a small analysis buffer). For
355 /// **MB-scale** state (a sampler's audio, big wavetables) copying
356 /// on the audio thread is itself a hazard - publish that off the
357 /// audio thread instead via
358 /// `InitContext::snapshot_publisher()` (a background-serialized,
359 /// pointer-swapped buffer) and leave this at the default.
360 fn snapshot_into(state: &Self::DspState, buf: &mut Vec<u8>) -> bool {
361 let bytes = Self::save_state(state);
362 if bytes.is_empty() {
363 false
364 } else {
365 buf.extend_from_slice(&bytes);
366 true
367 }
368 }
369
370 /// Generation token for the state [`Self::snapshot_into`]
371 /// serializes. Bump it (any monotonic change is enough -
372 /// a counter you increment when custom state mutates) so the
373 /// shell re-serializes **only when it changes**: an unchanged
374 /// block then pays O(1) - a single integer read - regardless
375 /// of snapshot size, instead of re-copying the whole buffer
376 /// every block.
377 ///
378 /// Read on the audio thread each block, so keep it trivial
379 /// (read a field; no work). `None` (the default) means "no
380 /// version tracking - re-serialize every block", which is fine
381 /// for tiny state but pays the full copy each block for larger
382 /// state. Return `Some(token)` to opt into gating.
383 fn snapshot_version(state: &Self::DspState) -> Option<u64> {
384 let _ = state;
385 None
386 }
387
388 /// Bytes to pre-warm the inline snapshot buffer to, off the
389 /// audio thread, so the first [`Self::snapshot_into`] publish of
390 /// up to this many bytes doesn't reallocate on the audio thread.
391 /// Default 256. Raise it to your typical inline snapshot size;
392 /// genuinely large state should use the off-thread publisher
393 /// instead (which never touches this buffer).
394 #[must_use]
395 fn snapshot_prealloc_hint() -> usize {
396 $crate::__plugin_logic_deps::SNAPSHOT_PREALLOC
397 }
398
399 /// Restore plugin-specific state into `state`.
400 ///
401 /// Runs on the audio thread between blocks, with the same
402 /// exclusive access `process()` has - writing any field
403 /// is safe.
404 ///
405 /// # Errors
406 ///
407 /// Return `Err(StateLoadError)` when the blob is malformed
408 /// or otherwise can't be interpreted - the format wrapper
409 /// logs the failure (and on hosts that support it, surfaces
410 /// it to the DAW).
411 fn load_state(
412 state: &mut Self::DspState,
413 data: &[u8],
414 ) -> Result<(), $crate::__plugin_logic_deps::StateLoadError> {
415 let _ = (state, data);
416 Ok(())
417 }
418
419 /// Called on the audio thread immediately after
420 /// [`Self::load_state`] returns. Invalidate or recompute any
421 /// caches in `state` that the next `process()` reads. Default:
422 /// no-op.
423 fn state_changed(state: &mut Self::DspState, params: &Self::Params) {
424 let _ = (state, params);
425 }
426
427 /// Translate foreign state - a previous framework's blob,
428 /// or a truce envelope saved under a different plugin id -
429 /// into truce params + extra, so a plugin ported to truce
430 /// keeps its users' old sessions and presets. Runs on the
431 /// host thread; receiverless so it can't touch (or alias)
432 /// the live instance. Return `None` for bytes you don't
433 /// recognize - the wrapper then reports load failure to
434 /// the host, exactly as if this hook didn't exist.
435 ///
436 /// One-shot by construction: the next save writes a normal
437 /// truce envelope, so this never becomes a permanent
438 /// dual-format reader. Keyed formats (AU / LV2 / AAX) only
439 /// see foreign bytes when `truce.toml` declares the legacy
440 /// keys to probe (`[plugin.legacy_state]`).
441 #[must_use]
442 fn migrate_state(
443 foreign: &$crate::__plugin_logic_deps::ForeignState,
444 ) -> Option<$crate::__plugin_logic_deps::MigratedState> {
445 let _ = foreign;
446 None
447 }
448
449 /// Report latency in samples for plugin delay compensation.
450 /// May change at runtime - return a new value and the host is
451 /// notified (see the wrapper latency-change path).
452 fn latency(state: &Self::DspState) -> u32 {
453 let _ = state;
454 0
455 }
456
457 /// Report tail time in samples (audio produced after input
458 /// stops - reverbs, delays). `u32::MAX` for infinite tail.
459 fn tail(state: &Self::DspState) -> u32 {
460 let _ = state;
461 0
462 }
463
464 // ---- GUI ----
465
466 /// Construct the editor for this plugin. Required.
467 ///
468 /// There is no auto-fallback - every plugin explicitly
469 /// names which renderer it wants. For the built-in
470 /// widget layout, call
471 /// `truce_gui::default_editor(params, layout)`; for
472 /// custom renderers, construct an `EguiEditor` /
473 /// `IcedEditor` / `SlintEditor` / hand-rolled `Editor`
474 /// here. The choice of renderer crate the plugin's
475 /// `Cargo.toml` pulls IS the choice of editor.
476 ///
477 /// An associated function, not a method: it receives the
478 /// lock-free `Arc<Self::Params>` store the wrapper already
479 /// holds, so the host can open the editor while audio is
480 /// running without ever taking the plugin lock. Editors bind
481 /// only to the param store (plus meters / transport, all
482 /// lock-free); custom DSP state is read at runtime through
483 /// the editor bridge, not at construction.
484 fn editor(
485 params: ::std::sync::Arc<Self::Params>,
486 ) -> Box<dyn $crate::__plugin_logic_deps::Editor>;
487 }
488 };
489}
490
491// Re-export the dependencies the leaf-trait macro substitutes by path,
492// under one `pub` doc-hidden module so user crates that invoke the
493// macro don't need to import each truce-core type by hand.
494#[doc(hidden)]
495pub mod __plugin_logic_deps {
496 pub use truce_core::buffer::AudioBuffer;
497 pub use truce_core::bus::BusLayout;
498 pub use truce_core::config::AudioConfig;
499 pub use truce_core::dsp_state::{NO_PRESERVE, layout_fingerprint};
500 pub use truce_core::editor::Editor;
501 pub use truce_core::events::EventList;
502 pub use truce_core::process::{ProcessContext, ProcessStatus};
503 pub use truce_core::snapshot::SNAPSHOT_PREALLOC;
504 pub use truce_core::state::{ForeignState, MigratedState, StateLoadError};
505 pub use truce_core::tasks::{InitContext, TaskSpawner};
506 pub use truce_params::Params;
507}
508
509plugin_logic_leaf_trait! {
510 /// The `f32`-buffer user-facing plugin trait.
511 ///
512 /// Plugin authors implement this in a single `impl` block when
513 /// their audio path is `f32` end-to-end (the default - matches
514 /// the host wire format for nearly all DAWs and formats).
515 /// `truce::prelude` and `truce::prelude32` re-export this name
516 /// directly; `truce::prelude64m` does too (the `m` mixed-precision
517 /// prelude keeps the audio buffer at `f32` and only switches the
518 /// `param.read()` precision).
519 ///
520 /// Required: [`Self::process`], [`Self::editor`]. Everything else
521 /// has a default: `init` builds `Self::DspState::default()` unless
522 /// construction needs params, and `reset` is a no-op. The editor is
523 /// constructed explicitly - layout-only plugins typically call
524 /// `truce_gui::default_editor(params, layout())` (where `layout()`
525 /// is a plain inherent method on the plugin struct, not part of the
526 /// trait). A plugin with no DSP state at all should implement
527 /// [`PurePluginLogic`] instead and skip the state plumbing entirely.
528 ///
529 /// ## Params vs. DSP state
530 ///
531 /// The type you implement this on is a stateless descriptor; the
532 /// data lives in two places, and the method signatures reflect the
533 /// split:
534 ///
535 /// - **Params** (`type Params`) - the user-facing values in your
536 /// `#[derive(Params)]` struct, held as `Arc<Self::Params>`.
537 /// Atomic-backed and `Sync`, shared lock-free with the host and
538 /// the editor. Arrives read-only as `&Self::Params`.
539 /// - **DSP state** (`type DspState`) - filter memory, phase
540 /// accumulators, voice buffers, delay lines. Plain and
541 /// non-atomic, mutated every sample, exclusive to the audio
542 /// thread. Owned by the shell, passed `&mut` to the methods that
543 /// mutate it (`process` / `reset` / `load_state`) and `&` to the
544 /// ones that read it (`save_state` / `snapshot_into`).
545 ///
546 /// `editor` takes neither - it is an associated function over the
547 /// param store, because a GUI is a *view* that binds only params
548 /// (plus lock-free meters / transport) and never touches DSP state,
549 /// so it can be built without the plugin lock. DSP state can't move
550 /// into params: making per-sample filter memory atomic-shared would
551 /// put a synchronized access on the hottest path, and it isn't a
552 /// "parameter" anyway.
553 pub trait PluginLogic<sample = f32>
554}
555
556plugin_logic_leaf_trait! {
557 /// The `f64`-buffer user-facing plugin trait. Same surface as
558 /// [`PluginLogic`] but with the audio buffer pinned to `f64`.
559 ///
560 /// Plugin authors don't usually name this directly - `truce::prelude64`
561 /// re-exports it as `PluginLogic`, so the impl header reads the
562 /// same regardless of which precision the prelude chose. Pick
563 /// `truce::prelude64` (and thus this leaf) when the DSP path runs
564 /// in `f64` end-to-end and the wrapper-boundary widen/narrow
565 /// memcpy is worth the cleaner DSP code.
566 pub trait PluginLogic64<sample = f64>
567}
568
569// ---------------------------------------------------------------------------
570// Pure leaf traits - stateless sugar over PluginLogic / PluginLogic64
571// ---------------------------------------------------------------------------
572
573/// Define a sample-pinned pure (stateless) leaf trait plus its blanket
574/// impl into the matching stateful leaf. Two invocations: `PurePluginLogic`
575/// over [`PluginLogic`] and [`PurePluginLogic64`] over [`PluginLogic64`].
576/// A macro for the same reason as [`plugin_logic_leaf_trait!`]: the two
577/// surfaces stay in lock-step by construction.
578macro_rules! pure_plugin_leaf_trait {
579 ($(#[$attr:meta])* $vis:vis trait $name:ident: $leaf:ident<sample = $sample:ty>) => {
580 $(#[$attr])*
581 $vis trait $name: 'static {
582 /// The plugin's parameter struct (`#[derive(Params)]`).
583 /// Shared, immutable during a block - it arrives by
584 /// reference every call from the shell, which owns the
585 /// `Arc`.
586 type Params: crate::__plugin_logic_deps::Params;
587
588 /// Opt into zero-copy in-place I/O. Same contract as the
589 /// stateful leaf's `supports_in_place`.
590 #[must_use]
591 fn supports_in_place() -> bool {
592 false
593 }
594
595 /// Supported audio bus configurations. Same contract as the
596 /// stateful leaf's `bus_layouts`. Default: the standard audio
597 /// effect - stereo and mono.
598 #[must_use]
599 fn bus_layouts() -> Vec<crate::__plugin_logic_deps::BusLayout> {
600 crate::__plugin_logic_deps::BusLayout::stereo_and_mono()
601 }
602
603 /// Process one block of audio as a pure function of params
604 /// and input. Same real-time contract as the stateful
605 /// leaf's `process`, minus the state argument.
606 fn process(
607 params: &Self::Params,
608 buffer: &mut crate::__plugin_logic_deps::AudioBuffer<$sample>,
609 events: &crate::__plugin_logic_deps::EventList,
610 context: &mut crate::__plugin_logic_deps::ProcessContext,
611 ) -> crate::__plugin_logic_deps::ProcessStatus;
612
613 /// Translate foreign state into truce shape. Same contract
614 /// as the stateful leaf's `migrate_state` - a stateless
615 /// plugin may still inherit params from a previous
616 /// framework's blob.
617 #[must_use]
618 fn migrate_state(
619 foreign: &crate::__plugin_logic_deps::ForeignState,
620 ) -> Option<crate::__plugin_logic_deps::MigratedState> {
621 let _ = foreign;
622 None
623 }
624
625 /// Construct the editor for this plugin. Required. Same
626 /// contract as the stateful leaf's `editor`.
627 fn editor(
628 params: ::std::sync::Arc<Self::Params>,
629 ) -> Box<dyn crate::__plugin_logic_deps::Editor>;
630 }
631
632 // The blanket that makes the sugar real: a pure plugin IS a
633 // stateful plugin with `DspState = ()`. Everything downstream
634 // (`PluginLogicCore`, `PluginEditor`, the shells, `plugin!`)
635 // binds through $leaf and never learns the difference. Methods
636 // not forwarded here (`init`, `reset`, `save_state`, `latency`,
637 // `tail`, ...) keep their $leaf defaults, which are exactly the
638 // stateless behaviors.
639 impl<T: $name> $leaf for T {
640 type Params = <T as $name>::Params;
641 type DspState = ();
642
643 fn supports_in_place() -> bool {
644 <T as $name>::supports_in_place()
645 }
646
647 fn bus_layouts() -> Vec<crate::__plugin_logic_deps::BusLayout> {
648 <T as $name>::bus_layouts()
649 }
650
651 fn process(
652 _state: &mut (),
653 params: &Self::Params,
654 buffer: &mut crate::__plugin_logic_deps::AudioBuffer<$sample>,
655 events: &crate::__plugin_logic_deps::EventList,
656 context: &mut crate::__plugin_logic_deps::ProcessContext,
657 ) -> crate::__plugin_logic_deps::ProcessStatus {
658 <T as $name>::process(params, buffer, events, context)
659 }
660
661 fn migrate_state(
662 foreign: &crate::__plugin_logic_deps::ForeignState,
663 ) -> Option<crate::__plugin_logic_deps::MigratedState> {
664 <T as $name>::migrate_state(foreign)
665 }
666
667 fn editor(
668 params: ::std::sync::Arc<Self::Params>,
669 ) -> Box<dyn crate::__plugin_logic_deps::Editor> {
670 <T as $name>::editor(params)
671 }
672 }
673 };
674}
675
676pure_plugin_leaf_trait! {
677 /// The stateless `f32` plugin trait: [`PluginLogic`] minus every
678 /// state-shaped item. For a pure parameter-driven effect - one
679 /// whose `process` is a function of params and input only - this
680 /// removes the `type DspState = ()` / `init` / `_state: &mut ()`
681 /// plumbing entirely:
682 ///
683 /// ```ignore
684 /// pub struct Gain;
685 ///
686 /// impl PurePluginLogic for Gain {
687 /// type Params = GainParams;
688 /// fn process(params: &GainParams, buffer: &mut AudioBuffer, events: &EventList, ctx: &mut ProcessContext) -> ProcessStatus {
689 /// /* ... */
690 /// }
691 /// fn editor(params: Arc<GainParams>) -> Box<dyn Editor> { /* ... */ }
692 /// }
693 /// ```
694 ///
695 /// A blanket impl makes every `PurePluginLogic` a [`PluginLogic`] with
696 /// `DspState = ()`, so `truce::plugin!` and every shell consume it
697 /// unchanged - and implementing both traits for one type is
698 /// correctly rejected as conflicting. When the plugin grows DSP
699 /// state, switch the impl header to [`PluginLogic`] and add the
700 /// state type and arguments.
701 ///
702 /// Required: [`Self::process`], [`Self::editor`]. Optional:
703 /// [`Self::bus_layouts`], [`Self::supports_in_place`],
704 /// [`Self::migrate_state`]. Anything state-shaped (`reset`,
705 /// `save_state`, `latency`, `tail`, ...) needs state to act on -
706 /// implement [`PluginLogic`] directly if you need those.
707 pub trait PurePluginLogic: PluginLogic<sample = f32>
708}
709
710pure_plugin_leaf_trait! {
711 /// The stateless `f64` plugin trait. Same surface as
712 /// [`PurePluginLogic`] but with the audio buffer pinned to `f64`;
713 /// blanket-implements [`PluginLogic64`]. `truce::prelude64`
714 /// re-exports it as `PurePluginLogic`, so the impl header reads the
715 /// same regardless of precision.
716 pub trait PurePluginLogic64: PluginLogic64<sample = f64>
717}
718
719// ---------------------------------------------------------------------------
720// Background tasks - opt-in managed off-thread work
721// ---------------------------------------------------------------------------
722
723pub use crate::__plugin_logic_deps::{InitContext, TaskSpawner};
724
725/// Opt-in managed background work. Each **task type** implements this to
726/// declare its params, its concurrency mode, and the handler the framework
727/// runs on a shared background-thread pool; a plugin lists one or more task
728/// types with the `tasks:` key on `truce::plugin!` (`tasks: [Rebuild,
729/// Analyze]`). Every task type gets its own inbound queue and mode, so a
730/// serialized lane and a concurrent lane coexist in one plugin. Nothing
731/// changes for a plugin that declares no tasks.
732///
733/// `run` executes off the audio thread and reaches shared state through
734/// `params` (its `#[skip]` channels / atomics), exactly like the editor:
735/// it must never touch `DspState`, which is audio-thread-exclusive.
736/// Feedback to the audio thread stays the plugin's job through those
737/// `#[skip]` channels.
738///
739/// Keep handlers short and non-blocking. The pool is shared by every
740/// truce plugin in the host and small (`available_parallelism() - 1`
741/// threads, as few as one), so a handler that blocks on I/O (reading a
742/// sample off disk) or waits on a lock stalls background work for *every
743/// other instance too*, not just its own. Allocation and CPU-bound bursts
744/// are fine - that is what the pool is for. For work that genuinely blocks
745/// or runs long, give the plugin its own thread with
746/// `AudioTap::spawn_worker` rather than the shared pool.
747///
748/// Schedule tasks with `ctx.tasks::<Rebuild>()` from `process` (wait-free),
749/// the editor's `PluginContext`, or the `InitContext` passed to `init` -
750/// the type parameter selects the lane.
751///
752/// ```ignore
753/// struct Rebuild { sample_rate: f64, time_s: f32 }
754/// impl BackgroundTask for Rebuild {
755/// type Params = ReverbParams;
756/// const SERIALIZED: bool = true; // non-reentrant graph build
757/// fn run(self, params: &ReverbParams) {
758/// let graph = build_graph(self.sample_rate, self.time_s);
759/// let _ = params.ready.force_push(graph); // #[skip] handoff
760/// }
761/// }
762/// // truce::plugin! { logic, params, tasks: [Rebuild] }
763/// ```
764pub trait BackgroundTask: Send + 'static {
765 /// The plugin's parameter struct; must match the leaf trait's
766 /// `type Params`. (`Send`/`'static` on the task type itself: the pool
767 /// moves it across threads and the worker outlives any block.)
768 type Params: crate::__plugin_logic_deps::Params;
769 /// Run this lane's handler one at a time for a given instance
770 /// ("one-slot" mode).
771 ///
772 /// Default `false`: the pool is shared and lock-free, so a burst that
773 /// re-arms a lane while a worker is still draining it can hand a second
774 /// worker the same lane - `run` may run **concurrently with itself**
775 /// for one instance. A handler that only talks to the audio thread
776 /// through lock-free channels / atomics (the reverb example's MPMC
777 /// handoff) is fine that way and keeps maximum throughput.
778 ///
779 /// Set `true` when the handler read-modify-writes shared mutable state
780 /// that isn't safe to enter re-entrantly (a scratch buffer, a
781 /// non-atomic cache): the pool then serializes this lane's drains so at
782 /// most one `run` for this instance runs at a time, without the author
783 /// needing a `try_lock` guard. Tasks are never dropped or reordered;
784 /// serialization only bounds concurrency, so keep the handler short
785 /// (a long serialized handler delays this lane's later tasks). The mode
786 /// is per lane, so a concurrent lane in the same plugin is unaffected.
787 const SERIALIZED: bool = false;
788 /// Run one task on the pool. See the trait docs for the contract,
789 /// including the concurrency note on [`Self::SERIALIZED`].
790 fn run(self, params: &Self::Params);
791}
792
793// ---------------------------------------------------------------------------
794// Bridges - each leaf forwards every method to PluginLogicCore<S>
795// ---------------------------------------------------------------------------
796
797/// Define a blanket `impl<T: $leaf> PluginLogicCore<$sample> for T`
798/// that forwards every trait method to `<T as $leaf>::method(...)`.
799/// One source-of-truth for both `(PluginLogic, f32)` and
800/// `(PluginLogic64, f64)` bridges.
801macro_rules! plugin_logic_bridge {
802 ($leaf:ident, $sample:ty) => {
803 impl<T: $leaf> PluginLogicCore<$sample> for T {
804 type Params = <T as $leaf>::Params;
805 type DspState = <T as $leaf>::DspState;
806
807 const PRESERVE_DSP_STATE: bool = <T as $leaf>::PRESERVE_DSP_STATE;
808
809 fn supports_in_place() -> bool {
810 <Self as $leaf>::supports_in_place()
811 }
812
813 fn bus_layouts() -> Vec<BusLayout> {
814 <Self as $leaf>::bus_layouts()
815 }
816
817 fn init(
818 params: &Self::Params,
819 cx: &crate::__plugin_logic_deps::InitContext,
820 ) -> Self::DspState {
821 <Self as $leaf>::init(params, cx)
822 }
823
824 fn reset(state: &mut Self::DspState, params: &Self::Params, config: &AudioConfig) {
825 <Self as $leaf>::reset(state, params, config);
826 }
827
828 fn process(
829 state: &mut Self::DspState,
830 params: &Self::Params,
831 buffer: &mut AudioBuffer<$sample>,
832 events: &EventList,
833 context: &mut ProcessContext,
834 ) -> ProcessStatus {
835 // FTZ/DAZ (or FZ on AArch64) for the duration of
836 // the user's process body. Denormals on filter
837 // feedback paths stall the core; the guard pays
838 // ~two MXCSR writes per block to avoid that. Both the
839 // static and hot shells route process through here, so
840 // this brackets exactly the user body in both modes.
841 let _denormal_guard = DenormalGuard::new();
842 <Self as $leaf>::process(state, params, buffer, events, context)
843 }
844
845 fn save_state(state: &Self::DspState) -> Vec<u8> {
846 <Self as $leaf>::save_state(state)
847 }
848
849 fn snapshot_into(state: &Self::DspState, buf: &mut Vec<u8>) -> bool {
850 <Self as $leaf>::snapshot_into(state, buf)
851 }
852
853 fn snapshot_version(state: &Self::DspState) -> Option<u64> {
854 <Self as $leaf>::snapshot_version(state)
855 }
856
857 fn snapshot_prealloc_hint() -> usize {
858 <Self as $leaf>::snapshot_prealloc_hint()
859 }
860
861 fn load_state(state: &mut Self::DspState, data: &[u8]) -> Result<(), StateLoadError> {
862 <Self as $leaf>::load_state(state, data)
863 }
864
865 fn state_changed(state: &mut Self::DspState, params: &Self::Params) {
866 <Self as $leaf>::state_changed(state, params);
867 }
868
869 fn migrate_state(foreign: &ForeignState) -> Option<MigratedState> {
870 <Self as $leaf>::migrate_state(foreign)
871 }
872
873 fn latency(state: &Self::DspState) -> u32 {
874 <Self as $leaf>::latency(state)
875 }
876
877 fn tail(state: &Self::DspState) -> u32 {
878 <Self as $leaf>::tail(state)
879 }
880 }
881
882 impl<T: $leaf> PluginEditor<$sample> for T {
883 type Params = <T as $leaf>::Params;
884
885 fn editor(params: std::sync::Arc<Self::Params>) -> Box<dyn Editor> {
886 <Self as $leaf>::editor(params)
887 }
888 }
889 };
890}
891
892plugin_logic_bridge!(PluginLogic, f32);
893plugin_logic_bridge!(PluginLogic64, f64);
894
895// ---------------------------------------------------------------------------
896// Default hit test - referenced by leaf macro expansions
897// ---------------------------------------------------------------------------
898
899/// Default hit test: circular for knobs, rectangular for everything
900/// else, skip meters. Used by the leaf traits' `hit_test` defaults.
901#[must_use]
902pub fn default_hit_test(widgets: &[WidgetRegion], x: f32, y: f32) -> Option<usize> {
903 for (i, w) in widgets.iter().enumerate() {
904 if w.widget_type == WidgetType::Meter {
905 continue;
906 }
907 if w.widget_type == WidgetType::Knob {
908 let dx = x - w.cx;
909 let dy = y - w.cy;
910 if dx * dx + dy * dy <= w.radius * w.radius {
911 return Some(i);
912 }
913 } else if x >= w.x && x <= w.x + w.w && y >= w.y && y <= w.y + w.h {
914 return Some(i);
915 }
916 }
917 None
918}