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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Types to expose and customize a CLAP file's entry.
//!
//! On Windows and Linux (and other non-macOS UNIXes), CLAP plugins are distributed as prebuilt
//! dynamically-loaded libraries (usually `.dll` or `.so` files) with a `.clap` extension.
//! They expose a single [`EntryDescriptor`], which, once initialized, acts as the entry
//! point for the host to read into the library file.
//!
//! On macOS, CLAP plugins are distributed as a standard
//! [bundle](https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/AboutBundles/AboutBundles.html),
//! which contains the aforementioned dynamically-loaded libraries as its executable file.
//!
//! A CLAP's [`Entry`] is the only exposed symbol in the library. Once
//! [initialized](Entry::new), its role is to expose a number of [factories](Factory), which are
//! singletons implementing various functionalities. The most relevant is the [`PluginFactory`](crate::factory::plugin::PluginFactoryImpl),
//! which allows to list and instantiate plugins. See the [`factory`](crate::factory) module
//! documentation to learn more about factories.
//!
//! An entry type can then be exposed to the host reading the library file by using the
//! [`clack_export_entry`](crate::clack_export_entry) macro.
//!
//! See the [`Entry`] trait documentation for information and examples on how to implement your own
//! entry type, or see the provided [`SinglePluginEntry`] convenience type if you only need to
//! expose a single plugin type to the host.

use crate::extensions::wrapper::handle_panic;
use crate::factory::{Factory, FactoryImplementation};
use std::error::Error;
use std::ffi::{CStr, c_void};
use std::fmt::{Display, Formatter};
use std::hint::unreachable_unchecked;
use std::panic::{AssertUnwindSafe, UnwindSafe};
use std::ptr::NonNull;
use std::sync::Mutex;

pub use clack_common::entry::*;

mod single;

pub use single::{DefaultPluginFactory, SinglePluginEntry};

/// A prelude that's helpful for implementing custom [`Entry`] and [`PluginFactory`](crate::factory::plugin::PluginFactoryImpl) types.
pub mod prelude {
    pub use crate::{
        entry::{Entry, EntryDescriptor, EntryFactories, EntryLoadError, SinglePluginEntry},
        factory::{
            Factory,
            plugin::{PluginFactoryImpl, PluginFactoryWrapper},
        },
        host::HostInfo,
        plugin::{PluginDescriptor, PluginInstance},
    };
}

