truce-plugin 3.1.0

User-facing PluginLogic traits for truce - the plugin author's entry point.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! User-facing plugin traits + internal bridge.
//!
//! This crate is the plugin author's entry point. The single
//! `impl PluginLogic for MyPlugin { ... }` block covers both
//! audio-thread DSP and main-thread GUI, with sample precision
//! routed through the prelude (see `truce::prelude` /
//! `truce::prelude64`).
//!
//! `truce-plugin` depends on `truce-gui-types` (light: layout,
//! render trait, widget regions) - not the full `truce-gui`.
//! Plugin authors who supply a custom editor (egui, iced, slint,
//! raw window handle) end up with `truce-plugin` in their dep
//! tree but not the built-in editor's tiny-skia + baseview +
//! truce-font stack.
//!
//! ## Three traits, one source of truth
//!
//! - [`PluginLogic`]   - what plugin authors implement for `f32`-buffer plugins.
//! - [`PluginLogic64`] - what plugin authors implement for `f64`-buffer plugins.
//! - [`PluginLogicCore`] - generic-over-`S` trait the format wrappers consume.
//!
//! The two leaf traits are stamped from one
//! `plugin_logic_leaf_trait!` `macro_rules!` definition (further
//! down this file) so their method surfaces stay in lock-step. Each leaf
//! gets a blanket impl that forwards every method to
//! `PluginLogicCore<S>` with the matching `S`. Wrappers
//! (`StaticShell`, `HotShell`, the format crates) bind on
//! `PluginLogicCore<S>` and don't care which leaf the user impl'd.
//!
//! ## What this buys
//!
//! Plugin authors writing `impl PluginLogic for Synth { ... }`
//! never name a precision. The `truce::prelude64` re-export aliases
//! `PluginLogic64` as `PluginLogic` in the user's scope, so the
//! same impl header reads the same regardless of which prelude is
//! in use. The `<S>` token that used to live on the impl header is
//! gone - the prelude carries the precision choice.

use truce_core::buffer::AudioBuffer;
use truce_core::bus::BusLayout;
use truce_core::denormal::DenormalGuard;
use truce_core::editor::Editor;
use truce_core::events::EventList;
use truce_core::process::{ProcessContext, ProcessStatus};
use truce_core::state::{ForeignState, MigratedState, StateLoadError};
use truce_gui_types::interaction::WidgetRegion;
use truce_gui_types::widgets::WidgetType;
use truce_params::sample::Sample;

// ---------------------------------------------------------------------------
// PluginLogicCore - generic trait, what format wrappers consume
// ---------------------------------------------------------------------------

/// Wrapper-facing plugin trait, generic over the audio sample type.
///
/// Format wrappers (`StaticShell`, `HotShell`, CLAP / VST3 / etc.)
/// bind on `PluginLogicCore<S>`. Plugin authors don't implement this
/// directly - they implement [`PluginLogic`] (`f32`) or
/// [`PluginLogic64`] (`f64`), and the blanket impls below route them
/// into `PluginLogicCore`.
///
/// Method docs live on the leaf traits ([`PluginLogic`] /
/// [`PluginLogic64`]); the shape mirrors them exactly.
pub trait PluginLogicCore<S: Sample = f32>: Send + 'static {
    #[must_use]
    fn supports_in_place() -> bool
    where
        Self: Sized;

    #[must_use]
    fn bus_layouts() -> Vec<BusLayout>
    where
        Self: Sized;

    fn reset(&mut self, sample_rate: f64, max_block_size: usize);

    fn process(
        &mut self,
        buffer: &mut AudioBuffer<S>,
        events: &EventList,
        context: &mut ProcessContext,
    ) -> ProcessStatus;

    fn save_state(&self) -> Vec<u8>;
    /// Lock-free state-save opt-in. See [`PluginLogic::snapshot_into`].
    /// Called on the audio thread each block when supported; the shell
    /// publishes the result into a `SnapshotSlot` the host reads without
    /// the plugin lock. Default `false`; the leaf bridge overrides it.
    fn snapshot_into(&self, buf: &mut Vec<u8>) -> bool {
        let _ = buf;
        false
    }
    /// Restore plugin-specific state. See [`PluginLogic::load_state`].
    ///
    /// # Errors
    ///
    /// Forwards whatever the user impl returns - typically a malformed
    /// blob error decoded by `bincode` / `serde` / similar.
    fn load_state(&mut self, data: &[u8]) -> Result<(), StateLoadError>;
    /// Translate foreign state into truce shape. See
    /// [`PluginLogic::migrate_state`].
    #[must_use]
    fn migrate_state(foreign: &ForeignState) -> Option<MigratedState>
    where
        Self: Sized;
    fn state_changed(&mut self);
    fn latency(&self) -> u32;
    fn tail(&self) -> u32;
}

