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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Scanning installed plugins in helper processes, one helper per bundle.
#[cfg(test)]
mod benchmark;
mod bundle;
mod cache;
#[cfg(test)]
mod catalog_tests;
mod control;
mod execute;
use control::Work;
pub use control::{ScanControl, ScanEvent, ScanItem, ScanStage, ScanTarget};
#[cfg(any(test, fuzzing))]
pub mod fuzz;
mod moduleinfo;
mod policy;
pub use policy::{ScanAction, ScanPolicy};
mod run;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::Duration;
use plughost_core::ipc::Request;
use plughost_core::{Failure, PluginFormat, PluginId, PluginInfo};
use plughost_core::{HostIdentity, PluginRef};
use self::bundle::Inspection;
use crate::errors::Error;
/// The result of scanning one bundle.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScanOutcome {
/// Metadata for the classes found, without a guarantee that every class can be instantiated.
Found(Vec<PluginInfo>),
/// Metadata discovery found a compatible binary, but no class metadata or cached result.
/// Native inspection is required; this is not a plugin failure.
NotInspected,
/// The caller cancelled the operation. Never counted or cached as a plugin failure.
Cancelled,
/// The caller skipped this item. Never counted or cached as a plugin failure.
Skipped,
/// Excluded by the caller's policy, including during retry. Cached results are preserved.
Blocked,
/// The binary does not contain the helper's architecture; it was not loaded.
UnsupportedArchitecture,
/// There is no binary, for example the remains of an interrupted install.
InvalidBundle,
/// Scanning returned a plugin or host error.
Failed(Failure),
/// The helper process died while loading the module, with its exit status.
Crashed(String),
/// The helper made no progress within the stall timeout and was terminated.
TimedOut,
}
impl ScanOutcome {
fn is_failure(&self) -> bool {
matches!(
self,
ScanOutcome::Failed(_) | ScanOutcome::Crashed(_) | ScanOutcome::TimedOut
)
}
}
/// How a bundle result was obtained.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Source {
/// Native inspection was selected; failure or interruption may occur before loading.
Loaded,
/// Read from `moduleinfo.json` without loading.
ModuleInfo,
/// Unchanged native result from an earlier scan.
Cache,
/// Inspected without loading (policy, architecture or missing binary).
Inspected,
}
/// One discovered bundle and its outcome, provenance, and automatic exclusion status.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct BundleScan {
/// The discovered bundle path, preserving search-directory priority.
pub path: PathBuf,
/// Classes or the reason this bundle supplied no classes.
pub outcome: ScanOutcome,
/// Metadata source or the inspection path selected for this result.
pub source: Source,
/// Consecutive failed scans of this unchanged bundle.
pub failures: u32,
/// Failed too often; skipped until [`Scanner::retry`].
pub excluded: bool,
}
/// Ordered discovery results for native bundles and the Audio Unit registry.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Catalog {
/// Every VST3 and CLAP bundle found, in directory priority order.
pub bundles: Vec<BundleScan>,
/// Allowed Audio Units in the system registry (macOS), read fresh by a helper without loading.
pub audio_units: ScanOutcome,
}
impl BundleScan {
/// The classes this bundle supplied, each with the reference that loads it from this bundle,
/// without a guarantee of successful loading. Empty unless the outcome is
/// [`ScanOutcome::Found`].
pub fn plugins(&self) -> Vec<(PluginRef, &PluginInfo)> {
let ScanOutcome::Found(classes) = &self.outcome else {
return Vec::new();
};
classes
.iter()
.filter_map(|class| {
let class_id = class.id.class_id().as_str();
let plugin = match class.id.format() {
PluginFormat::Vst3 => PluginRef::vst3(&self.path, class_id),
PluginFormat::Clap => PluginRef::clap(&self.path, class_id),
// A helper reported a class no bundle can hold.
_ => return None,
};
Some((plugin, class))
})
.collect()
}
}
impl Catalog {
/// Every discovered plugin class identity, without a guarantee of successful loading.
/// When bundles share a [`PluginId`], the one found first (in the higher priority directory)
/// wins.
pub fn plugins(&self) -> Vec<(PluginRef, &PluginInfo)> {
let mut seen = HashSet::new();
let audio_units = match &self.audio_units {
ScanOutcome::Found(classes) => classes.as_slice(),
_ => &[],
};
self.bundles
.iter()
.flat_map(BundleScan::plugins)
.chain(
audio_units
.iter()
.map(|class| (PluginRef::audio_unit(class.id.class_id().as_str()), class)),
)
.filter(|(plugin, _)| seen.insert(plugin.id().clone()))
.collect()
}
/// Where the class `id` is installed: the reference [`Catalog::plugins`] gives it, from the
/// highest priority directory that has it. `None` when the catalog has no such class.
pub fn resolve(&self, id: &PluginId) -> Option<PluginRef> {
self.plugins()
.into_iter()
.map(|(plugin, _)| plugin)
.find(|plugin| plugin.id() == id)
}
}
/// The standard VST3 and CLAP folders of the platform, highest priority first, and the folders in
/// `CLAP_PATH`. Applications add their own plugin folders.
pub fn default_directories() -> Vec<PathBuf> {
let mut directories = Vec::new();
#[cfg(target_os = "macos")]
{
let home = std::env::var_os("HOME").map(PathBuf::from);
for format in ["VST3", "CLAP"] {
if let Some(home) = &home {
directories.push(home.join("Library/Audio/Plug-Ins").join(format));
}
directories.push(PathBuf::from("/Library/Audio/Plug-Ins").join(format));
}
directories.push(PathBuf::from("/Network/Library/Audio/Plug-Ins/VST3"));
}
#[cfg(target_os = "windows")]
{
let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from);
let common = std::env::var_os("CommonProgramFiles").map(PathBuf::from);
for format in ["VST3", "CLAP"] {
if let Some(local) = &local {
directories.push(local.join("Programs\\Common").join(format));
}
if let Some(common) = &common {
directories.push(common.join(format));
}
}
}
if let Some(paths) = std::env::var_os("CLAP_PATH") {
directories.extend(std::env::split_paths(&paths));
}
directories
}
/// Configures metadata discovery, supervised native scans, caching, and selection policy.
/// Each native bundle scan runs in a short-lived helper; discovery alone does not load it.
#[derive(Debug)]
pub struct Scanner {
helper: PathBuf,
cache: PathBuf,
directories: Vec<PathBuf>,
jobs: usize,
stall_timeout: Duration,
exclude_after: u32,
policy: ScanPolicy,
host: HostIdentity,
}
/// A bundle's scan result and the cache entry to keep for it.
type Scanned = (BundleScan, Option<cache::Entry>);
#[derive(Clone, Copy, PartialEq, Eq)]
enum ScanMode {
Metadata,
Native,
Retry,
}
impl ScanMode {
fn stall_timeout(self, configured: Duration) -> Duration {
if self == Self::Retry {
// A wait long enough to answer a license dialog by hand.
Duration::from_secs(24 * 60 * 60)
} else {
configured
}
}
}
impl Scanner {
/// Scans the platform's standard folders with `helper`, keeping native results in `cache`.
/// Native inspection is serial unless [`Self::jobs`] is explicitly set.
#[must_use]
pub fn new(helper: &Path, cache: &Path) -> Scanner {
Scanner {
helper: helper.to_path_buf(),
cache: cache.to_path_buf(),
directories: default_directories(),
jobs: 1,
stall_timeout: Duration::from_secs(30),
exclude_after: 2,
policy: ScanPolicy::default(),
host: HostIdentity::default(),
}
}
/// The identity native inspection presents to plugins, as [`crate::Chain::spawn`] does
/// (default: [`HostIdentity::default`]). VST3 factories receive it as their host context;
/// CLAP inspection reads descriptors without a host. Cached native results are reused
/// whichever identity inspected them. An invalid identity fails [`Self::scan`] and
/// [`Self::retry`] with [`Error::Input`] before any helper starts.
#[must_use]
pub fn host(mut self, host: HostIdentity) -> Scanner {
self.host = host;
self
}
/// Folders to scan, highest priority first.
#[must_use]
pub fn directories(mut self, directories: Vec<PathBuf>) -> Scanner {
self.directories = directories;
self
}
/// Selects bundles and registered Audio Units. Blocked bundles remain visible with
/// [`ScanOutcome::Blocked`]; blocked Audio Units are omitted from registry results.
/// Rules apply to discovery, native scanning and retry, independently of failure exclusion.
#[must_use]
pub fn policy(mut self, policy: ScanPolicy) -> Scanner {
self.policy = policy;
self
}
/// Native inspection helpers to run at the same time (default: one). Zero selects one.
/// The Audio Unit registry uses one of these slots and overlaps bundle inspection when
/// this limit exceeds one.
/// Parallel inspection can open multiple plugin dialogs concurrently.
#[must_use]
pub fn jobs(mut self, jobs: usize) -> Scanner {
self.jobs = jobs.max(1);
self
}
/// How long a helper may go without progress (module loaded, each class) before it is
/// terminated.
#[must_use]
pub fn stall_timeout(mut self, timeout: Duration) -> Scanner {
self.stall_timeout = timeout;
self
}
/// Discovers bundles without loading their plugin code. Uses unchanged native cache entries,
/// static VST3 metadata and binary headers. Missing/malformed metadata yields
/// [`ScanOutcome::NotInspected`], never an automatic native load. The cache is not written.
/// Audio Unit registry enumeration uses a helper without instantiating Audio Units.
/// Discovery does not prove that a plugin can be instantiated or process audio.
pub fn discover(&self) -> Catalog {
self.discover_controlled(&ScanControl::default(), &|_| {})
}
/// Metadata discovery with cancellation, per-item skipping and stage notifications.
/// Filesystem traversal checks cancellation between entries; an OS filesystem call itself
/// cannot be interrupted. Items not admitted before cancellation are absent from the catalog.
pub fn discover_controlled(
&self,
control: &ScanControl,
events: &(dyn Fn(&ScanEvent) + Sync),
) -> Catalog {
let cache = cache::load(&self.cache);
let paths = bundle::find(&self.directories, &|| control.is_cancelled());
let mut bundles = Vec::new();
for path in paths {
let Some(work) = control.begin(ScanTarget::Bundle(path.clone()), events) else {
break;
};
let (scan, _) =
self.scan_bundle(&path, cache.bundles.get(&path), ScanMode::Metadata, &work);
events(&ScanEvent::BundleFinished(scan.clone()));
bundles.push(scan);
}
Catalog {
bundles,
audio_units: self.list_audio_units(control, events, None),
}
}
/// Inspects native classes, calling `progress` as each bundle finishes. Reuses unchanged
/// native cache results, but static module metadata does not replace native inspection.
/// Plugins can show dialogs during loading. This does not instantiate every plugin class
/// or verify DSP capabilities. Audio Units are listed from their registry only.
/// Cache access can fail; each bundle's problems are in its outcome. Changed results are
/// written to the cache before the completion callback, including when a later bundle is
/// interrupted, and synced to stable storage when the scan ends.
pub fn scan(&self, progress: &(dyn Fn(&BundleScan) + Sync)) -> Result<Catalog, Error> {
self.scan_controlled(&ScanControl::default(), &|event| {
if let ScanEvent::BundleFinished(scan) = event {
progress(scan);
}
})
}
/// Reads the Audio Unit registry through a helper. There is none on other platforms.
fn list_audio_units(
&self,
control: &ScanControl,
events: &(dyn Fn(&ScanEvent) + Sync),
aborted: Option<&std::sync::atomic::AtomicBool>,
) -> ScanOutcome {
let outcome = match control.begin(ScanTarget::AudioUnits, events) {
None => ScanOutcome::Cancelled,
Some(work) => {
let work = if let Some(aborted) = aborted {
work.abort_on(aborted)
} else {
work
};
if let Some(outcome) = work.stage(ScanStage::Inspecting) {
outcome
} else if cfg!(target_os = "macos") {
self.execute(Request::ListAudioUnits, self.stall_timeout, &work)
.unwrap_or_else(outcome_of)
} else {
ScanOutcome::Found(Vec::new())
}
}
};
events(&ScanEvent::AudioUnitsFinished(outcome.clone()));
outcome
}
/// Scans one bundle again with a 24-hour stall timeout, even if excluded, so the user can answer
/// a dialog the plugin shows. Updates the cache. Explicit policy blocks still apply.
pub fn retry(&self, path: &Path) -> Result<BundleScan, Error> {
self.retry_controlled(path, &ScanControl::default(), &|_| {})
}
/// Interactive retry with the same stop/stage contract as [`Self::scan_controlled`].
pub fn retry_controlled(
&self,
path: &Path,
control: &ScanControl,
events: &(dyn Fn(&ScanEvent) + Sync),
) -> Result<BundleScan, Error> {
self.validate_host()?;
if control.is_cancelled() {
let cache = cache::load(&self.cache);
let scan = self.interrupted(
path,
cache.bundles.get(path),
ScanOutcome::Cancelled,
Source::Inspected,
);
events(&ScanEvent::BundleFinished(scan.clone()));
return Ok(scan);
}
let mut writer = cache::Writer::open(&self.cache).map_err(Error::Cache)?;
let cached = writer.entry(path).cloned();
let Some(work) = control.begin(ScanTarget::Bundle(path.to_path_buf()), events) else {
let scan = self.interrupted(
path,
cached.as_ref(),
ScanOutcome::Cancelled,
Source::Inspected,
);
events(&ScanEvent::BundleFinished(scan.clone()));
return Ok(scan);
};
let (scan, entry) = self.scan_bundle(path, cached.as_ref(), ScanMode::Retry, &work);
writer.update(path, entry).map_err(Error::Cache)?;
writer.finish().map_err(Error::Cache)?;
events(&ScanEvent::BundleFinished(scan.clone()));
Ok(scan)
}
fn validate_host(&self) -> Result<(), Error> {
self.host
.validate()
.map_err(|error| Error::Input { slot: None, error })
}
fn interrupted(
&self,
path: &Path,
cached: Option<&cache::Entry>,
outcome: ScanOutcome,
source: Source,
) -> BundleScan {
let failures = cached.map_or(0, |entry| entry.failures);
BundleScan {
path: path.to_path_buf(),
outcome,
source,
failures,
excluded: failures >= self.exclude_after,
}
}
fn scan_bundle(
&self,
path: &Path,
cached: Option<&cache::Entry>,
mode: ScanMode,
work: &Work<'_>,
) -> Scanned {
if let Some(outcome) = work.stage(ScanStage::Inspecting) {
return (
self.interrupted(path, cached, outcome, Source::Inspected),
cached.cloned(),
);
}
if !self.policy.allows_bundle(path) {
return (
self.interrupted(path, cached, ScanOutcome::Blocked, Source::Inspected),
cached.cloned(),
);
}
let scan = |outcome, source, failures, excluded| BundleScan {
path: path.to_path_buf(),
outcome,
source,
failures,
excluded,
};
if path.to_str().is_none() {
return (
scan(
ScanOutcome::Failed(Failure::new(
plughost_core::FailureKind::InvalidInput,
plughost_core::InputError::PathEncoding.to_string(),
)),
Source::Inspected,
0,
false,
),
None,
);
}
let Some(executable) = bundle::executable(path) else {
return (
scan(ScanOutcome::InvalidBundle, Source::Inspected, 0, false),
None,
);
};
let fingerprint = bundle::fingerprint(path, &executable);
let unchanged = cached.filter(|entry| entry.fingerprint == fingerprint);
if let Some(entry) = unchanged
&& mode != ScanMode::Retry
{
let excluded = entry.failures >= self.exclude_after;
if mode == ScanMode::Metadata || !entry.outcome.is_failure() || excluded {
let result = scan(
entry.outcome.clone(),
Source::Cache,
entry.failures,
excluded,
);
return (result, Some(entry.clone()));
}
}
match bundle::inspect(&executable) {
Inspection::Supported => {}
Inspection::UnsupportedArchitecture => {
return (
scan(
ScanOutcome::UnsupportedArchitecture,
Source::Inspected,
0,
false,
),
None,
);
}
Inspection::Invalid => {
return (
scan(ScanOutcome::InvalidBundle, Source::Inspected, 0, false),
None,
);
}
}
if mode == ScanMode::Metadata {
let (outcome, source) = match moduleinfo::read(path) {
Some(classes) => (ScanOutcome::Found(classes), Source::ModuleInfo),
None => (ScanOutcome::NotInspected, Source::Inspected),
};
return (scan(outcome, source, 0, false), None);
}
let outcome = match self.execute(
Request::Scan {
bundle: path.to_path_buf(),
host: self.host.clone(),
interactive: mode == ScanMode::Retry,
},
mode.stall_timeout(self.stall_timeout),
work,
) {
Ok(outcome) => outcome,
// The cache keeps its entry, but a changed bundle's failures no longer count.
Err(error) => {
return (
self.interrupted(path, unchanged, outcome_of(error), Source::Loaded),
cached.cloned(),
);
}
};
if matches!(outcome, ScanOutcome::Cancelled | ScanOutcome::Skipped) {
return (
self.interrupted(path, unchanged, outcome, Source::Loaded),
cached.cloned(),
);
}
let failures = if outcome.is_failure() {
unchanged.map_or(0, |entry| entry.failures) + 1
} else {
0
};
let entry = cache::Entry {
fingerprint,
outcome: outcome.clone(),
failures,
};
let excluded = failures >= self.exclude_after;
(
scan(outcome, Source::Loaded, failures, excluded),
Some(entry),
)
}
}
fn outcome_of(error: Error) -> ScanOutcome {
match error {
Error::Crashed { status, .. } => {
ScanOutcome::Crashed(status.map(|status| status.to_string()).unwrap_or_default())
}
Error::TimedOut { .. } => ScanOutcome::TimedOut,
Error::Operation { failure, .. } => ScanOutcome::Failed(failure),
error => ScanOutcome::Failed(Failure::new(error.kind(), error.diagnostic())),
}
}