/// A CLAP file's entry point.
///
/// This trait can be implemented by a custom, user-provided type in order to customize the library's
/// entrypoint behavior. The [`clack_export_entry!`](crate::clack_export_entry) macro can then be
/// used to set that type as the library's entry point to be discovered and loaded by hosts.
///
/// If you only care about the entry exposing a single plugin, you may use the [`SinglePluginEntry`]
/// type instead of making your own.
///
/// To learn more about entries, refer to the [module documentation](self).
///
/// # Example
///
/// The following example shows how to create a custom entry and plugin factory that exposes
/// two different plugins.
///
/// In this example, the second plugin also needs some custom initialization logic to create a
/// (non-realtime-safe) channel between the `Shared` struct and the `MainThread` struct. This is
/// also not possible to do with [`SinglePluginEntry`], since only allows for pure functions.
///
/// ```
/// use std::ffi::CStr;
/// use std::sync::mpsc::{channel, Receiver, Sender};
/// use clack_plugin::entry::prelude::*;
/// use clack_plugin::prelude::*;
///
/// pub struct MyFirstPlugin;
/// pub struct MySecondPlugin;
///
/// impl Plugin for MyFirstPlugin {
///     type AudioProcessor<'a> = ();
///     type Shared<'a> = ();
///     type MainThread<'a> = ();
/// }
///
/// impl Plugin for MySecondPlugin {
///     type AudioProcessor<'a> = ();
///     type Shared<'a> = MySecondPluginShared;
///     type MainThread<'a> = MySecondPluginMainThread;
/// }
///
/// // For the sake of this example, this plugin just needs to share Strings around.
/// pub struct MySecondPluginShared(Sender<String>);
/// pub struct MySecondPluginMainThread(Receiver<String>);
///
/// impl PluginShared<'_> for MySecondPluginShared {}
/// impl PluginMainThread<'_, MySecondPluginShared> for MySecondPluginMainThread {}
///
/// // Our entry implementation
///
/// pub struct MyEntry {
///     plugin_factory: PluginFactoryWrapper<MyPluginFactory>
/// }
///
/// impl Entry for MyEntry {
///     fn new(bundle_path: Option<&CStr>) -> Result<Self, EntryLoadError> {
///         // Initialize the factory and its wrapper
///         Ok(Self { plugin_factory: PluginFactoryWrapper::new(MyPluginFactory::new()) })
///     }
///
///     fn declare_factories<'a>(&'a self, builder: &mut EntryFactories<'a>) {
///         // Expose MyPluginFactory as an available factory, using the wrapper
///         builder.register_factory(&self.plugin_factory);
///     }
/// }
///
/// // Our factory holds the descriptors for both of our plugins
/// pub struct MyPluginFactory {
///     first_plugin: PluginDescriptor,
///     second_plugin: PluginDescriptor,
/// }
///
/// impl MyPluginFactory {
///     pub fn new() -> Self {
///         Self {
///             first_plugin: PluginDescriptor::new("my.plugin.first", "My first plugin"),
///             second_plugin: PluginDescriptor::new("my.plugin.second", "My second plugin"),
///         }
///     }
/// }
///
/// impl PluginFactoryImpl for MyPluginFactory {
///     fn plugin_count(&self) -> u32 {
///         2 // We have 2 plugins to expose to the host
///     }
///
///     // Gets the plugin descriptor matching the given index.
///     // It doesn't matter much which plugin has which index,
///     // but each of our plugins must have a unique one.
///     fn plugin_descriptor(&self, index: u32) -> Option<&PluginDescriptor> {
///         match index {
///             0 => Some(&self.first_plugin),
///             1 => Some(&self.second_plugin),
///             _ => None,
///         }
///     }
///
///     // Called when the host desires to create a new instance of one of our plugins.
///     // Which plugin it is, is determined by the given plugin_id.
///     fn create_plugin<'a>(
///         &'a self,
///         host_info: HostInfo<'a>,
///         plugin_id: &CStr,
///     ) -> Option<PluginInstance<'a>> {
///         if plugin_id == self.first_plugin.id().unwrap_or_default() {
///             // We can use the PluginInstance type to easily make a new instance of a given
///             // plugin type.
///             Some(PluginInstance::new::<MyFirstPlugin>(
///                 host_info,
///                 &self.first_plugin,
///                 |_host| Ok(()) /* Create the shared struct */,
///                 |_host, _shared| Ok(()) /* Create the main thread struct */,
///             ))
///         } else if plugin_id == self.second_plugin.id().unwrap_or_default() {
///             let (tx, rx) = channel();
///
///             Some(PluginInstance::new::<MySecondPlugin>(
///                 host_info,
///                 &self.second_plugin,
///                 |_host| Ok(MySecondPluginShared(tx)) /* Create the shared struct */,
///                 |_host, _shared| Ok(MySecondPluginMainThread(rx)) /* Create the main thread struct */,
///             ))
///         } else {
///             None
///         }
///     }
/// }
///
/// clack_export_entry!(MyEntry);
/// ```
pub trait Entry: Sized + Send + Sync + 'static {
    /// Instantiates the entry.
    ///
    /// The path of the bundle file this entry was loaded from is also given by the host, in case
    /// extra neighboring files need to be loaded.
    ///
    /// # Host Compatibility Notes
    ///
    /// Some hosts might misbehave and pass an empty path to this function, or might even forget
    /// to properly initialize the entry before trying to get factories from it.
    ///
    /// In those cases, Clack will call this function to instantiate the entry "just-in-time", but
    /// `None` will be passed to this function instead of the path.
    ///
    /// This is still invalid host behavior according to the CLAP specification. Therefore, it is
    /// completely valid for implementations of this function to always return [`EntryLoadError`]
    /// when `None` is passed instead of a path.
    ///
    /// However, this allows plugins that may not need the bundle file path to initialize, and at
    /// least partially recover.
    ///
    /// # Platform Compatibility notes
    ///
    /// On Windows and Linux, this `bundle_path` is the one of the dynamic library file this entry
    /// was loaded from.
    ///
    /// On macOS, `bundle_path` should be the path of the actual bundle directory the library
    /// this entry was loaded from, resides in.
    ///
    /// # Errors
    ///
    /// This returns [`EntryLoadError`] if any error occurred during instantiation.
    fn new(bundle_path: Option<&CStr>) -> Result<Self, EntryLoadError>;

    /// Declares the factories this entry exposes to the host, by registering them to the given
    /// [`EntryFactories`] builder.
    ///
    /// See the [`EntryFactories`] documentation for more information.
    fn declare_factories<'a>(&'a self, builder: &mut EntryFactories<'a>);
}

