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
//! Types and handles for plugins to interact with the host.

use clack_common::extensions::{Extension, HostExtensionSide, RawExtension};
use clack_common::utils::ClapVersion;
use clap_sys::host::clap_host;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;

/// Various information about the host, provided at plugin instantiation time.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct HostInfo<'a> {
    raw: NonNull<clap_host>,
    _lifetime: PhantomData<&'a clap_host>,
}

impl<'a> HostInfo<'a> {
    /// Creates a new [`HostInfo`] type from a given raw, C FFI compatible pointer.
    ///
    /// # Safety
    /// Pointer must be valid for the duration of the `'a` lifetime. Moreover, the contents of
    /// the `clap_host` struct must all also be valid.
    #[inline]
    pub const unsafe fn from_raw(raw: NonNull<clap_host>) -> Self {
        Self {
            raw,
            _lifetime: PhantomData,
        }
    }

    /// The [`ClapVersion`] the host uses.
    #[inline]
    pub const fn clap_version(&self) -> ClapVersion {
        ClapVersion::from_raw(self.as_raw().clap_version)
    }

    /// A user-friendly name for the host (e.g. "Bitwig Studio").
    ///
    /// This should always be set by the host.
    pub const fn name(&self) -> Option<&'a CStr> {
        let Some(ptr) = NonNull::new(self.as_raw().name as *mut _) else {
            return None;
        };
        // SAFETY: this type ensures the pointers are valid
        Some(unsafe { CStr::from_ptr(ptr.as_ptr()) })
    }

    /// The host's vendor (e.g. "Bitwig GmbH").
    ///
    /// This field is optional.
    pub const fn vendor(&self) -> Option<&'a CStr> {
        let Some(ptr) = NonNull::new(self.as_raw().vendor as *mut _) else {
            return None;
        };
        // SAFETY: this type ensures the pointers are valid
        Some(unsafe { CStr::from_ptr(ptr.as_ptr()) })
    }

    /// A URL to the host's webpage.
    ///
    /// This field is optional.
    pub const fn url(&self) -> Option<&'a CStr> {
        let Some(ptr) = NonNull::new(self.as_raw().url as *mut _) else {
            return None;
        };
        // SAFETY: this type ensures the pointers are valid
        Some(unsafe { CStr::from_ptr(ptr.as_ptr()) })
    }

    /// A version string for the host (e.g. "4.3").
    ///
    /// This should always be set by the host.
    pub const fn version(&self) -> Option<&'a CStr> {
        let Some(ptr) = NonNull::new(self.as_raw().version as *mut _) else {
            return None;
        };
        // SAFETY: this type ensures the pointers are valid
        Some(unsafe { CStr::from_ptr(ptr.as_ptr()) })
    }

    /// Retrieves the host's pointer to the given [extension type](Extension) `E`.
    ///
    /// This returns `None` if the host does not support the given extension.
    ///
    /// # Example
    ///
    /// ```
    /// use clack_extensions::log::{HostLog, LogSeverity};
    /// use clack_plugin::host::HostInfo;
    ///
    /// # fn foo(info: HostInfo) {
    /// let info: HostInfo = /* ... */
    /// # info;
    /// if let Some(log) = info.get_extension::<HostLog>() {
    ///     // The log extension is supported by this host
    /// } else {
    ///     // The log extension is not supported by this host
    /// }
    /// # }
    /// ```
    pub fn get_extension<E: Extension<ExtensionSide = HostExtensionSide>>(&self) -> Option<E> {
        let identifier = const { E::IDENTIFIERS.first().unwrap() };
        // SAFETY: this type ensures the function pointers are valid
        let ext = unsafe { self.as_raw().get_extension?(self.raw.as_ptr(), identifier.as_ptr()) };

        let ext = NonNull::new(ext as *mut _)?;
        // SAFETY: The CLAP spec guarantees that the extension lives as long as the instance.
        let raw = unsafe { RawExtension::from_raw_host_extension(ext, self.raw) };

        // SAFETY: pointer comes from the associated E::IDENTIFIER.
        unsafe { Some(E::from_raw(raw)) }
    }

    /// # Safety
    /// Some functions exposed by [`HostSharedHandle`] cannot be called until plugin is initializing
    #[inline]
    pub(crate) const unsafe fn to_handle(self) -> HostSharedHandle<'a> {
        HostSharedHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }

    /// Returns a raw, C FFI-compatible reference to the host handle.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_host {
        // SAFETY: this type ensures the raw pointer is valid
        unsafe { self.raw.as_ref() }
    }
}

/// A thread-safe handle to the host.
///
/// This can be used to fetch information about the host, scan available extensions, or perform
/// requests to the host.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct HostSharedHandle<'a> {
    raw: NonNull<clap_host>,
    _lifetime: PhantomData<&'a clap_host>,
}

// SAFETY: this type only safely exposes the thread-safe operations of clap_host
unsafe impl Send for HostSharedHandle<'_> {}
// SAFETY: this type only safely exposes the thread-safe operations of clap_host
unsafe impl Sync for HostSharedHandle<'_> {}

