Skip to main content

plughost_core/
plugin.rs

1use std::fmt;
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5
6/// Native plugin ABI used for discovery and loading.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum PluginFormat {
10    /// Steinberg VST 3.
11    Vst3,
12    /// Audio Unit (macOS), v2 or v3.
13    AudioUnit,
14    /// CLever Audio Plug-in (CLAP).
15    Clap,
16}
17
18/// A plugin class identifier in its format's canonical form, so that two IDs of one class
19/// compare equal however they were written. It comes with its format in a [`PluginId`]. For VST3 it is the 32-digit hexadecimal class ID in
20/// the form `.vstpreset` files use, and for Audio Units the component type, subtype, and
21/// manufacturer codes as 24 hexadecimal digits; both are kept in upper case. For CLAP it is the
22/// plugin ID as given.
23#[derive(Clone, Debug, PartialEq, Eq, Hash)]
24pub struct ClassId(String);
25
26impl ClassId {
27    /// The canonical form of `id` in `format`: VST3 and Audio Unit IDs in upper case, CLAP IDs as
28    /// they are. The ID is not otherwise checked; one no plugin has fails when it is loaded.
29    fn new(format: PluginFormat, id: impl Into<String>) -> ClassId {
30        let mut id = id.into();
31        match format {
32            PluginFormat::Vst3 | PluginFormat::AudioUnit => id.make_ascii_uppercase(),
33            PluginFormat::Clap => {}
34        }
35        ClassId(id)
36    }
37
38    /// The identifier text.
39    pub fn as_str(&self) -> &str {
40        &self.0
41    }
42}
43
44impl fmt::Display for ClassId {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        f.write_str(&self.0)
47    }
48}
49
50/// The identity of a plugin class, independent of where it is installed: its format and class
51/// ID. Store it, not a path, with the work that uses the plugin, and find the installed class
52/// again with the scanner's `Catalog::resolve`.
53///
54/// It serializes with serde as a `format` (`"vst3"`, `"audio-unit"` or `"clap"`) and a
55/// `class_id`; deserializing puts the ID in its canonical form.
56#[derive(Clone, Debug, PartialEq, Eq, Hash)]
57pub struct PluginId {
58    format: PluginFormat,
59    class_id: ClassId,
60}
61
62impl PluginId {
63    /// The class `class_id` of `format`, with the ID in its canonical form (see [`ClassId`]).
64    #[must_use]
65    pub fn new(format: PluginFormat, class_id: impl Into<String>) -> PluginId {
66        PluginId {
67            format,
68            class_id: ClassId::new(format, class_id),
69        }
70    }
71
72    /// The class's native format.
73    pub fn format(&self) -> PluginFormat {
74        self.format
75    }
76
77    /// The class's identifier within its format.
78    pub fn class_id(&self) -> &ClassId {
79        &self.class_id
80    }
81}
82
83/// The persisted form of a [`PluginId`], with format names that do not depend on the Rust names
84/// of [`PluginFormat`]'s variants.
85#[derive(Serialize, Deserialize)]
86#[serde(rename = "PluginId")]
87struct PersistedId {
88    format: PersistedFormat,
89    class_id: String,
90}
91
92#[derive(Serialize, Deserialize)]
93enum PersistedFormat {
94    #[serde(rename = "vst3")]
95    Vst3,
96    #[serde(rename = "audio-unit")]
97    AudioUnit,
98    #[serde(rename = "clap")]
99    Clap,
100}
101
102impl Serialize for PluginId {
103    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
104        let format = match self.format {
105            PluginFormat::Vst3 => PersistedFormat::Vst3,
106            PluginFormat::AudioUnit => PersistedFormat::AudioUnit,
107            PluginFormat::Clap => PersistedFormat::Clap,
108        };
109        PersistedId {
110            format,
111            class_id: self.class_id.0.clone(),
112        }
113        .serialize(serializer)
114    }
115}
116
117impl<'de> Deserialize<'de> for PluginId {
118    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<PluginId, D::Error> {
119        let persisted = PersistedId::deserialize(deserializer)?;
120        let format = match persisted.format {
121            PersistedFormat::Vst3 => PluginFormat::Vst3,
122            PersistedFormat::AudioUnit => PluginFormat::AudioUnit,
123            PersistedFormat::Clap => PluginFormat::Clap,
124        };
125        Ok(PluginId::new(format, persisted.class_id))
126    }
127}
128
129/// A plugin class to load: its identity and where it is installed. VST3 and CLAP classes live in
130/// a bundle; Audio Units have none, the system registry finds them. Build it with the format's
131/// constructor, or take it from the scanner's catalog.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct PluginRef {
134    pub(crate) id: PluginId,
135    pub(crate) bundle: Option<PathBuf>,
136}
137
138impl PluginRef {
139    /// The VST3 class `class_id` in the `.vst3` bundle (or, on Windows, single-file module) at
140    /// `bundle`.
141    #[must_use]
142    pub fn vst3(bundle: impl Into<PathBuf>, class_id: impl Into<String>) -> PluginRef {
143        PluginRef {
144            id: PluginId::new(PluginFormat::Vst3, class_id),
145            bundle: Some(bundle.into()),
146        }
147    }
148
149    /// The CLAP plugin `class_id` in the `.clap` bundle at `bundle`.
150    #[must_use]
151    pub fn clap(bundle: impl Into<PathBuf>, class_id: impl Into<String>) -> PluginRef {
152        PluginRef {
153            id: PluginId::new(PluginFormat::Clap, class_id),
154            bundle: Some(bundle.into()),
155        }
156    }
157
158    /// The registered Audio Unit `class_id`.
159    #[must_use]
160    pub fn audio_unit(class_id: impl Into<String>) -> PluginRef {
161        PluginRef {
162            id: PluginId::new(PluginFormat::AudioUnit, class_id),
163            bundle: None,
164        }
165    }
166
167    /// The class's identity.
168    pub fn id(&self) -> &PluginId {
169        &self.id
170    }
171
172    /// The bundle that contains a VST3 or CLAP class; `None` for an Audio Unit.
173    pub fn bundle(&self) -> Option<&Path> {
174        self.bundle.as_deref()
175    }
176}
177
178/// Broad native classification used in discovery results.
179#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
180#[non_exhaustive]
181pub enum PluginKind {
182    /// An audio or MIDI effect.
183    Effect,
184    /// A sound-generating instrument.
185    Instrument,
186}
187
188/// A plugin class as its format describes it.
189#[derive(Clone, Debug, PartialEq, Eq)]
190#[non_exhaustive]
191pub struct PluginInfo {
192    /// The class's format and identifier.
193    pub id: PluginId,
194    /// Native plugin display name.
195    pub name: String,
196    /// Native vendor name, or empty when unavailable.
197    pub vendor: String,
198    /// Native plugin version string, or empty when unavailable.
199    pub version: String,
200    /// Native SDK version string, or empty when unavailable.
201    pub sdk_version: String,
202    /// Native effect or instrument classification.
203    pub kind: PluginKind,
204    /// Format sub-categories, for example `Fx` and `EQ`.
205    pub categories: Vec<String>,
206}
207
208impl PluginInfo {
209    /// A class with no vendor, version, SDK version or categories yet.
210    #[must_use]
211    pub fn new(id: PluginId, name: impl Into<String>, kind: PluginKind) -> PluginInfo {
212        PluginInfo {
213            id,
214            name: name.into(),
215            vendor: String::new(),
216            version: String::new(),
217            sdk_version: String::new(),
218            kind,
219            categories: Vec::new(),
220        }
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn hexadecimal_ids_compare_whatever_their_case() {
230        let lower = PluginId::new(PluginFormat::Vst3, "abcdef019182faeb4163747a44784c76");
231        let upper = PluginId::new(PluginFormat::Vst3, "ABCDEF019182FAEB4163747A44784C76");
232        assert_eq!(lower, upper);
233        assert_eq!(
234            lower.class_id().as_str(),
235            "ABCDEF019182FAEB4163747A44784C76"
236        );
237        assert_eq!(
238            PluginId::new(PluginFormat::AudioUnit, "6175667864656c796170706c"),
239            PluginId::new(PluginFormat::AudioUnit, "6175667864656C796170706C")
240        );
241        // CLAP IDs are case-sensitive.
242        assert_ne!(
243            PluginId::new(PluginFormat::Clap, "com.example.Delay"),
244            PluginId::new(PluginFormat::Clap, "com.example.delay")
245        );
246    }
247
248    #[test]
249    fn ids_persist_with_their_format_names_and_read_back_canonical() {
250        let id = PluginId::new(PluginFormat::AudioUnit, "6175667864656C796170706C");
251        assert_eq!(
252            serde_json::to_string(&id).unwrap(),
253            r#"{"format":"audio-unit","class_id":"6175667864656C796170706C"}"#
254        );
255        for (json, format) in [
256            (
257                r#"{"format":"vst3","class_id":"abcdef01"}"#,
258                PluginFormat::Vst3,
259            ),
260            (
261                r#"{"format":"audio-unit","class_id":"abcdef01"}"#,
262                PluginFormat::AudioUnit,
263            ),
264        ] {
265            assert_eq!(
266                serde_json::from_str::<PluginId>(json).unwrap(),
267                PluginId::new(format, "ABCDEF01")
268            );
269        }
270        let clap = PluginId::new(PluginFormat::Clap, "com.example.Delay");
271        let json = serde_json::to_string(&clap).unwrap();
272        assert_eq!(json, r#"{"format":"clap","class_id":"com.example.Delay"}"#);
273        assert_eq!(serde_json::from_str::<PluginId>(&json).unwrap(), clap);
274    }
275}