clack-plugin 0.2.0

Low-level, safe Rust wrappers to create audio plugins using the CLAP audio plugin API.
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
//! Utilities to manipulate Plugin instances from an FFI context.
//!
//! These unsafe utilities are targeted at extension implementors. Most `clack-plugin` users do not
//! have to use those utilities to use extensions, see `clack-extensions` instead.

use crate::host::HostSharedHandle;
use crate::internal_utils::UnsafeOptionCell;
use crate::plugin::{Plugin, PluginAudioProcessor, PluginBoxInner, PluginError, logging};
use crate::process::PluginAudioConfiguration;
use clap_sys::ext::log::*;
use clap_sys::plugin::clap_plugin;
use std::borrow::Cow;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt::{Display, Formatter};
use std::io::Write;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::ptr::NonNull;

#[cfg(not(test))]
#[allow(unused)]
pub(crate) use std::panic::catch_unwind as handle_panic;

#[cfg(test)]
#[inline]
#[allow(unused)]
pub(crate) fn handle_panic<F: FnOnce() -> R, R>(f: F) -> std::thread::Result<R> {
    Ok(f())
}

/// A wrapper around a `clack` plugin of a given type.
///
/// This wrapper allows access to a plugin's [`Shared`](Plugin::Shared),
/// [`MainThread`](Plugin::MainThread), and [`AudioProcessor`](Plugin::AudioProcessor) structs, while
/// also handling common FFI issues, such as error management and unwind safety.
///
/// The only way to access an instance of `PluginWrapper` is through the
/// [`handle`](PluginWrapper::handle) function.
pub struct PluginWrapper<'a, P: Plugin> {
    audio_processor: UnsafeOptionCell<P::AudioProcessor<'a>>,
    main_thread: P::MainThread<'a>,
    shared: Pin<Box<P::Shared<'a>>>,
    host: HostSharedHandle<'a>,
}

impl<'a, P: Plugin> PluginWrapper<'a, P> {
    /// # Safety
    ///
    /// `shared` and `main_thread` must be related and correctly initialized.
    pub(crate) unsafe fn new(
        host: HostSharedHandle<'a>,
        shared: Pin<Box<P::Shared<'a>>>,
        main_thread: P::MainThread<'a>,
    ) -> Self {
        Self {
            host,
            shared,
            main_thread,
            audio_processor: UnsafeOptionCell::new(),
        }
    }

    /// # Safety
    /// Caller must ensure this method is only called on main thread and has exclusivity
    pub(crate) unsafe fn activate(
        &self,
        audio_config: PluginAudioConfiguration,
    ) -> Result<(), PluginWrapperError> {
        if self.is_active() {
            return Err(PluginWrapperError::ActivatedPlugin);
        }

        let shared = &*(self.shared() as *const _);
        let host = self.host;

        let processor = P::AudioProcessor::activate(
            host.as_audio_processor_unchecked(),
            self.main_thread(),
            shared,
            audio_config,
        )?;

        // SAFETY: It is up to the caller to ensure this is never called simultaneously with deactivate()
        self.audio_processor.put(processor);

        Ok(())
    }

    /// # Safety
    /// Caller must ensure this method is only called on main thread, and has exclusivity on it
    pub(crate) unsafe fn deactivate(&self) -> Result<(), PluginWrapperError> {
        match self.audio_processor.take() {
            None => Err(PluginWrapperError::DeactivatedPlugin),
            Some(audio_processor) => {
                audio_processor.deactivate(self.main_thread());

                Ok(())
            }
        }
    }

    /// Returns if the current plugin has been activated or not.
    #[inline]
    pub fn is_active(&self) -> bool {
        self.audio_processor.is_some()
    }