/// An error indicating an entry has failed loading.
///
/// This error is returned by [`Entry::new`] when it fails.
#[derive(Copy, Clone, Debug)]
pub struct EntryLoadError;

impl Display for EntryLoadError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("Entry failed to load.")
    }
}

impl Error for EntryLoadError {}

/// Exposes a given [`Entry`] type to the host as *the* library's entry point.
///
/// This macro exports the standard CLAP symbol `clap_entry`, set to an [`EntryDescriptor`] which
/// relies on the given `entry_type` for behavior.
///
/// Note this means you cannot call this macro twice in the same executable, as the produced symbols
/// will conflict.
///
/// # Example
///
/// This example exposes a custom `MyEntry` entry type. See the [`Entry`] trait documentation for
/// an example of how to actually implement it.
///
/// ```
/// use std::ffi::CStr;
/// use clack_plugin::entry::prelude::*;
/// use clack_plugin::prelude::*;
///
/// pub struct MyEntry;
///
/// impl Entry for MyEntry {
/// #    fn new(bundle_path: Option<&CStr>) -> Result<Self, EntryLoadError> {
/// #        unreachable!()
/// #    }
///     /* ... */
/// #    fn declare_factories<'a>(&'a self, builder: &mut EntryFactories<'a>) {
/// #        unreachable!()
/// #    }
/// }
///
/// // The host will now see and use this entry.
/// clack_export_entry!(MyEntry);
/// ```
#[macro_export]
macro_rules! clack_export_entry {
    ($entry_type:ty, $entry_lambda:expr) => {
        #[allow(non_upper_case_globals, missing_docs)]
        #[allow(unsafe_code)]
        #[allow(warnings, unused)]
        #[unsafe(no_mangle)]
        pub static clap_entry: $crate::entry::EntryDescriptor =
            $crate::clack_entry!($entry_type, $entry_lambda);
    };
    ($entry_type:ty) => {
        #[allow(non_upper_case_globals, missing_docs)]
        #[allow(unsafe_code)]
        #[allow(warnings, unused)]
        #[unsafe(no_mangle)]
        pub static clap_entry: $crate::entry::EntryDescriptor = $crate::clack_entry!($entry_type);
    };
}

