Skip to main content

truce_loader/
lib.rs

1//! Hot-reload mechanics for truce: dylib loading, ABI canary, and the
2//! shells (`HotShell<P, S>`, `StaticShell<P, L, S>`) that bridge the
3//! user-facing `truce_plugin::PluginLogic` / `truce_plugin::PluginLogic64`
4//! leaf traits onto [`truce_core::PluginRuntime`] for format wrappers.
5//!
6//! Plugin authors don't reach into this crate directly. They write
7//! `impl PluginLogic for MyPlugin` (the leaf trait is sample-pinned
8//! via the prelude re-export) and the `truce::plugin!` macro picks
9//! the static or hot shell based on the `shell` Cargo feature.
10//!
11//! # ABI boundary
12//!
13//! `PluginLogic` is a stateless descriptor with a separate `type DspState`,
14//! so the DSP state can live in the *shell* rather than the reloadable
15//! dylib. The dylib exports a flat set of Rust-ABI functions
16//! (`export_plugin!`) over an opaque `*mut ()` state pointer (an erased
17//! `Box<State>`) plus the shell's `Arc<Params>` pointer. `HotShell` owns
18//! the state and, on a reload, keeps it when the new dylib's
19//! `truce_state_fingerprint` matches (code-only edit) - so a reverb tail
20//! survives the swap - and re-inits it otherwise. `StaticShell` holds a
21//! typed `L::DspState` directly.
22//!
23//! ```ignore
24//! use truce_loader::{AbiCanary, PluginLogic, PluginLogicCore};
25//!
26//! struct MyPlugin;                 // stateless descriptor
27//! impl PluginLogic for MyPlugin { type DspState = MyState; /* ... */ }
28//!
29//! // Emitted by `truce::plugin!` (plugin authors don't write these).
30//! // `Sample` resolves through the prelude alias (`f32` for `prelude` /
31//! // `prelude32` / `prelude64m`, `f64` for `prelude64`).
32//! #[unsafe(no_mangle)]
33//! pub fn truce_init_state(params: *const ()) -> *mut () { /* Box<State> */ }
34//! #[unsafe(no_mangle)]
35//! pub fn truce_process(state: *mut (), params: *const (), /* ... */) { }
36//!
37//! #[unsafe(no_mangle)]
38//! pub fn truce_abi_canary_v2() -> AbiCanary { AbiCanary::current::<Sample>() }
39//! ```
40
41#[doc(hidden)]
42pub mod __macro_deps {
43    pub use truce_core;
44    // `truce_plugin` carries the `PluginLogicCore` blanket the
45    // `export_plugin!` / `export_static!` macros need to name
46    // (`<L as PluginLogicCore<Sample>>::supports_in_place()` etc.).
47    // Re-exported here so the macro can resolve it via
48    // `$crate::__macro_deps::truce_plugin` regardless of whether the
49    // caller has `truce-plugin` as a direct dep.
50    pub use truce_plugin;
51}
52
53mod canary;
54mod safe_types;
55
56#[cfg(feature = "shell")]
57mod loader;
58#[cfg(feature = "shell")]
59pub mod shell;
60pub mod static_shell;
61
62pub use canary::{ABI_EPOCH, AbiCanary};
63pub use safe_types::*;
64// Source the leaf + core traits directly from `truce-plugin` rather
65// than via the optional `truce-gui` re-export, so these names are
66// reachable regardless of whether the `builtin-gui` feature is on.
67pub use truce_plugin::{PluginLogic, PluginLogic64, PluginLogicCore};
68
69#[cfg(feature = "shell")]
70pub use loader::NativeLoader;
71
72/// Export the `#[unsafe(no_mangle)]` symbols the hot-reload shell binds.
73///
74/// The dylib no longer hands the shell a `Box<dyn PluginLogicCore>`
75/// trait object. Instead it exports a flat set of Rust-ABI functions
76/// that operate on an **opaque state pointer** (`*mut ()`, an erased
77/// `Box<State>`): the shell owns the state, so it can hold it across a
78/// hot-reload code swap and run the freshly loaded code on the same
79/// bytes (guarded by the `truce_state_fingerprint` export).
80///
81/// `params_ptr` is a raw `Arc<Params>` pointer from the shell; each call
82/// borrows `&Params` from it (no refcount change - the shell keeps the
83/// `Arc` alive for the call's duration). `Sample` is the prelude's
84/// `type Sample` alias (`f32` for `prelude` / `prelude32` / `prelude64m`,
85/// `f64` for `prelude64`); the canary's `sample_precision` byte guards a
86/// precision-mismatched load.
87#[macro_export]
88macro_rules! export_plugin {
89    ($logic:ty, $params:ty) => {
90        /// Build the initial DSP state; returns an erased `Box<State>`.
91        #[unsafe(no_mangle)]
92        pub fn truce_init_state(params_ptr: *const ()) -> *mut () {
93            let params: &$params = unsafe { &*(params_ptr as *const $params) };
94            let state = <$logic as $crate::PluginLogicCore<Sample>>::init(params);
95            Box::into_raw(Box::new(state)).cast::<()>()
96        }
97
98        /// Drop a state allocated by *this* dylib's `truce_init_state`.
99        /// Called by the shell through the origin dylib (kept alive by
100        /// the loader's leaked-handle policy) so `State`'s `Drop` runs
101        /// with the code that produced it.
102        #[unsafe(no_mangle)]
103        pub fn truce_drop_state(state: *mut ()) {
104            drop(unsafe {
105                Box::from_raw(state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>())
106            });
107        }
108
109        /// Best-effort layout fingerprint of `State` - the shell keeps
110        /// the old state across a reload only when this matches.
111        /// Computed at load time from the state type's `type_name` /
112        /// `size_of` / `align_of`; `NO_PRESERVE` when the plugin opts out
113        /// via `PRESERVE_DSP_STATE = false` (or the state is zero-sized).
114        #[unsafe(no_mangle)]
115        pub fn truce_state_fingerprint() -> u64 {
116            if <$logic as $crate::PluginLogicCore<Sample>>::PRESERVE_DSP_STATE {
117                $crate::__macro_deps::truce_core::dsp_state::layout_fingerprint::<
118                    <$logic as $crate::PluginLogicCore<Sample>>::DspState,
119                >()
120            } else {
121                $crate::__macro_deps::truce_core::dsp_state::NO_PRESERVE
122            }
123        }
124
125        #[unsafe(no_mangle)]
126        pub fn truce_reset(
127            state: *mut (),
128            params_ptr: *const (),
129            config: &$crate::__macro_deps::truce_core::config::AudioConfig,
130        ) {
131            let state = unsafe {
132                &mut *state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>()
133            };
134            let params: &$params = unsafe { &*(params_ptr as *const $params) };
135            <$logic as $crate::PluginLogicCore<Sample>>::reset(state, params, config);
136        }
137
138        #[unsafe(no_mangle)]
139        pub fn truce_process(
140            state: *mut (),
141            params_ptr: *const (),
142            buffer: &mut $crate::__macro_deps::truce_core::buffer::AudioBuffer<Sample>,
143            events: &$crate::__macro_deps::truce_core::events::EventList,
144            ctx: &mut $crate::__macro_deps::truce_core::process::ProcessContext,
145        ) -> $crate::__macro_deps::truce_core::process::ProcessStatus {
146            let state = unsafe {
147                &mut *state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>()
148            };
149            let params: &$params = unsafe { &*(params_ptr as *const $params) };
150            <$logic as $crate::PluginLogicCore<Sample>>::process(state, params, buffer, events, ctx)
151        }
152
153        #[unsafe(no_mangle)]
154        pub fn truce_latency(state: *const ()) -> u32 {
155            let state =
156                unsafe { &*state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>() };
157            <$logic as $crate::PluginLogicCore<Sample>>::latency(state)
158        }
159
160        #[unsafe(no_mangle)]
161        pub fn truce_tail(state: *const ()) -> u32 {
162            let state =
163                unsafe { &*state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>() };
164            <$logic as $crate::PluginLogicCore<Sample>>::tail(state)
165        }
166
167        #[unsafe(no_mangle)]
168        pub fn truce_save_state(state: *const ()) -> Vec<u8> {
169            let state =
170                unsafe { &*state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>() };
171            <$logic as $crate::PluginLogicCore<Sample>>::save_state(state)
172        }
173
174        #[unsafe(no_mangle)]
175        pub fn truce_snapshot_into(state: *const (), buf: &mut Vec<u8>) -> bool {
176            let state =
177                unsafe { &*state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>() };
178            <$logic as $crate::PluginLogicCore<Sample>>::snapshot_into(state, buf)
179        }
180
181        #[unsafe(no_mangle)]
182        pub fn truce_load_state(
183            state: *mut (),
184            data: &[u8],
185        ) -> Result<(), $crate::__macro_deps::truce_core::state::StateLoadError> {
186            let state = unsafe {
187                &mut *state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>()
188            };
189            <$logic as $crate::PluginLogicCore<Sample>>::load_state(state, data)
190        }
191
192        #[unsafe(no_mangle)]
193        pub fn truce_state_changed(state: *mut (), params_ptr: *const ()) {
194            let state = unsafe {
195                &mut *state.cast::<<$logic as $crate::PluginLogicCore<Sample>>::DspState>()
196            };
197            let params: &$params = unsafe { &*(params_ptr as *const $params) };
198            <$logic as $crate::PluginLogicCore<Sample>>::state_changed(state, params);
199        }
200
201        // Editor construction lives in its own symbol: it is
202        // receiverless (over the shared `Arc<Params>`), so the shell
203        // rebuilds the editor from this dylib's `$logic` without
204        // touching the DSP state. A reload swaps in the new editor
205        // code - the host picks it up on the next editor close+open.
206        #[unsafe(no_mangle)]
207        pub fn truce_build_editor(
208            params_ptr: *const (),
209        ) -> Box<dyn $crate::__macro_deps::truce_core::editor::Editor> {
210            let params: Arc<$params> = unsafe {
211                Arc::increment_strong_count(params_ptr as *const $params);
212                Arc::from_raw(params_ptr as *const $params)
213            };
214            <$logic as $crate::__macro_deps::truce_plugin::PluginEditor<Sample>>::editor(params)
215        }
216
217        // `_v2` because `AbiCanary` crosses this boundary *by value*
218        // (sret): if the two sides disagreed about its size, the call
219        // itself would corrupt the caller's stack before any field
220        // compare. A canary-layout change therefore renames the symbol,
221        // so a mismatched pair fails at `dlsym` - cleanly.
222        #[unsafe(no_mangle)]
223        pub fn truce_abi_canary_v2() -> $crate::AbiCanary {
224            $crate::AbiCanary::current::<Sample>()
225        }
226    };
227}