impl<'a> HostSharedHandle<'a> {
    /// Returns the host's information.
    #[inline]
    pub const fn info(&self) -> HostInfo<'a> {
        HostInfo {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }

    /// Returns a raw, C FFI-compatible reference to the host handle.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_host {
        // SAFETY: this type enforces the pointer is valid for 'a
        unsafe { self.raw.as_ref() }
    }

    /// Returns this handle as a reference to the host's information.
    #[inline]
    pub const fn as_info(&self) -> &HostInfo<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &*(self as *const Self as *const HostInfo<'a>) }
    }

    /// Requests the host to [deactivate](crate::plugin::PluginAudioProcessor::deactivate) and then
    /// [re-activate](crate::plugin::PluginAudioProcessor::activate) the plugin.
    /// The operation may be delayed by the host.
    #[inline]
    pub fn request_restart(&self) {
        if let Some(request_restart) = self.as_raw().request_restart {
            // SAFETY: field is guaranteed to be correct by host. Lifetime is enforced by 'a
            unsafe { request_restart(self.raw.as_ptr()) }
        }
    }

    /// Requests the host to [activate](crate::plugin::PluginAudioProcessor::activate) the plugin,
    /// and start audio processing.
    /// This is useful if you have external IO and need to wake the plugin up from "sleep".
    #[inline]
    pub fn request_process(&self) {
        if let Some(request_process) = self.as_raw().request_process {
            // SAFETY: field is guaranteed to be correct by host. Lifetime is enforced by 'a
            unsafe { request_process(self.raw.as_ptr()) }
        }
    }

    /// Requests the host to schedule a call to the
    /// [on_main_thread](crate::plugin::PluginMainThread::on_main_thread) method on the main thread.
    #[inline]
    pub fn request_callback(&self) {
        if let Some(request_callback) = self.as_raw().request_callback {
            // SAFETY: field is guaranteed to be correct by host. Lifetime is enforced by 'a
            unsafe { request_callback(self.raw.as_ptr()) }
        }
    }

    /// Unsafely creates a main-thread host handle from this thread-safe handle.
    ///
    /// # Safety
    ///
    /// Callers *MUST* ensure this is only called on the main thread, and that they have exclusive (&mut) access.
    #[inline]
    pub const unsafe fn as_main_thread_unchecked(&self) -> HostMainThreadHandle<'a> {
        HostMainThreadHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }

    /// Unsafely creates an audio-processor host handle from this thread-safe handle.
    ///
    /// # Safety
    ///
    /// Callers *MUST* ensure this is only called on the audio thread, and that they have exclusive (&mut) access.
    #[inline]
    pub const unsafe fn as_audio_processor_unchecked(&self) -> HostAudioProcessorHandle<'a> {
        HostAudioProcessorHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }

    /// Safely dereferences a [`RawExtension`] pointer produced by this host.
    ///
    /// See the documentation of the [`RawExtension`] type for more information about how this works
    /// internally.
    ///
    /// # Panics
    ///
    /// This method will panic if the given extension pointer does not match the host
    /// this handle came from.
    #[inline]
    pub fn use_extension<E: Sized>(&self, extension: &RawExtension<HostExtensionSide, E>) -> &'a E {
        if self.raw != extension.host_ptr() {
            mismatched_instance();
        }

        // SAFETY: the RawExtension type enforces the pointee is valid for as long as the matching
        // instance is still alive.
        unsafe { extension.as_ptr().as_ref() }
    }

    /// Creates a [`HostSharedHandle`] from a raw `clap_host` pointer.
    ///
    /// # Safety
    ///
    ///
    #[inline]
    pub unsafe fn from_raw(raw: NonNull<clap_host>) -> Self {
        Self {
            raw,
            _lifetime: PhantomData,
        }
    }

    /// Returns a [`HostSharedHandle`] that points to the same host, but with an arbitrary lifetime
    /// instead of the host's.
    ///
    /// This can be useful in situations where you need to use host callbacks in a container that
    /// does not let you use proper lifetimes, but you can still guarantee that host callbacks won't
    /// be called after the host's `'a` lifetime.
    ///
    /// # Safety
    ///
    /// The returned handle's lifetime is completely meaningless here.
    /// Proper care muse be taken in order to ensure *no* methods on this type are used beyond the
    /// original host `'a` lifetime.
    #[inline]
    pub unsafe fn with_arbitrary_lifetime<'b>(&self) -> HostSharedHandle<'b> {
        HostSharedHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }
}

impl<'a> From<HostSharedHandle<'a>> for HostInfo<'a> {
    #[inline]
    fn from(h: HostSharedHandle<'a>) -> Self {
        h.info()
    }
}

impl<'a> Deref for HostSharedHandle<'a> {
    type Target = HostInfo<'a>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_info()
    }
}