/// Produces an [`EntryDescriptor`] value from a given [`Entry`] type, but without exposing it.
///
/// This can be useful as an alternative to the usual
/// [`clack_export_entry`](crate::clack_export_entry) macro if you do not want or need to export the
/// given entry, and just need an [`EntryDescriptor`].
#[macro_export]
macro_rules! clack_entry {
    ($entry_type:ty, $entry_lambda:expr) => {
        ({
            #[allow(unsafe_code)]
            const fn _entry() -> $crate::entry::EntryDescriptor {
                static HOLDER: $crate::entry::EntryHolder<$entry_type> =
                    $crate::entry::EntryHolder::new();

                unsafe extern "C" fn init(plugin_path: *const ::core::ffi::c_char) -> bool {
                    HOLDER.init_with(plugin_path, $entry_lambda)
                }

                unsafe extern "C" fn deinit() {
                    HOLDER.de_init()
                }

                unsafe extern "C" fn get_factory(
                    identifier: *const ::core::ffi::c_char,
                ) -> *const ::core::ffi::c_void {
                    HOLDER.get_factory_with(identifier, $entry_lambda)
                }

                $crate::entry::EntryDescriptor {
                    clap_version: $crate::utils::ClapVersion::CURRENT.to_raw(),
                    init: Some(init),
                    deinit: Some(deinit),
                    get_factory: Some(get_factory),
                }
            }
            _entry()
        })
    };
    ($entry_type:ty) => {
        ({
            #[allow(unsafe_code)]
            const fn _entry() -> $crate::entry::EntryDescriptor {
                static HOLDER: $crate::entry::EntryHolder<$entry_type> =
                    $crate::entry::EntryHolder::new();

                unsafe extern "C" fn init(plugin_path: *const ::core::ffi::c_char) -> bool {
                    HOLDER.init(plugin_path)
                }

                unsafe extern "C" fn deinit() {
                    HOLDER.de_init()
                }

                unsafe extern "C" fn get_factory(
                    identifier: *const ::core::ffi::c_char,
                ) -> *const ::core::ffi::c_void {
                    HOLDER.get_factory(identifier)
                }

                $crate::entry::EntryDescriptor {
                    clap_version: $crate::utils::ClapVersion::CURRENT.to_raw(),
                    init: Some(init),
                    deinit: Some(deinit),
                    get_factory: Some(get_factory),
                }
            }
            _entry()
        })
    };
}

/// A lightweight collection of all the factories a given plugin entry supports.
///
/// [`Entry`] implementations are expected to declare the factories they support to the host using
/// the [`register_factory`](EntryFactories::register_factory) method.
pub struct EntryFactories<'a> {
    found: Option<NonNull<c_void>>,
    requested: &'a [&'a CStr],
}

impl<'a> EntryFactories<'a> {
    #[doc(hidden)]
    #[inline]
    pub fn new(requested: &'a [&'a CStr]) -> Self {
        Self {
            found: None,
            requested,
        }
    }

    #[doc(hidden)]
    #[inline]
    pub fn found(&self) -> Option<NonNull<c_void>> {
        self.found
    }

    /// Adds a given factory implementation to the list of factories this entry supports.
    ///
    /// This method returns the factory itself, allowing for easy method chaining and a builder-like
    /// usage pattern.
    ///
    /// See [`Entry`]'s documentation for an example.
    pub fn register_factory<F: FactoryImplementation<'a>>(&mut self, factory: &'a F) -> &mut Self {
        if self.found.is_some() {
            return self;
        }

        for requested in self.requested {
            if F::Factory::IDENTIFIERS.contains(requested) {
                self.found = Some(factory.wrapper().as_raw().as_raw().cast());
                break;
            }
        }

        self
    }
}

enum EntryHolderInner<E> {
    Initialized { reference_count: usize, entry: E },
    Uninitialized,
}

#[doc(hidden)]
pub struct EntryHolder<E: Entry> {
    inner: Mutex<EntryHolderInner<E>>,
}

use crate::entry::EntryHolderInner::*;

#[doc(hidden)]
impl<E: Entry> EntryHolder<E> {
    #[allow(clippy::new_without_default)] // This is actually a private type
    pub const fn new() -> Self {
        Self {
            inner: Mutex::new(Uninitialized),
        }
    }