    /// Returns a reference to a plugin's [`Shared`](Plugin::Shared) struct.
    ///
    /// This is always safe to call in any context, since the `Shared` struct is required to
    /// implement `Sync`.
    #[inline]
    pub fn shared(&self) -> &P::Shared<'a> {
        &self.shared
    }

    /// Returns a raw, non-null pointer to the plugin's [`MainThread`](Plugin::MainThread)
    /// struct.
    ///
    /// # Safety
    /// The caller must ensure this method is only called on the main thread.
    ///
    /// The pointer is safe to mutably dereference, as long as the caller ensures it is not being
    /// aliased, as per usual safety rules.
    #[inline]
    pub unsafe fn main_thread(&self) -> &'_ P::MainThread<'a> {
        &self.main_thread
    }

    /// Returns a raw, non-null pointer to the plugin's audio processor
    /// (i.e. [`Plugin`](PluginAudioProcessor)) struct.
    ///
    /// # Errors
    ///
    /// This method will return `PluginWrapperError::DeactivatedPlugin` if the plugin has not been
    /// activated before calling this method.
    ///
    /// This is an extra safety check which ensures that hosts correctly activated plugins before
    /// calling any audio-thread method.
    ///
    /// # Safety
    /// The caller must ensure this method is only called on the audio thread.
    ///
    /// The pointer is safe to mutably dereference, as long as the caller ensures it is not being
    /// aliased, as per usual safety rules.
    #[inline]
    pub unsafe fn audio_processor(
        &self,
    ) -> Result<NonNull<P::AudioProcessor<'a>>, PluginWrapperError> {
        self.audio_processor
            .as_ptr()
            // SAFETY: pointer has been created from reference, it cannot be null.
            .ok_or(PluginWrapperError::DeactivatedPlugin)
    }

    /// Provides a shared reference to a plugin wrapper of a given type, to the given handler
    /// closure.
    ///
    /// Besides providing a reference, this function does a few extra safety checks:
    ///
    /// * The given `clap_plugin` pointer is null-checked, as well as some other host-provided
    ///   pointers;
    /// * The handler is wrapped in [`std::panic::catch_unwind`];
    /// * Any [`PluginWrapperError`] returned by the handler is caught.
    ///
    /// If any of the above safety check fails, an error message is logged (using the standard CLAP
    /// logging extension). If logging is unavailable or fails for any reason, the error message is
    /// written to `stderr` as a fallback.
    ///
    /// Note that some safety checks (e.g. the `clap_plugin` pointer null-checks) may result in the
    /// closure never being called, and an error being returned only. Users of this function must
    /// not rely on the completion of this closure for safety, and must handle this function
    /// returning `None` gracefully.
    ///
    /// If all goes well, the return value of the handler closure is forwarded and returned by this
    /// function.
    ///
    /// # Errors
    ///
    /// If any safety check failed, or any error or panic occurred inside the handler closure, this
    /// function returns `None`, and the error message is logged.
    ///
    /// # Safety
    ///
    /// The given plugin type `P` **must** be the correct type for the received pointer. Otherwise,
    /// incorrect casts will occur, which will lead to Undefined Behavior.
    ///
    /// The `plugin` pointer must also point to a valid instance of `clap_plugin`, as provided by
    /// the CLAP Host. While this function does a couple of simple safety checks, only a few common
    /// cases are actually covered (i.e. null checks), and those **must not** be relied upon: those
    /// checks only exist to help debugging faulty hosts.
    ///
    /// # Example
    ///
    /// This is the implementation of the [`on_main_thread`](crate::plugin::PluginMainThread::on_main_thread)
    /// callback's C wrapper.
    ///
    /// This method is guaranteed by the CLAP specification to be only called on the main thread.
    ///
    /// ```
    /// use clap_sys::plugin::clap_plugin;
    /// use clack_plugin::plugin::{Plugin, PluginMainThread};
    /// use clack_plugin::extensions::wrapper::PluginWrapper;
    ///
    /// unsafe extern "C" fn on_main_thread<P: Plugin>(plugin: *const clap_plugin) {
    ///   PluginWrapper::<P>::handle(plugin, |p| {
    ///     p.main_thread().on_main_thread();
    ///     Ok(())
    ///   });
    /// }
    /// ```
    pub unsafe fn handle<T, F>(plugin: *const clap_plugin, handler: F) -> Option<T>
    where
        F: FnOnce(&PluginWrapper<'a, P>) -> Result<T, PluginWrapperError>,
    {
        match Self::from_raw(plugin).and_then(|p| Self::handle_panic(p, handler)) {
            Ok(value) => Some(value),
            Err(e) => {
                logging::plugin_log::<P>(plugin, &e);

                None
            }
        }
    }

    /// # Safety
    /// The plugin pointer must be valid
    pub(crate) unsafe fn handle_plugin_data<T, F>(
        plugin: *const clap_plugin,
        handler: F,
    ) -> Option<T>
    where
        F: FnOnce(NonNull<PluginBoxInner<'a, P>>) -> Result<T, PluginWrapperError>,
    {
        match Self::plugin_data_from_raw(plugin).and_then(|p| Self::handle_panic(p, handler)) {
            Ok(value) => Some(value),
            Err(e) => {
                logging::plugin_log::<P>(plugin, &e);

                None
            }
        }
    }

    /// # Safety
    /// The plugin pointer must be valid
    unsafe fn from_raw<'p>(raw: *const clap_plugin) -> Result<&'p Self, PluginWrapperError> {
        raw.as_ref()
            .ok_or(PluginWrapperError::NullPluginInstance)?
            .plugin_data
            .cast::<PluginBoxInner<'a, P>>()
            .as_ref()
            .ok_or(PluginWrapperError::AlreadyDestroyed)?
            .wrapper()
    }

    /// # Safety
    /// The plugin pointer must be valid
    unsafe fn plugin_data_from_raw(
        raw: *const clap_plugin,
    ) -> Result<NonNull<PluginBoxInner<'a, P>>, PluginWrapperError> {
        let data = raw
            .as_ref()
            .ok_or(PluginWrapperError::NullPluginInstance)?
            .plugin_data
            .cast::<PluginBoxInner<'a, P>>();

        NonNull::new(data).ok_or(PluginWrapperError::AlreadyDestroyed)
    }

    #[inline]
    fn handle_panic<Pa, T, F>(parameter: Pa, handler: F) -> Result<T, PluginWrapperError>
    where
        F: FnOnce(Pa) -> Result<T, PluginWrapperError>,
    {
        handle_panic(AssertUnwindSafe(|| handler(parameter)))
            .map_err(|_| PluginWrapperError::Panic)?
    }
}