/// A main-thread handle to the host.
///
/// This can be used to perform requests to the host that can only be made from the main thread.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct HostMainThreadHandle<'a> {
    raw: NonNull<clap_host>,
    _lifetime: PhantomData<&'a clap_host>,
}

impl<'a> HostMainThreadHandle<'a> {
    /// Gets a thread-safe host handle from this handle.
    #[inline]
    pub const fn shared(&self) -> HostSharedHandle<'a> {
        HostSharedHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }

    /// Returns this handle as a reference to a thread-safe host handle from this handle.
    #[inline]
    pub const fn as_shared(&self) -> &HostSharedHandle<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &*(self as *const Self as *const HostSharedHandle<'a>) }
    }

    /// Returns a raw, C FFI-compatible reference to the host handle.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_host {
        // SAFETY: this type enforces the pointer is valid for 'a
        unsafe { self.raw.as_ref() }
    }

    /// Creates a [`HostMainThreadHandle`] from a raw `clap_host` pointer.
    ///
    /// # Safety
    ///
    ///
    #[inline]
    pub unsafe fn from_raw(raw: NonNull<clap_host>) -> Self {
        Self {
            raw,
            _lifetime: PhantomData,
        }
    }

    /// Returns a [`HostMainThreadHandle`] that points to the same host, but with an arbitrary lifetime
    /// instead of the host's.
    ///
    /// This can be useful in situations where you need to use host callbacks in a container that
    /// does not let you use proper lifetimes, but you can still guarantee that host callbacks won't
    /// be called after the host's `'a` lifetime.
    ///
    /// # Safety
    ///
    /// The returned handle's lifetime is completely meaningless here.
    /// Proper care muse be taken in order to ensure *no* methods on this type are used beyond the
    /// original host `'a` lifetime.
    #[inline]
    pub unsafe fn with_arbitrary_lifetime<'b>(&self) -> HostMainThreadHandle<'b> {
        HostMainThreadHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }
}

impl<'a> From<HostMainThreadHandle<'a>> for HostSharedHandle<'a> {
    #[inline]
    fn from(h: HostMainThreadHandle<'a>) -> Self {
        h.shared()
    }
}

impl<'a> Deref for HostMainThreadHandle<'a> {
    type Target = HostSharedHandle<'a>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_shared()
    }
}

/// An audio-processor handle to the host.
///
/// This can be used to perform requests to the host that can only be made from the audio thread.
#[repr(transparent)]
pub struct HostAudioProcessorHandle<'a> {
    raw: NonNull<clap_host>,
    _lifetime: PhantomData<&'a clap_host>,
}

// SAFETY: this type only exposes the audio-thread-safe (Send) operation of clap_host
unsafe impl Send for HostAudioProcessorHandle<'_> {}

impl<'a> HostAudioProcessorHandle<'a> {
    /// Gets a thread-safe host handle from this handle.
    #[inline]
    pub const fn shared(&self) -> HostSharedHandle<'a> {
        HostSharedHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }

    /// Returns a raw, C FFI-compatible reference to the host handle.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_host {
        // SAFETY: this type enforces the pointer is valid for 'a
        unsafe { self.raw.as_ref() }
    }

    /// Returns this handle as a reference to a thread-safe host handle from this handle.
    #[inline]
    pub const fn as_shared(&self) -> &HostSharedHandle<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &*(self as *const Self as *const HostSharedHandle<'a>) }
    }

    /// Creates a [`HostAudioProcessorHandle`] from a raw `clap_host` pointer.
    ///
    /// # Safety
    ///
    ///
    #[inline]
    pub unsafe fn from_raw(raw: NonNull<clap_host>) -> Self {
        Self {
            raw,
            _lifetime: PhantomData,
        }
    }

    /// Returns a [`HostAudioProcessorHandle`] that points to the same host, but with an arbitrary lifetime
    /// instead of the host's.
    ///
    /// This can be useful in situations where you need to use host callbacks in a container that
    /// does not let you use proper lifetimes, but you can still guarantee that host callbacks won't
    /// be called after the host's `'a` lifetime.
    ///
    /// # Safety
    ///
    /// The returned handle's lifetime is completely meaningless here.
    /// Proper care muse be taken in order to ensure *no* methods on this type are used beyond the
    /// original host `'a` lifetime.
    #[inline]
    pub unsafe fn with_arbitrary_lifetime<'b>(&self) -> HostAudioProcessorHandle<'b> {
        HostAudioProcessorHandle {
            raw: self.raw,
            _lifetime: PhantomData,
        }
    }
}

impl<'a> From<HostAudioProcessorHandle<'a>> for HostSharedHandle<'a> {
    #[inline]
    fn from(h: HostAudioProcessorHandle<'a>) -> Self {
        h.shared()
    }
}

impl<'a> Deref for HostAudioProcessorHandle<'a> {
    type Target = HostSharedHandle<'a>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_shared()
    }
}

#[inline(never)]
#[cold]
const fn mismatched_instance() -> ! {
    panic!("Given host handle doesn't match the extension pointer it was used on.")
}