    /// # Safety
    ///
    /// Users *must* ensure this is called at least once before any other method, and that
    /// `plugin_path` points to a valid, NULL-terminated C string.
    #[inline]
    pub unsafe fn init(&self, plugin_path: *const core::ffi::c_char) -> bool {
        self.init_with(plugin_path, |p| E::new(p))
    }

    /// # Safety
    ///
    /// Users *must* ensure this is called at least once before any other method, and that
    /// `plugin_path` points to a valid, NULL-terminated C string.
    pub unsafe fn init_with(
        &self,
        plugin_path: *const core::ffi::c_char,
        entry_factory: impl FnOnce(Option<&CStr>) -> Result<E, EntryLoadError> + UnwindSafe,
    ) -> bool {
        let Ok(Ok(mut inner)) = handle_panic(|| self.inner.lock()) else {
            // A poisoned lock means init() panicked, so we consider the entry unusable.
            // Same if lock() itself panicked.
            return false;
        };

        match &mut *inner {
            Initialized {
                reference_count, ..
            } => {
                *reference_count += 1;
                true
            }
            Uninitialized => {
                let plugin_path = CStr::from_ptr(plugin_path);
                let plugin_path = (!plugin_path.is_empty()).then_some(plugin_path);
                let entry = handle_panic(|| entry_factory(plugin_path));

                if let Ok(Ok(entry)) = entry {
                    *inner = Initialized {
                        entry,
                        reference_count: 1,
                    };
                    true
                } else {
                    false
                }
            }
        }
    }

    /// # Safety
    ///
    /// Users must *only* call this after they are done with the whole entry.
    pub unsafe fn de_init(&self) {
        let Ok(mut inner) = self.inner.lock() else {
            return;
        };

        if let Initialized {
            reference_count, ..
        } = &mut *inner
        {
            if *reference_count > 1 {
                *reference_count -= 1;
            } else {
                let _ = handle_panic(AssertUnwindSafe(|| *inner = Uninitialized));
            }
        }
    }

    /// # Safety
    ///
    /// Users *must* ensure this is called at least once before any other method, and that
    /// `plugin_path` points to a valid, NULL-terminated C string.
    #[inline]
    pub unsafe fn get_factory(&self, identifier: *const core::ffi::c_char) -> *const c_void {
        self.get_factory_with(identifier, |p| E::new(p))
    }

    /// # Safety
    ///
    /// This must only be called between calls to init and de_init, and identifier must point to a
    /// valid, NULL-terminated C string.
    pub unsafe fn get_factory_with(
        &self,
        identifier: *const core::ffi::c_char,
        entry_factory: impl FnOnce(Option<&CStr>) -> Result<E, EntryLoadError> + UnwindSafe,
    ) -> *const c_void {
        if identifier.is_null() {
            return core::ptr::null();
        }

        let Ok(mut inner) = self.inner.lock() else {
            return core::ptr::null();
        };

        let entry = match &*inner {
            Initialized { entry, .. } => entry,
            Uninitialized => {
                let entry = handle_panic(|| entry_factory(None));

                if let Ok(Ok(entry)) = entry {
                    *inner = Initialized {
                        entry,
                        // This will leak the entry if deinit() is not called afterward, but it's better than
                        // straight-up failing to load.
                        reference_count: 1,
                    };

                    let Initialized { entry, .. } = &*inner else {
                        // SAFETY: we just initialized it to Initialized above
                        unsafe {
                            unreachable_unchecked();
                        }
                    };

                    entry
                } else {
                    return core::ptr::null();
                }
            }
        };

        let identifier = CStr::from_ptr(identifier);

        let result = handle_panic(AssertUnwindSafe(|| {
            let identifiers = &[identifier];
            let mut builder = EntryFactories::new(identifiers);
            entry.declare_factories(&mut builder);
            builder.found()
        }));

        match result {
            Ok(Some(found)) => found.as_ptr(),
            _ => core::ptr::null(),
        }
    }
}