// SAFETY: the wrapper itself can be shared and used across threads, accessing any inner part that
// isn't requires unsafe.
unsafe impl<P: Plugin> Send for PluginWrapper<'_, P> {}
// SAFETY: the wrapper itself can be shared and used across threads, accessing any inner part that
// isn't requires unsafe.
unsafe impl<P: Plugin> Sync for PluginWrapper<'_, P> {}

/// Errors raised by a [`PluginWrapper`].
#[derive(Debug)]
#[non_exhaustive]
pub enum PluginWrapperError {
    /// The `clap_plugin` raw pointer was null.
    NullPluginInstance,
    /// The `clap_plugin.plugin_data` raw pointer was null, which indicates the instance was already
    /// destroyed.
    AlreadyDestroyed,
    /// An unexpectedly null raw pointer was encountered.
    ///
    /// The given string may contain more information about which pointer was found to be null.
    NulPtr(&'static str),
    /// An invalid parameter value was encountered.
    ///
    /// The given string may contain more information about which parameter was found to be invalid.
    InvalidParameter(&'static str),
    /// The plugin was not properly initialized (i.e. `init` was not called).
    UninitializedPlugin,
    /// The host tried to call a plugin method while `init` is running.
    PluginCalledDuringInitialization,
    /// The host tried to call a plugin method while `destroy` is running.
    Destroying,
    /// The plugin's initialization (`init`) has failed.
    InitializationAlreadyFailed,
    /// The plugin is already initialized (i.e. a second call to `init` was attempted).
    AlreadyInitialized,
    /// An attempt was made to call `activate` on an already activated plugin.
    ActivatedPlugin,
    /// An attempt was made to call an audio-thread function while the plugin was deactivated
    /// (e.g. without previously calling `activate`).
    DeactivatedPlugin,
    /// A function which requires the plugin to be deactivated was called while the plugin was still
    /// active.
    DeactivationRequiredForFunction(&'static str),
    /// The plugin panicked during a function call.
    Panic,
    /// A given [`PluginError`] was raised during a function call.
    Plugin(PluginError),
    /// Bad UTF-8.
    StringEncoding(std::str::Utf8Error),
    /// Plugin returned a malformed C string.
    InvalidCString(std::ffi::NulError),
    /// Encountered an error while trying to format another [`PluginWrapperError`]
    ErrorFormatError(std::io::Error),
    /// A generic or custom error of a given severity.
    Error(clap_log_severity, Box<dyn Error>),
    /// A constant string message to be displayed.
    Message(clap_log_severity, &'static str),
}

impl PluginWrapperError {
    /// Returns the severity of this error.
    ///
    /// This is mainly useful for logging.
    ///
    /// # Example
    ///
    /// ```
    /// use clap_sys::ext::log::CLAP_LOG_PLUGIN_MISBEHAVING;
    /// use clack_plugin::extensions::wrapper::PluginWrapperError;
    /// let error = PluginWrapperError::Panic;
    ///
    /// assert_eq!(error.severity(), CLAP_LOG_PLUGIN_MISBEHAVING);
    /// ```
    pub fn severity(&self) -> clap_log_severity {
        match self {
            PluginWrapperError::Plugin(_) => CLAP_LOG_ERROR,
            PluginWrapperError::Panic => CLAP_LOG_PLUGIN_MISBEHAVING,
            PluginWrapperError::Error(s, _) => *s,
            PluginWrapperError::Message(s, _) => *s,
            _ => CLAP_LOG_HOST_MISBEHAVING,
        }
    }

    /// If this error holds an [`io::Error`](std::io::Error), returns its raw OS error.
    ///
    /// If not applicable, this returns `None` instead.
    pub fn os_error_code(&self) -> Option<i32> {
        let e = match self {
            PluginWrapperError::Error(_, e) => e,
            _ => return None,
        };

        e.downcast_ref::<std::io::Error>()?.raw_os_error()
    }

    /// Formats this error into either a [`CStr`] or [`CString`].
    ///
    /// This will handle formatting failures and return an appropriate message in that case, so
    /// unlike the [`Display`] implementation, this will always return a displayable error message.
    pub fn format_cstr(&self) -> Cow<'static, CStr> {
        let mut buf = Vec::new();
        match buf.write_fmt(format_args!("{}", self)) {
            Ok(()) => {}
            Err(e) => {
                // Stop this here to avoid infinitely failing to format the failing error message
                if matches!(self, PluginWrapperError::ErrorFormatError(_)) {
                    return c"Failed to format error".into();
                }

                return PluginWrapperError::ErrorFormatError(e).format_cstr();
            }
        };

        // Truncate until the first NULL byte just in case. This is better than returning no error message.
        if let Some(idx) = buf.iter().position(|&b| b == 0) {
            buf.truncate(idx);
        }

        // This should not be able to happen thanks to the above check, but let's put it here just in case
        let Ok(str) = CString::new(buf) else {
            return c"Error format failure: NulError".into();
        };

        str.into()
    }

    /// Returns a closure that maps an error to a [`PluginWrapperError::Error`] error of a given
    /// severity.
    ///
    /// This is a useful helper method when paired with [`Result::map_err`].
    ///
    /// # Example
    /// ```
    /// use clap_sys::ext::log::CLAP_LOG_PLUGIN_MISBEHAVING;
    /// use clack_plugin::extensions::wrapper::PluginWrapperError;
    ///
    /// let x: Result<(), _> = Err(std::env::VarError::NotPresent); // Some random error type
    /// let clap_error = x.map_err(PluginWrapperError::with_severity(CLAP_LOG_PLUGIN_MISBEHAVING));
    ///
    /// assert_eq!(clap_error.unwrap_err().severity(), CLAP_LOG_PLUGIN_MISBEHAVING);
    /// ```
    #[inline]
    pub fn with_severity<E: 'static + Error>(
        severity: clap_log_severity,
    ) -> impl Fn(E) -> PluginWrapperError {
        move |e| PluginWrapperError::Error(severity, Box::new(e))
    }
}

impl From<PluginError> for PluginWrapperError {
    #[inline]
    fn from(e: PluginError) -> Self {
        PluginWrapperError::Plugin(e)
    }
}

impl Display for PluginWrapperError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        use PluginWrapperError::*;

        match self {
            NullPluginInstance => {
                f.write_str("Plugin method was called with null clap_plugin pointer")
            }
            AlreadyDestroyed => f.write_str(
                "Plugin instance was already destroyed (clap_plugin.plugin_data pointer is null)",
            ),
            PluginCalledDuringInitialization => {
                f.write_str("Host tried to call plugin function during initialization")
            }
            InitializationAlreadyFailed => f.write_str("Plugin initialization has already failed"),
            AlreadyInitialized => f.write_str("Plugin is already initialized"),
            Destroying => f.write_str("Plugin is being destroyed"),
            NulPtr(ptr_name) => {
                write!(f, "Plugin method was called with null {ptr_name} pointer")
            }
            InvalidParameter(p) => {
                write!(f, "Received invalid parameter '{p}'")
            }
            UninitializedPlugin => f.write_str("Plugin was not properly initialized before use"),
            ActivatedPlugin => f.write_str("Plugin was already activated"),
            DeactivatedPlugin => {
                f.write_str("Plugin was not activated before calling a audio-thread method")
            }
            DeactivationRequiredForFunction(function) => write!(
                f,
                "Host attempted to call '{function}' while plugin was still active"
            ),
            StringEncoding(e) => {
                write!(
                    f,
                    "Encountered string containing invalid UTF-8 at position {}.",
                    e.valid_up_to()
                )
            }
            InvalidCString(e) => {
                write!(
                    f,
                    "Encountered string containing a NUL byte at position {}.",
                    e.nul_position()
                )
            }
            ErrorFormatError(e) => {
                write!(f, "Error while formatting plugin error: '{e}'")
            }
            Plugin(e) => Display::fmt(&e, f),
            Error(_, e) => Display::fmt(e, f),
            Message(_, msg) => f.write_str(msg),
            Panic => f.write_str("Plugin panicked"),
        }
    }
}

impl Error for PluginWrapperError {}