/// Precision-keyed editor factory, bridged from the leaf traits.
///
/// `plugin!` / `export_static!` / `export_plugin!` build the editor from
/// the concrete logic type without naming which leaf trait
/// ([`PluginLogic`] vs [`PluginLogic64`]) it implements. Keyed on `S`
/// only so the two per-leaf blanket impls don't overlap - the editor and
/// param store are precision-independent.
///
/// This lives off [`PluginLogicCore`] on purpose: it carries an
/// associated `Params` type and a receiverless `editor`, either of which
/// would make `PluginLogicCore` non-object-safe and break the
/// hot-reload loader's type-erased `Box<dyn PluginLogicCore<S>>`. Only
/// concrete code (the shells' macros) ever names it, never `dyn`.
pub trait PluginEditor<S: Sample> {
    /// The plugin's parameter struct; mirrors the leaf's `Params`.
    type Params: truce_params::Params;

    /// Build the editor from the lock-free param store. Receiverless, so
    /// the wrapper constructs it while the audio thread runs, without the
    /// plugin lock.
    fn editor(params: std::sync::Arc<Self::Params>) -> Box<dyn Editor>;
}

// ---------------------------------------------------------------------------
// Leaf traits - what plugin authors implement
// ---------------------------------------------------------------------------

/// Define a sample-pinned leaf trait. Two invocations:
/// `PluginLogic` (f32) and [`PluginLogic64`] (f64). The trait
/// definition has to be a macro because we want the two trait
/// surfaces to stay in exact lock-step - adding a new method means
/// updating one place, not three (the macro, plus two trait
/// declarations).
///
/// Doc-hidden because it's a single-purpose internal macro, not an
/// API users should reach for.
#[doc(hidden)]
#[macro_export]
macro_rules! plugin_logic_leaf_trait {
    ($(#[$attr:meta])* $vis:vis trait $name:ident<sample = $sample:ty>) => {
        $(#[$attr])*
        $vis trait $name: Send + 'static {
            /// The plugin's parameter struct (`#[derive(Params)]`). Named
            /// here so the editor can be built from an `Arc<Self::Params>`
            /// without borrowing the plugin - see [`Self::editor`].
            type Params: $crate::__plugin_logic_deps::Params;

            /// Opt into zero-copy in-place I/O. When this returns `true`,
            /// the format wrapper skips its safety memcpy on host-aliased
            /// buffers and hands the plugin the raw shared memory through
            /// `AudioBuffer::in_out_mut(ch)`. The plugin must check
            /// `AudioBuffer::is_in_place(ch)` per channel before reading
            /// `input(ch)`.
            ///
            /// Default `false`: the wrapper copies aliased inputs into
            /// scratch so `input(ch)` and `output(ch)` are always
            /// disjoint. Costs one memcpy per aliased channel per block.
            #[must_use]
            fn supports_in_place() -> bool
            where
                Self: Sized,
            {
                false
            }

            /// Supported audio bus configurations. The host picks one;
            /// the others are rejected at bus-config time before
            /// `process` is ever called. Default: stereo in, stereo out.
            #[must_use]
            fn bus_layouts() -> Vec<$crate::__plugin_logic_deps::BusLayout>
            where
                Self: Sized,
            {
                vec![$crate::__plugin_logic_deps::BusLayout::stereo()]
            }

            /// Reset for a new sample rate / block size. Called before
            /// the first `process` and any time the host reconfigures.
            fn reset(&mut self, sample_rate: f64, max_block_size: usize);

            /// Process one block of audio. Real-time - no allocations,
            /// locks, or I/O.
            fn process(
                &mut self,
                buffer: &mut $crate::__plugin_logic_deps::AudioBuffer<$sample>,
                events: &$crate::__plugin_logic_deps::EventList,
                context: &mut $crate::__plugin_logic_deps::ProcessContext,
            ) -> $crate::__plugin_logic_deps::ProcessStatus;

            /// Serialize plugin-specific state (DSP state, not params -
            /// those are saved automatically). Default: delegates to
            /// [`Self::snapshot_into`] (empty when neither is
            /// overridden).
            ///
            /// Runs on a host or GUI thread while the audio thread is
            /// paused at a block boundary (the wrapper's plugin lock),
            /// so reading any field is safe - but an audio block that
            /// arrives mid-save waits for this to return. Keep it
            /// cheap: copy bytes out, don't compute or compress here.
            /// To take this off the plugin lock entirely, override
            /// [`Self::snapshot_into`] instead.
            fn save_state(&self) -> Vec<u8> {
                let mut buf = Vec::new();
                let _ = self.snapshot_into(&mut buf);
                buf
            }

            /// Opt into lock-free state save. `buf` arrives **cleared**,
            /// with its capacity retained across calls so a steady state
            /// is allocation-free; fill it with the same bytes
            /// [`Self::save_state`] would produce (append freely - it is
            /// never carried over from the previous block).
            ///
            /// The return value is a *static capability*, not a
            /// per-block flag: `true` means "this plugin publishes
            /// snapshots", `false` means "it never does" (the default).
            /// Once you return `true` you must return `true` for the
            /// plugin's whole lifetime - if the custom state empties out,
            /// return `true` with `buf` left empty (an empty blob), don't
            /// return `false`. The shell latches the opt-in on the first
            /// published block; a later `false` is a contract violation
            /// that would otherwise leave the host reading a stale
            /// snapshot forever.
            ///
            /// Called on the **audio thread** after each process block,
            /// under the same real-time rules as `process` - bounded, no
            /// unbounded allocation. The wrapper publishes the result
            /// into a lock-free slot the host reads without ever taking
            /// the plugin lock, so saving state while audio runs never
            /// stalls the audio thread. Overriding this is the
            /// preferred way to serialize custom state; the default
            /// [`Self::save_state`] delegates here.
            fn snapshot_into(&self, buf: &mut Vec<u8>) -> bool {
                let _ = buf;
                false
            }

            /// Restore plugin-specific state.
            ///
            /// Runs on the audio thread between blocks, with the same
            /// exclusive access `process()` has - writing any field
            /// is safe.
            ///
            /// # Errors
            ///
            /// Return `Err(StateLoadError)` when the blob is malformed
            /// or otherwise can't be interpreted - the format wrapper
            /// logs the failure (and on hosts that support it, surfaces
            /// it to the DAW).
            fn load_state(
                &mut self,
                _data: &[u8],
            ) -> Result<(), $crate::__plugin_logic_deps::StateLoadError> {
                Ok(())
            }

            /// Called on the audio thread immediately after
            /// [`Self::load_state`] returns. Invalidate or recompute any
            /// caches the next `process()` reads. Default: no-op.
            fn state_changed(&mut self) {}

            /// Translate foreign state - a previous framework's blob,
            /// or a truce envelope saved under a different plugin id -
            /// into truce params + extra, so a plugin ported to truce
            /// keeps its users' old sessions and presets. Runs on the
            /// host thread; receiverless so it can't touch (or alias)
            /// the live instance. Return `None` for bytes you don't
            /// recognize - the wrapper then reports load failure to
            /// the host, exactly as if this hook didn't exist.
            ///
            /// One-shot by construction: the next save writes a normal
            /// truce envelope, so this never becomes a permanent
            /// dual-format reader. Keyed formats (AU / LV2 / AAX) only
            /// see foreign bytes when `truce.toml` declares the legacy
            /// keys to probe (`[plugin.legacy_state]`).
            #[must_use]
            fn migrate_state(
                _foreign: &$crate::__plugin_logic_deps::ForeignState,
            ) -> Option<$crate::__plugin_logic_deps::MigratedState>
            where
                Self: Sized,
            {
                None
            }

            /// Report latency in samples for plugin delay compensation.
            fn latency(&self) -> u32 {
                0
            }

            /// Report tail time in samples (audio produced after input
            /// stops - reverbs, delays). `u32::MAX` for infinite tail.
            fn tail(&self) -> u32 {
                0
            }

            // ---- GUI ----

            /// Construct the editor for this plugin. Required.
            ///
            /// There is no auto-fallback - every plugin explicitly
            /// names which renderer it wants. For the built-in
            /// widget layout, call
            /// `truce_gui::default_editor(params, layout)`; for
            /// custom renderers, construct an `EguiEditor` /
            /// `IcedEditor` / `SlintEditor` / hand-rolled `Editor`
            /// here. The choice of renderer crate the plugin's
            /// `Cargo.toml` pulls IS the choice of editor.
            ///
            /// An associated function, not a method: it receives the
            /// lock-free `Arc<Self::Params>` store the wrapper already
            /// holds, so the host can open the editor while audio is
            /// running without ever taking the plugin lock. Editors bind
            /// only to the param store (plus meters / transport, all
            /// lock-free); custom DSP state is read at runtime through
            /// the editor bridge, not at construction.
            fn editor(
                params: ::std::sync::Arc<Self::Params>,
            ) -> Box<dyn $crate::__plugin_logic_deps::Editor>;
        }
    };
}

// Re-export the dependencies the leaf-trait macro substitutes by path,
// under one `pub` doc-hidden module so user crates that invoke the
// macro don't need to import each truce-core type by hand.
#[doc(hidden)]
pub mod __plugin_logic_deps {
    pub use truce_core::buffer::AudioBuffer;
    pub use truce_core::bus::BusLayout;
    pub use truce_core::editor::Editor;
    pub use truce_core::events::EventList;
    pub use truce_core::process::{ProcessContext, ProcessStatus};
    pub use truce_core::state::{ForeignState, MigratedState, StateLoadError};
    pub use truce_params::Params;
}

plugin_logic_leaf_trait! {
    /// The `f32`-buffer user-facing plugin trait.
    ///
    /// Plugin authors implement this in a single `impl` block when
    /// their audio path is `f32` end-to-end (the default - matches
    /// the host wire format for nearly all DAWs and formats).
    /// `truce::prelude` and `truce::prelude32` re-export this name
    /// directly; `truce::prelude64m` does too (the `m` mixed-precision
    /// prelude keeps the audio buffer at `f32` and only switches the
    /// `param.read()` precision).
    ///
    /// Required: [`Self::reset`], [`Self::process`], [`Self::editor`].
    /// Everything else has a default. The editor is constructed
    /// explicitly - layout-only plugins typically call
    /// `truce_gui::default_editor(params, layout())` (where `layout()`
    /// is a plain inherent method on the plugin struct, not part of the
    /// trait).
    ///
    /// ## Params vs. DSP state
    ///
    /// The struct you implement this on holds two different kinds of
    /// data, and the method receivers reflect the split:
    ///
    /// - **Params** - the user-facing values in your `#[derive(Params)]`
    ///   struct, held as `Arc<Self::Params>`. Atomic-backed and `Sync`,
    ///   shared lock-free with the host and the editor.
    /// - **DSP state** - everything else on the struct: filter memory,
    ///   phase accumulators, voice buffers, delay lines. Plain and
    ///   non-atomic, mutated every sample, exclusive to the audio thread.
    ///
    /// `process` / `reset` / `load_state` take `&mut self` because they
    /// mutate DSP state; `save_state` / `snapshot_into` take `&self`
    /// because they read it. `editor` takes neither - it is an
    /// associated function over the param store, because a GUI is a
    /// *view* that binds only params (plus lock-free meters / transport)
    /// and never touches DSP state, so it can be built without the
    /// plugin lock. DSP state can't move into params: making per-sample
    /// filter memory atomic-shared would put a synchronized access on
    /// the hottest path, and it isn't a "parameter" anyway.
    pub trait PluginLogic<sample = f32>
}

plugin_logic_leaf_trait! {
    /// The `f64`-buffer user-facing plugin trait. Same surface as
    /// [`PluginLogic`] but with the audio buffer pinned to `f64`.
    ///
    /// Plugin authors don't usually name this directly - `truce::prelude64`
    /// re-exports it as `PluginLogic`, so the impl header reads the
    /// same regardless of which precision the prelude chose. Pick
    /// `truce::prelude64` (and thus this leaf) when the DSP path runs
    /// in `f64` end-to-end and the wrapper-boundary widen/narrow
    /// memcpy is worth the cleaner DSP code.
    pub trait PluginLogic64<sample = f64>
}

// ---------------------------------------------------------------------------
// Bridges - each leaf forwards every method to PluginLogicCore<S>
// ---------------------------------------------------------------------------

/// Define a blanket `impl<T: $leaf> PluginLogicCore<$sample> for T`
/// that forwards every trait method to `<T as $leaf>::method(...)`.
/// One source-of-truth for both `(PluginLogic, f32)` and
/// `(PluginLogic64, f64)` bridges.
macro_rules! plugin_logic_bridge {
    ($leaf:ident, $sample:ty) => {
        impl<T: $leaf> PluginLogicCore<$sample> for T {
            fn supports_in_place() -> bool
            where
                Self: Sized,
            {
                <Self as $leaf>::supports_in_place()
            }

            fn bus_layouts() -> Vec<BusLayout>
            where
                Self: Sized,
            {
                <Self as $leaf>::bus_layouts()
            }

            fn reset(&mut self, sample_rate: f64, max_block_size: usize) {
                <Self as $leaf>::reset(self, sample_rate, max_block_size);
            }

            fn process(
                &mut self,
                buffer: &mut AudioBuffer<$sample>,
                events: &EventList,
                context: &mut ProcessContext,
            ) -> ProcessStatus {
                // FTZ/DAZ (or FZ on AArch64) for the duration of
                // the user's process body. Denormals on filter
                // feedback paths stall the core; the guard pays
                // ~two MXCSR writes per block to avoid that.
                let _denormal_guard = DenormalGuard::new();
                <Self as $leaf>::process(self, buffer, events, context)
            }

            fn save_state(&self) -> Vec<u8> {
                <Self as $leaf>::save_state(self)
            }

            fn snapshot_into(&self, buf: &mut Vec<u8>) -> bool {
                <Self as $leaf>::snapshot_into(self, buf)
            }

            fn load_state(&mut self, data: &[u8]) -> Result<(), StateLoadError> {
                <Self as $leaf>::load_state(self, data)
            }

            fn state_changed(&mut self) {
                <Self as $leaf>::state_changed(self);
            }

            fn migrate_state(foreign: &ForeignState) -> Option<MigratedState>
            where
                Self: Sized,
            {
                <Self as $leaf>::migrate_state(foreign)
            }

            fn latency(&self) -> u32 {
                <Self as $leaf>::latency(self)
            }

            fn tail(&self) -> u32 {
                <Self as $leaf>::tail(self)
            }
        }

        impl<T: $leaf> PluginEditor<$sample> for T {
            type Params = <T as $leaf>::Params;

            fn editor(params: std::sync::Arc<Self::Params>) -> Box<dyn Editor> {
                <Self as $leaf>::editor(params)
            }
        }
    };
}

plugin_logic_bridge!(PluginLogic, f32);
plugin_logic_bridge!(PluginLogic64, f64);

// ---------------------------------------------------------------------------
// Default hit test - referenced by leaf macro expansions
// ---------------------------------------------------------------------------

/// Default hit test: circular for knobs, rectangular for everything
/// else, skip meters. Used by the leaf traits' `hit_test` defaults.
#[must_use]
pub fn default_hit_test(widgets: &[WidgetRegion], x: f32, y: f32) -> Option<usize> {
    for (i, w) in widgets.iter().enumerate() {
        if w.widget_type == WidgetType::Meter {
            continue;
        }
        if w.widget_type == WidgetType::Knob {
            let dx = x - w.cx;
            let dy = y - w.cy;
            if dx * dx + dy * dy <= w.radius * w.radius {
                return Some(i);
            }
        } else if x >= w.x && x <= w.x + w.w && y >= w.y && y <= w.y + w.h {
            return Some(i);
        }
    }
    None
}