truce_core/wrapper.rs
1//! Helpers shared across format wrappers (CLAP, VST3, VST2, AU, AAX, LV2).
2//!
3//! Each wrapper still owns its format-specific descriptor types and
4//! callback tables; those don't unify cleanly. What unifies is the
5//! "boring" boundary glue: building `CStrings` from `ParamInfo`
6//! fields, picking the default bus layout, and resolving install-time
7//! name overrides.
8//!
9//! Each helper is a single small function so the wrappers stay
10//! greppable - the per-format vtable construction code reads as
11//! "for each param, get cstrings, build descriptor" without inlined
12//! `CString::new(...).unwrap_or_default()` boilerplate.
13//!
14//! Adding a new format wrapper? Reach for these first; only fall back
15//! to direct `CString::new` etc. when the format genuinely needs
16//! something none of the other formats does.
17
18use std::any::type_name;
19use std::ffi::CString;
20use std::panic::{AssertUnwindSafe, catch_unwind};
21use std::sync::Arc;
22
23use truce_params::ParamInfo;
24
25use crate::bus::BusLayout;
26use crate::export::PluginExport;
27
28pub use plugin_mutex::{PluginGuard, PluginMutex};
29
30/// The mediation lock every format wrapper puts around its plugin
31/// instance. The audio thread holds the lock for the duration of a
32/// block (`process`, `reset`, the queued state apply); host-thread
33/// state callbacks and the editor's `get_state` closure block for
34/// the read - safe in that direction, and bounded by the block the
35/// audio thread is finishing. Meters ride the lock-free `MeterStore`
36/// instead, so per-frame GUI paints never touch this lock.
37///
38/// The lock is only as strong as the scheduler behind it, so
39/// [`PluginMutex`] picks per platform:
40/// - **macOS**: `std::sync::Mutex` sits on `os_unfair_lock`, which
41/// donates the waiter's priority to the owner - a GUI thread
42/// preempted mid-`save_state` gets boosted to the waiting audio
43/// thread's priority.
44/// - **Linux**: a `PTHREAD_PRIO_INHERIT` pthread mutex; std's
45/// futex-based lock has no priority inheritance there.
46/// - **Windows**: `std::sync::Mutex` (SRWLOCK). User space has no
47/// priority-inheriting primitive, so the defense is the short
48/// hold - non-audio holders only span `save_state` / `editor()`.
49///
50/// (`parking_lot` inherits priority nowhere, which is why it isn't
51/// used. Uncontended cost is a CAS on every platform.)
52/// A panic while holding the guard unlocks on unwind; std's poison
53/// is forgiven (see [`lock_plugin`]).
54///
55/// A `Mutex` rather than an `RwLock`: the only non-audio accessors
56/// are a host state save and an editor preset capture - both rare -
57/// so reader parallelism buys nothing, and `Mutex<P>: Sync` needs
58/// only `P: Send` (an `RwLock` would force `Sync` onto every plugin
59/// type).
60///
61/// The `Arc` is what makes GUI closures sound: they clone the handle
62/// instead of stashing a raw pointer into the instance struct (whose
63/// `&mut` the audio thread holds during callbacks).
64pub type SharedPlugin<P> = Arc<PluginMutex<P>>;
65
66/// Wrap a freshly created plugin in the wrapper-standard mediation
67/// lock. See [`SharedPlugin`].
68pub fn shared_plugin<P>(plugin: P) -> SharedPlugin<P> {
69 Arc::new(PluginMutex::new(plugin))
70}
71
72/// Lock the mediation lock, forgiving poison. A poisoned lock means a
73/// panic already escaped somewhere and was reported by the wrapper's
74/// panic guard; refusing every later block would turn one bad block
75/// into permanent silence, and the plugin's state is no more suspect
76/// than after any other caught panic. (The Linux pthread lock has no
77/// poison to forgive; unwind simply unlocks.)
78pub fn lock_plugin<P>(plugin: &PluginMutex<P>) -> PluginGuard<'_, P> {
79 plugin.lock()
80}
81
82/// [`lock_plugin`]'s non-blocking twin: `None` only when the lock is
83/// genuinely held (poison is forgiven, same rationale).
84pub fn try_lock_plugin<P>(plugin: &PluginMutex<P>) -> Option<PluginGuard<'_, P>> {
85 plugin.try_lock()
86}
87
88/// Read the plugin's custom-state blob for a host state save.
89///
90/// Prefers the lock-free [`SnapshotSlot`](crate::snapshot::SnapshotSlot)
91/// the audio thread publishes each block; only when the plugin doesn't
92/// opt into snapshots (nothing published) does it fall back to locking
93/// the plugin and calling `save_state()`. So a snapshot-capable plugin's
94/// host save never touches the plugin lock and never waits on an
95/// in-flight audio block. Params are serialized separately (lock-free),
96/// so this is the only piece of a save that could contend the lock.
97pub fn save_extra<P: crate::plugin::PluginRuntime>(
98 snapshot: &crate::snapshot::SnapshotSlot,
99 plugin: &PluginMutex<P>,
100) -> Vec<u8> {
101 snapshot
102 .read()
103 .unwrap_or_else(|| lock_plugin(plugin).save_state())
104}
105
106/// std-backed [`PluginMutex`]: macOS (`os_unfair_lock` donates the
107/// waiter's priority) and Windows (SRWLOCK; no user-space priority
108/// inheritance exists). Miri also lands here - it has no shim for
109/// `pthread_mutexattr_setprotocol`, and the std lock gives it full
110/// visibility.
111#[cfg(any(not(target_os = "linux"), miri))]
112mod plugin_mutex {
113 use std::ops::{Deref, DerefMut};
114 use std::sync::{Mutex, MutexGuard, PoisonError, TryLockError};
115
116 /// See [`super::SharedPlugin`] for the per-platform lock choice.
117 pub struct PluginMutex<T>(Mutex<T>);
118
119 /// Guard handing out the exclusive `&mut T`; unlocks on drop.
120 pub struct PluginGuard<'a, T>(MutexGuard<'a, T>);
121
122 impl<T> PluginMutex<T> {
123 pub fn new(value: T) -> Self {
124 Self(Mutex::new(value))
125 }
126
127 /// Block until the lock is held. Poison is forgiven (see
128 /// [`super::lock_plugin`]).
129 pub fn lock(&self) -> PluginGuard<'_, T> {
130 PluginGuard(self.0.lock().unwrap_or_else(PoisonError::into_inner))
131 }
132
133 /// `None` only when the lock is genuinely held.
134 pub fn try_lock(&self) -> Option<PluginGuard<'_, T>> {
135 match self.0.try_lock() {
136 Ok(guard) => Some(PluginGuard(guard)),
137 Err(TryLockError::Poisoned(poisoned)) => Some(PluginGuard(poisoned.into_inner())),
138 Err(TryLockError::WouldBlock) => None,
139 }
140 }
141 }
142
143 impl<T> Deref for PluginGuard<'_, T> {
144 type Target = T;
145 fn deref(&self) -> &T {
146 &self.0
147 }
148 }
149
150 impl<T> DerefMut for PluginGuard<'_, T> {
151 fn deref_mut(&mut self) -> &mut T {
152 &mut self.0
153 }
154 }
155}
156
157/// Linux [`PluginMutex`]: a `PTHREAD_PRIO_INHERIT` pthread mutex.
158/// std's futex-based lock has no priority inheritance, so a
159/// low-priority GUI thread preempted mid-`save_state` would stall
160/// the audio thread at the scheduler's mercy; with PI the holder
161/// inherits the waiting audio thread's priority for the remainder
162/// of the hold.
163#[cfg(all(target_os = "linux", not(miri)))]
164mod plugin_mutex {
165 use std::cell::UnsafeCell;
166 use std::marker::PhantomData;
167 use std::ops::{Deref, DerefMut};
168
169 /// See [`super::SharedPlugin`] for the per-platform lock choice.
170 pub struct PluginMutex<T> {
171 /// Boxed: a pthread mutex must not move once initialized,
172 /// and `Arc::new(PluginMutex::new(..))` moves the struct.
173 raw: Box<UnsafeCell<libc::pthread_mutex_t>>,
174 data: UnsafeCell<T>,
175 }
176
177 // SAFETY: the pthread mutex serializes all access to `data`, so
178 // sharing the container across threads hands `T` to one thread
179 // at a time - the same bound (`T: Send`) std's `Mutex` requires.
180 unsafe impl<T: Send> Send for PluginMutex<T> {}
181 // SAFETY: as above - `&PluginMutex` only reaches `T` through the
182 // lock, so `Sync` needs only `T: Send`.
183 unsafe impl<T: Send> Sync for PluginMutex<T> {}
184
185 impl<T> PluginMutex<T> {
186 pub fn new(value: T) -> Self {
187 let raw = Box::new(UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER));
188 // SAFETY: `raw` is freshly allocated and unshared; the
189 // attr is initialized before use and destroyed after.
190 unsafe {
191 let mut attr: libc::pthread_mutexattr_t = std::mem::zeroed();
192 if libc::pthread_mutexattr_init(&raw mut attr) == 0 {
193 // Best effort: a libc refusing PI still leaves a
194 // valid default-protocol attr, and init below
195 // yields an ordinary mutex.
196 let _ = libc::pthread_mutexattr_setprotocol(
197 &raw mut attr,
198 libc::PTHREAD_PRIO_INHERIT,
199 );
200 let _ = libc::pthread_mutex_init(raw.get(), &raw const attr);
201 let _ = libc::pthread_mutexattr_destroy(&raw mut attr);
202 }
203 }
204 Self {
205 raw,
206 data: UnsafeCell::new(value),
207 }
208 }
209
210 /// Block until the lock is held. A panicking previous holder
211 /// unlocked on unwind (guard drop); there is no poison state.
212 pub fn lock(&self) -> PluginGuard<'_, T> {
213 // SAFETY: the mutex was initialized in `new` and outlives
214 // the returned guard's borrow.
215 unsafe {
216 libc::pthread_mutex_lock(self.raw.get());
217 }
218 PluginGuard {
219 lock: self,
220 _not_send: PhantomData,
221 }
222 }
223
224 /// `None` when the lock is held elsewhere.
225 pub fn try_lock(&self) -> Option<PluginGuard<'_, T>> {
226 // SAFETY: as in `lock`.
227 (unsafe { libc::pthread_mutex_trylock(self.raw.get()) } == 0).then_some(PluginGuard {
228 lock: self,
229 _not_send: PhantomData,
230 })
231 }
232 }
233
234 impl<T> Drop for PluginMutex<T> {
235 fn drop(&mut self) {
236 // SAFETY: `&mut self` proves no guard is alive, so the
237 // mutex is unlocked and safe to destroy.
238 unsafe {
239 libc::pthread_mutex_destroy(self.raw.get());
240 }
241 }
242 }
243
244 /// Guard handing out the exclusive `&mut T`; unlocks on drop.
245 pub struct PluginGuard<'a, T> {
246 lock: &'a PluginMutex<T>,
247 /// PI mutexes must be unlocked by the locking thread; the
248 /// raw-pointer marker strips `Send` so the guard can't cross.
249 _not_send: PhantomData<*const ()>,
250 }
251
252 impl<T> Deref for PluginGuard<'_, T> {
253 type Target = T;
254 fn deref(&self) -> &T {
255 // SAFETY: this guard holds the lock.
256 unsafe { &*self.lock.data.get() }
257 }
258 }
259
260 impl<T> DerefMut for PluginGuard<'_, T> {
261 fn deref_mut(&mut self) -> &mut T {
262 // SAFETY: this guard holds the lock exclusively.
263 unsafe { &mut *self.lock.data.get() }
264 }
265 }
266
267 impl<T> Drop for PluginGuard<'_, T> {
268 fn drop(&mut self) {
269 // SAFETY: this guard holds the lock; unlock happens on
270 // the locking thread (the guard is `!Send`).
271 unsafe {
272 libc::pthread_mutex_unlock(self.lock.raw.get());
273 }
274 }
275 }
276}
277
278/// `CStrings` derived from a single `ParamInfo`. All four conversions
279/// follow the same pattern (`unwrap_or_default()` so a `\0` in metadata
280/// degrades to an empty C string instead of panicking the host); pulling
281/// them into one struct keeps the per-format vtable loops uniform.
282pub struct ParamCStrings {
283 pub name: CString,
284 pub short_name: CString,
285 pub unit: CString,
286 pub group: CString,
287}
288
289impl ParamCStrings {
290 /// Build all four `CStrings` for one parameter.
291 #[must_use]
292 pub fn from_info(info: &ParamInfo) -> Self {
293 Self {
294 name: CString::new(info.name).unwrap_or_default(),
295 short_name: CString::new(info.short_name).unwrap_or_default(),
296 unit: CString::new(info.unit.as_str()).unwrap_or_default(),
297 group: CString::new(info.group).unwrap_or_default(),
298 }
299 }
300}
301
302/// `(input_channels, output_channels)` for the plugin's default bus
303/// layout, or `None` when the plugin declares no layouts.
304/// Used by every format's vtable / descriptor to advertise channel
305/// counts at registration time.
306///
307/// **Note for `aumi` (MIDI processor) plugins:** the convention is
308/// `bus_layouts: [BusLayout::new()]`, which has zero input *and* zero
309/// output channels. This helper returns `Some((0, 0))` for that case,
310/// which is correct for AU (the AU shim's `channelCapabilities`
311/// returns `[0, 0]` and the host treats the plugin as MIDI-only) but
312/// **wrong for AAX**, which requires every plugin to advertise at
313/// least stereo audio I/O. AAX maps `(0, 0)` to `(2, 2)` (synthesizing
314/// a stereo passthrough) after this helper returns. Don't push that
315/// remap into this helper; only AAX needs it.
316///
317/// `None` indicates a plugin-author bug: zero-bus plugins must return
318/// `vec![BusLayout::new()]` explicitly. Callers should log a
319/// diagnostic and skip registration (see how each `register_*` entry
320/// point handles this) rather than substitute a silent default that
321/// would misreport channel counts to the host.
322#[must_use]
323pub fn default_io_channels<P: PluginExport>() -> Option<(u32, u32)> {
324 P::bus_layouts()
325 .first()
326 .map(|l| (l.total_input_channels(), l.total_output_channels()))
327}
328
329/// Pick the plugin's first bus layout, or `None` when the plugin
330/// declares no layouts.
331/// Used by wrappers (AAX, VST2) that need to read the layout *before*
332/// host-side bus-config negotiation, where a missing layout would
333/// otherwise produce silently-misreported channel counts.
334///
335/// For `aumi` plugins the returned layout is typically `BusLayout::new()`
336/// (zero in / zero out). AAX synthesizes `(2, 2)` from that case in
337/// `register_aax`; see [`default_io_channels`] for the rationale.
338///
339/// `None` is the same plugin-author-bug indicator as
340/// [`default_io_channels`]: log a diagnostic and skip registration.
341#[must_use]
342pub fn first_bus_layout<P: PluginExport>() -> Option<BusLayout> {
343 P::bus_layouts().into_iter().next()
344}
345
346/// Standard diagnostic emitted by `register_*` when [`first_bus_layout`]
347/// or [`default_io_channels`] returns `None`. Centralised so every
348/// wrapper prints the same actionable message.
349pub fn log_missing_bus_layout<P: PluginExport>(format: &str) {
350 eprintln!(
351 "[truce {format}] {}::bus_layouts() returned an empty list - \
352 plugin will not register. Plugins with no audio I/O (e.g. \
353 aumi MIDI-effects) should return vec![BusLayout::new()] \
354 explicitly.",
355 type_name::<P>(),
356 );
357}
358
359/// Diagnostic for a plugin that declared more MIDI ports than the
360/// format can carry. The wrapper clamps to a single port and routes
361/// all traffic to port `0`; without this line the truncation would read
362/// as "multi-port supported." `declared` is the plugin's per-direction
363/// port count; nothing is logged for the single-port (or zero-port)
364/// case. `direction` is `"input"` / `"output"`.
365pub fn log_midi_ports_clamped(format: &str, direction: &str, declared: u8) {
366 if declared > 1 {
367 eprintln!(
368 "[truce {format}] plugin declares {declared} MIDI {direction} ports, but {format} \
369 carries one - routing all {direction} MIDI to port 0.",
370 );
371 }
372}
373
374/// Run a `register_*` body under [`std::panic::catch_unwind`].
375///
376/// Format wrappers' `register_*` entry points run during plugin
377/// registration - some from `extern "C" fn init` static
378/// initializers (`.init_array` / `__mod_init_func` / `.CRT$XCU`),
379/// others lazily on the first host query (AAX, to keep the Windows
380/// loader-lock window empty during Pro Tools' scan). A panic that
381/// escapes them crosses an `extern "C"`
382/// boundary and aborts the host process - a `panic = "abort"`
383/// configuration would do the same. Catching the unwind here turns
384/// any panic during registration into a logged diagnostic plus
385/// "host sees no plugin," which is the same outcome a plugin author
386/// would expect from a missing `bus_layouts` declaration.
387///
388/// `AssertUnwindSafe` is applied internally - the panic is treated
389/// as fatal-for-this-plugin, so leaving an `Arc` ref-count or
390/// `OnceLock` half-set is acceptable: the host won't load the
391/// plugin and the process will exit shortly after registration
392/// finishes anyway.
393pub fn run_register<P>(format: &str, body: impl FnOnce()) {
394 let result = catch_unwind(AssertUnwindSafe(body));
395 if let Err(payload) = result {
396 eprintln!(
397 "[truce {format}] panic during register for {}: {}",
398 type_name::<P>(),
399 extract_panic_msg(&payload),
400 );
401 }
402}
403
404/// Run a per-block audio-thread `body` under
405/// [`std::panic::catch_unwind`].
406///
407/// Format wrappers call this around the `cb_process` body so a panic
408/// from user `process()` can't unwind across the `extern "C"` FFI
409/// boundary into the host (UB on most toolchains; abort on others).
410/// Returns `true` on clean exit, `false` if the body panicked - the
411/// caller should zero output buffers on `false` so the host doesn't
412/// keep playing whatever happened to be in those slots.
413///
414/// Panic logging is one short `eprintln!` per occurrence; the audio
415/// thread should never panic, so the I/O is rare and acceptable.
416#[must_use]
417pub fn run_audio_block<P>(format: &str, body: impl FnOnce()) -> bool {
418 let result = catch_unwind(AssertUnwindSafe(body));
419 if let Err(payload) = result {
420 eprintln!(
421 "[truce {format}] panic in process() for {}: {}",
422 type_name::<P>(),
423 extract_panic_msg(&payload),
424 );
425 return false;
426 }
427 true
428}
429
430/// Like [`run_audio_block`] but for callbacks that return a status
431/// code. Returns `body`'s value on a clean exit, `fallback` if the
432/// body panicked. Used by the CLAP wrapper, whose process callback
433/// returns a `clap_process_status` `i32`.
434pub fn run_audio_block_with<P, R>(format: &str, fallback: R, body: impl FnOnce() -> R) -> R {
435 match catch_unwind(AssertUnwindSafe(body)) {
436 Ok(r) => r,
437 Err(payload) => {
438 eprintln!(
439 "[truce {format}] panic in process() for {}: {}",
440 type_name::<P>(),
441 extract_panic_msg(&payload),
442 );
443 fallback
444 }
445 }
446}
447
448/// Run a generic `extern "C"` callback body under
449/// [`std::panic::catch_unwind`]. Returns `body`'s value on a clean
450/// exit, `fallback` if the body panicked.
451///
452/// Same shape as [`run_audio_block_with`] but parameterized on
453/// `action` (e.g. `"save_state"`, `"load_state"`) so the panic log
454/// pinpoints which callback boundary fired. Use this for non-process
455/// FFI surfaces - state save / load, param formatting, anything the
456/// host calls through an `extern "C" fn` where a panic would unwind
457/// across an ABI that doesn't promise abort-on-unwind.
458///
459/// Audio-thread process bodies should keep using
460/// [`run_audio_block`] / [`run_audio_block_with`] - the hardcoded
461/// `"process()"` label there keeps existing log lines stable.
462pub fn run_extern_callback_with<P, R>(
463 format: &str,
464 action: &str,
465 fallback: R,
466 body: impl FnOnce() -> R,
467) -> R {
468 match catch_unwind(AssertUnwindSafe(body)) {
469 Ok(r) => r,
470 Err(payload) => {
471 eprintln!(
472 "[truce {format}] panic in {action} for {}: {}",
473 type_name::<P>(),
474 extract_panic_msg(&payload),
475 );
476 fallback
477 }
478 }
479}
480
481fn extract_panic_msg(payload: &Box<dyn std::any::Any + Send>) -> &str {
482 if let Some(s) = payload.downcast_ref::<&'static str>() {
483 s
484 } else if let Some(s) = payload.downcast_ref::<String>() {
485 s.as_str()
486 } else {
487 "<non-string panic payload>"
488 }
489}
490
491#[cfg(test)]
492mod plugin_mutex_tests {
493 use std::sync::Arc;
494
495 use super::{lock_plugin, shared_plugin, try_lock_plugin};
496
497 #[test]
498 fn lock_round_trips_data() {
499 let plugin = shared_plugin(41);
500 *lock_plugin(&plugin) += 1;
501 assert_eq!(*lock_plugin(&plugin), 42);
502 }
503
504 #[test]
505 fn try_lock_reports_contention() {
506 let plugin = shared_plugin(0u32);
507 let held = lock_plugin(&plugin);
508 assert!(try_lock_plugin(&plugin).is_none());
509 drop(held);
510 assert!(try_lock_plugin(&plugin).is_some());
511 }
512
513 #[test]
514 fn excludes_across_threads() {
515 // Unsynchronized increments would lose updates; the final
516 // count proves the guard serializes every access.
517 let plugin = shared_plugin(0u64);
518 let threads: Vec<_> = (0..4)
519 .map(|_| {
520 let plugin = Arc::clone(&plugin);
521 std::thread::spawn(move || {
522 for _ in 0..10_000 {
523 *lock_plugin(&plugin) += 1;
524 }
525 })
526 })
527 .collect();
528 for t in threads {
529 t.join().unwrap();
530 }
531 assert_eq!(*lock_plugin(&plugin), 40_000);
532 }
533
534 #[test]
535 fn panicking_holder_does_not_wedge_the_lock() {
536 // One bad block must not turn into permanent silence: a
537 // panicking holder unlocks on unwind (std poison forgiven,
538 // pthread unlocked by the guard drop).
539 let plugin = shared_plugin(7);
540 let for_panic = Arc::clone(&plugin);
541 let _ = std::thread::spawn(move || {
542 let _guard = lock_plugin(&for_panic);
543 panic!("wedge attempt");
544 })
545 .join();
546 assert_eq!(*lock_plugin(&plugin), 7);
547 assert!(try_lock_plugin(&plugin).is_some());
548 }
549}