plughost 0.2.2

Load and run VST3, Audio Unit, and CLAP plugins from Rust, isolated in helper processes
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! A chain of plugins processed in order in one helper process.

mod audio;
mod realtime;
mod recovery;
mod shared;
mod state;

use std::path::{Path, PathBuf};
use std::time::Duration;

use plughost_core::internal::{events_fit, validate_choice_page, validate_parameter_text};
use plughost_core::ipc::{Request, Response};
use plughost_core::render::Tail;
use plughost_core::{
    CapabilityReport, Events, HostIdentity, ParameterInfo, PluginInfo, PluginRef, PluginState,
};

use crate::errors::Error;
use crate::helper::{Helper, Mode};
use crate::remote;

pub use recovery::ChainSnapshot;

/// How long each kind of operation may go without a response from the helper. Start from
/// [`Timeouts::default`] and change the fields that need other values. A duration too long to
/// end at a representable instant, such as [`Duration::MAX`], waits without a deadline.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Timeouts {
    /// Loading plugins, restoring state, importing/loading presets, selecting factory presets,
    /// opening editors, preparing a slot again and preparing an already configured chain again
    /// (which reloads its plugins). Large instruments take minutes. Loading a chain and
    /// preparing it again go through the plugins one at a time, and each plugin that finishes
    /// renews the timeout for the next.
    pub load: Duration,
    /// Initial preparation, resetting, saving state, parameter access and other control calls.
    pub control: Duration,
    /// Processing one block.
    pub process: Duration,
    /// How long an AppKit menu a remote editor's plugin opens stays open without a choice. The
    /// helper's main thread is in the menu's loop meanwhile; the helper closes it then.
    pub menu: Duration,
}

impl Default for Timeouts {
    fn default() -> Timeouts {
        Timeouts {
            load: Duration::from_secs(300),
            control: Duration::from_secs(60),
            process: Duration::from_secs(10),
            menu: Duration::from_secs(60),
        }
    }
}

/// One plugin of a chain to start, with what its fresh instance takes before the chain is
/// returned. Build it with [`ChainSlot::new`] (or from a [`PluginRef`]) and the `with_` methods.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChainSlot {
    /// The plugin class to load.
    pub plugin: PluginRef,
    /// A state saved with [`plughost_core::StatePurpose::Project`] that the loaded instance
    /// restores in place, before anything else, or `None` for its initial state.
    pub state: Option<PluginState>,
    /// The native bypass to set once the state is restored, or `None` to leave it as the plugin
    /// has it.
    pub bypass: Option<bool>,
}

impl ChainSlot {
    /// `plugin` with its initial state and bypass.
    #[must_use]
    pub fn new(plugin: PluginRef) -> ChainSlot {
        ChainSlot {
            plugin,
            state: None,
            bypass: None,
        }
    }

    /// Restores `state` into the loaded instance.
    #[must_use]
    pub fn with_state(mut self, state: PluginState) -> ChainSlot {
        self.state = Some(state);
        self
    }

    /// Sets the native bypass after the state.
    #[must_use]
    pub fn with_bypass(mut self, enabled: bool) -> ChainSlot {
        self.bypass = Some(enabled);
        self
    }
}

impl From<PluginRef> for ChainSlot {
    fn from(plugin: PluginRef) -> ChainSlot {
        ChainSlot::new(plugin)
    }
}

/// How [`Chain::spawn`] starts a chain: the host identity it presents to plugins, which
/// recovered chains keep, and its timeouts. Start from [`SpawnOptions::default`] and set the
/// fields to change.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct SpawnOptions {
    /// The calling application's identity.
    pub host: HostIdentity,
    /// How long the chain's operations may go without a response from the helper.
    pub timeouts: Timeouts,
    /// Whether the chain shows its editors remotely, to someone not in front of the machine
    /// (macOS only; elsewhere starting fails as unsupported). Its helper never activates itself,
    /// so it does not take the focus from other sessions on the machine, tells plugins that check
    /// that it is active, and opens editors only with [`Chain::open_remote_editor`]. When the
    /// application has accessibility access, the machine's own mouse does not reach its windows;
    /// without it a warning diagnostic says so. Recovered chains keep it.
    pub remote: bool,
}

impl SpawnOptions {
    /// Starts chains that present `host` to plugins, with `timeouts`.
    #[must_use]
    pub fn new(host: HostIdentity, timeouts: Timeouts) -> SpawnOptions {
        SpawnOptions {
            host,
            timeouts,
            remote: false,
        }
    }
}

/// Plugins processed in order, isolated in their own helper process. If a plugin crashes or
/// hangs, the chain's methods return [`Error::Crashed`] or [`Error::TimedOut`] (or
/// [`Error::Cancelled`] after a [`Chain::canceller`] ended the hang), and the application
/// decides whether to [`Chain::recover`], or [`Chain::recover_realtime`] for a chain with a
/// realtime endpoint.
pub struct Chain {
    identity: HostIdentity,
    helper_path: PathBuf,
    helper: Helper,
    /// Whether the helper runs in remote mode.
    remote: bool,
    plugins: Vec<PluginRef>,
    infos: Vec<PluginInfo>,
    timeouts: Timeouts,
    config: Option<plughost_core::RoutedChainConfig>,
    shared: Option<shared::Transport>,
    generation: u64,
    latency: u32,
    tail: Tail,
    realtime: Option<realtime::Realtime>,
}

impl std::fmt::Debug for Chain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Chain")
            .field("helper", &self.helper.monitor())
            .field("plugins", &self.infos)
            .field("config", &self.config)
            .field("prepared", &self.shared.is_some())
            .field("latency", &self.latency)
            .field("tail", &self.tail)
            .finish_non_exhaustive()
    }
}

impl Chain {
    /// Starts a helper and loads the `slots`' plugins into it, in chain order. Each loaded
    /// instance restores its slot's state in place and then takes its bypass, before the chain is
    /// returned; a state of another plugin class fails with `FailureKind::StateMismatch` for its
    /// slot. `options.host` identifies the calling application to plugins and is retained across
    /// resets and recovery.
    pub fn spawn(
        helper: &Path,
        slots: &[ChainSlot],
        options: &SpawnOptions,
    ) -> Result<Chain, Error> {
        options
            .host
            .validate()
            .map_err(|error| Error::Input { slot: None, error })?;
        start(
            helper,
            slots,
            &options.host,
            options.timeouts,
            options.remote,
        )
    }

    /// Starts a separate chain of `slots` with this chain's helper, host identity and timeouts,
    /// as [`Chain::spawn`] does, and prepares it with this chain's configuration when this chain
    /// has one. Take the slots from [`Chain::snapshot`]: each holds the slot's plugin, its state
    /// saved with [`plughost_core::StatePurpose::Project`] and its native bypass; for the plugins'
    /// initial states, take [`Chain::references`]. The slots are not checked against this chain's
    /// plugins: other plugins are prepared with this chain's configuration, which can fail or
    /// route them differently. This chain is
    /// left as it is, crashed or not: the application switches to the returned chain when it is
    /// ready, and keeps this one to retry after a failure. The recovered chain holds only what
    /// the slots hold: edits made after the states were saved and DSP history such as tails are
    /// not recovered, and editors are closed. The realtime endpoint stays with this chain: it is
    /// not moved to the recovered one, as [`Chain::recover_realtime`] does.
    pub fn recover(&self, slots: &[ChainSlot]) -> Result<Chain, Error> {
        let mut chain = start(
            &self.helper_path,
            slots,
            &self.identity,
            self.timeouts,
            self.remote,
        )?;
        if let Some(config) = &self.config {
            chain.prepare_audio(config)?;
        }
        Ok(chain)
    }

    /// Loaded plugin metadata in zero-based chain slot order.
    pub fn plugins(&self) -> &[PluginInfo] {
        &self.infos
    }

    /// The references this chain loaded its plugins from, in slot order: for example to recover
    /// it in the plugins' initial states, with `ChainSlot::from` for each.
    pub fn references(&self) -> &[PluginRef] {
        &self.plugins
    }

    /// Observes this helper's exit without issuing IPC requests, including while the chain is
    /// idle. The handle stays attached to this helper after recovery or Chain drop.
    pub fn helper_monitor(&self) -> crate::HelperMonitor {
        self.helper.monitor()
    }

    /// Ends a call this chain is blocked in from another thread, such as a plugin that does not
    /// return from restoring state, loading a preset, opening its editor, preparing again or
    /// processing, by terminating this helper. Loading in [`Chain::spawn`] and recovery is bounded
    /// by the load timeout instead: the chain and its canceller exist only once it is done. The
    /// handle stays attached to this helper after recovery or Chain drop.
    pub fn canceller(&self) -> crate::ChainCanceller {
        self.helper.canceller()
    }

    /// Drains bounded plugin and helper diagnostics. Poll from application/control code.
    /// Unread child-local logs are lost when the helper exits.
    pub fn take_diagnostics(&mut self) -> Result<plughost_core::DiagnosticBatch, Error> {
        match self.request(Request::Diagnostics, self.timeouts.control)? {
            Response::Diagnostics(batch) => Ok(batch),
            _ => Err(self.protocol_error()),
        }
    }

    /// Queries the loaded plugin without opening its editor or saving state. Results are a
    /// fresh snapshot, separate from scan/cache metadata. Re-query after configuration changes.
    pub fn capabilities(&mut self, slot: usize) -> Result<CapabilityReport, Error> {
        match self.request(Request::Capabilities { slot }, self.timeouts.control)? {
            Response::Capabilities(report) => Ok(report),
            _ => Err(self.protocol_error()),
        }
    }

    /// Drains coalesced timing notifications. This is a pull channel independent of diagnostics;
    /// an idle consumer cannot backpressure processing or shutdown. A recovered chain has its own
    /// stream.
    pub fn take_changes(&mut self) -> Result<plughost_core::ChangeBatch, Error> {
        match self.request(Request::Changes, self.timeouts.control)? {
            Response::Changes(batch) => Ok(batch),
            _ => Err(self.protocol_error()),
        }
    }

    /// Explicitly reactivates the saved configuration once. A repeated plugin restart request
    /// remains visible and never causes an automatic retry loop. DSP history may be discarded.
    /// [`Chain::reprepare_slot`] prepares one slot again, also while the realtime endpoint runs.
    pub fn reprepare(&mut self) -> Result<(), Error> {
        let config = self.config.clone().ok_or(Error::NotPrepared)?;
        self.prepare_audio(&config).map(|_| ())
    }

    /// Latest reported latency of the whole chain in samples, cached between helper responses.
    pub fn latency(&self) -> u32 {
        self.latency
    }

    /// Latest reported tail of the whole chain, cached between helper responses.
    pub fn tail(&self) -> Tail {
        self.tail
    }

    /// Each parameter of the plugin in `slot`, with its current normalized value, clamped to
    /// `0..=1`, or `None` when the plugin does not give one, or gives one or a range that is not
    /// finite.
    pub fn parameters(&mut self, slot: usize) -> Result<Vec<(ParameterInfo, Option<f64>)>, Error> {
        match self.request(Request::Parameters { slot }, self.timeouts.control)? {
            Response::Parameters(parameters) => Ok(parameters),
            _ => Err(self.protocol_error()),
        }
    }

    /// Reads current native range, default availability and group identity without editing.
    pub fn parameter_details(
        &mut self,
        slot: usize,
        id: u64,
    ) -> Result<plughost_core::ParameterDetails, Error> {
        match self.request(
            Request::ParameterDetails { slot, id },
            self.timeouts.control,
        )? {
            Response::ParameterDetails(details) => Ok(details),
            _ => Err(self.protocol_error()),
        }
    }

    /// Native discrete labels/values in pages of up to 256, without changing the parameter.
    pub fn parameter_choices(
        &mut self,
        slot: usize,
        id: u64,
        start: u64,
        count: u32,
    ) -> Result<plughost_core::ParameterChoicePage, Error> {
        validate_choice_page(start, count).map_err(|error| Error::Input {
            slot: Some(slot),
            error,
        })?;
        match self.request(
            Request::ParameterChoices {
                slot,
                id,
                start,
                count,
            },
            self.timeouts.control,
        )? {
            Response::ParameterChoices(page) => Ok(page),
            _ => Err(self.protocol_error()),
        }
    }

    /// Changes a parameter the way an edit in the plugin's editor does.
    pub fn set_parameter(&mut self, slot: usize, id: u64, value: f64) -> Result<(), Error> {
        self.request_edit(Request::SetParameter { slot, id, value })
    }

    /// Uses the native formatter without changing the parameter.
    pub fn parameter_text(&mut self, slot: usize, id: u64, value: f64) -> Result<String, Error> {
        match self.request(
            Request::ParameterText { slot, id, value },
            self.timeouts.control,
        )? {
            Response::ParameterText(text) => Ok(text),
            _ => Err(self.protocol_error()),
        }
    }

    /// Parses and edits in one helper operation; rejected text does not queue an edit.
    pub fn set_parameter_text(&mut self, slot: usize, id: u64, text: &str) -> Result<(), Error> {
        validate_parameter_text(text).map_err(|error| Error::Input {
            slot: Some(slot),
            error,
        })?;
        self.request_edit(Request::SetParameterText {
            slot,
            id,
            text: text.to_owned(),
        })
    }

    /// Parses native display text into a normalized value without editing the parameter.
    pub fn parameter_from_text(&mut self, slot: usize, id: u64, text: &str) -> Result<f64, Error> {
        validate_parameter_text(text).map_err(|error| Error::Input {
            slot: Some(slot),
            error,
        })?;
        match self.request(
            Request::ParameterFromText {
                slot,
                id,
                text: text.to_owned(),
            },
            self.timeouts.control,
        )? {
            Response::ParameterValue(value) => Ok(value),
            _ => Err(self.protocol_error()),
        }
    }

    /// Converts a normalized value to the plugin's native parameter units.
    pub fn parameter_to_plain(&mut self, slot: usize, id: u64, value: f64) -> Result<f64, Error> {
        match self.request(
            Request::ParameterToPlain { slot, id, value },
            self.timeouts.control,
        )? {
            Response::ParameterValue(value) => Ok(value),
            _ => Err(self.protocol_error()),
        }
    }

    /// Converts native parameter units to a normalized value without editing it.
    pub fn parameter_to_normalized(
        &mut self,
        slot: usize,
        id: u64,
        plain: f64,
    ) -> Result<f64, Error> {
        match self.request(
            Request::ParameterToNormalized { slot, id, plain },
            self.timeouts.control,
        )? {
            Response::ParameterValue(value) => Ok(value),
            _ => Err(self.protocol_error()),
        }
    }

    /// Clears every plugin's internal state (tails, delay lines), keeping its settings. Refused
    /// while the realtime endpoint runs; [`Chain::resync_realtime`] resets the plugins under it.
    /// A reset that fails at one slot, after earlier slots were reset, leaves the chain to be
    /// prepared again.
    pub fn reset(&mut self) -> Result<(), Error> {
        self.refuse_while_realtime()?;
        self.request_refreshed(Request::Reset)
    }

    /// Opens the editor of the plugin in `slot` in a window of the helper. The chain keeps
    /// processing while it is open, and edits in it reach the processor.
    pub fn open_editor(&mut self, slot: usize) -> Result<(), Error> {
        self.request_done(Request::OpenEditor { slot }, self.timeouts.load)
    }

    /// Closes the helper-owned editor window for this slot, if open.
    pub fn close_editor(&mut self, slot: usize) -> Result<(), Error> {
        self.request_done(Request::CloseEditor { slot }, self.timeouts.control)
    }

    /// Whether the editor of `slot` is open; the user may have closed its window.
    pub fn editor_open(&mut self, slot: usize) -> Result<bool, Error> {
        match self.request(Request::EditorOpen { slot }, self.timeouts.control)? {
            Response::EditorOpen(open) => Ok(open),
            _ => Err(self.protocol_error()),
        }
    }

    /// Sets where a remote chain shows its remote editors and moves those open there. The region
    /// must have a finite position and a positive size within an existing display, or it fails
    /// as [`InputError::RemoteRegion`](crate::InputError::RemoteRegion) and nothing changes.
    /// Moving editors to another display changes their scale, which plugins redraw for; closing
    /// and opening them again there avoids that.
    pub fn set_remote_region(&mut self, region: remote::Region) -> Result<(), Error> {
        self.request_done(Request::SetRemoteRegion { region }, self.timeouts.control)
    }

    /// Opens the editor of the plugin in `slot` for someone not in front of the machine, in a
    /// borderless window [`remote::EDITOR_INSET`] points in from the top-left corner of the
    /// region [`Chain::set_remote_region`] set, which the application reads and shows them. The
    /// editor is shown and the remote editor shown before is hidden, not closed, so it keeps its
    /// state; an editor already open is shown again. Returns the editor and its size.
    ///
    /// Needs a remote chain ([`SpawnOptions::remote`]) and a region, without which it fails as
    /// [`InputError::RemoteRegion`](crate::InputError::RemoteRegion). An Audio Unit v3 editor,
    /// which runs in its extension's process, and an editor that draws only in its own window
    /// fail as unsupported. Close it with [`Chain::close_editor`].
    pub fn open_remote_editor(&mut self, slot: usize) -> Result<remote::Opened, Error> {
        match self.request(Request::OpenRemoteEditor { slot }, self.timeouts.load)? {
            Response::RemoteEditorOpened(opened) => Ok(opened),
            _ => Err(self.protocol_error()),
        }
    }

    /// Shows the open remote editor of `slot` and hides the one shown before.
    pub fn show_remote_editor(&mut self, slot: usize) -> Result<(), Error> {
        self.request_done(Request::ShowRemoteEditor { slot }, self.timeouts.control)
    }

    /// Starts a remote session (macOS only): the channel on which the helper tells what happens
    /// to its remote editors as it happens, beginning with the current state. A later session
    /// ends this one. Needs a remote chain ([`SpawnOptions::remote`]).
    #[cfg(target_os = "macos")]
    pub fn remote_session(&mut self) -> Result<remote::Session, Error> {
        let (commands_read, commands_write) = remote::pipe().map_err(Error::RemoteChannel)?;
        let (notices_read, notices_write) = remote::pipe().map_err(Error::RemoteChannel)?;
        let commands = self.helper.send_channel(&commands_read)?;
        let notices = self.helper.send_channel(&notices_write)?;
        drop((commands_read, notices_write));
        let menu_timeout_ms = u64::try_from(self.timeouts.menu.as_millis()).unwrap_or(u64::MAX);
        self.request_done(
            Request::RemoteSession {
                commands,
                notices,
                menu_timeout_ms,
            },
            self.timeouts.control,
        )?;
        Ok(remote::Session::new(notices_read, commands_write))
    }

    fn request(&mut self, request: Request<'_>, timeout: Duration) -> Result<Response, Error> {
        let result = self.helper.request(request, timeout);
        if matches!(
            result,
            Err(Error::Protocol
                | Error::Crashed { .. }
                | Error::TimedOut { .. }
                | Error::Cancelled { .. })
        ) {
            self.shared = None;
        }
        result
    }

    fn request_done(&mut self, request: Request<'_>, timeout: Duration) -> Result<(), Error> {
        match self.request(request, timeout)? {
            Response::Done => Ok(()),
            _ => Err(self.protocol_error()),
        }
    }

    /// Reads the chain's latency and tail from the helper, and whether a plugin announced a
    /// latency that is not applied yet.
    fn read_timing(&mut self) -> Result<bool, Error> {
        if !self.is_prepared() {
            return Ok(false);
        }
        self.request_timing(Request::Timing)
    }

    /// Sends a parameter edit, after which the helper reads the timing again, except under a
    /// running realtime endpoint, whose timing changes arrive through [`Chain::take_changes`].
    fn request_edit(&mut self, request: Request<'_>) -> Result<(), Error> {
        if self.realtime_running() {
            return self.request_done(request, self.timeouts.control);
        }
        self.request_refreshed(request)
    }

    /// Sends a change after which the helper reads the timing again. A change that took effect
    /// while a slot's timing could not be read is answered without the timing, keeping the
    /// cached one; the helper's diagnostics name the slot.
    fn request_refreshed(&mut self, request: Request<'_>) -> Result<(), Error> {
        match self.request(request, self.timeouts.control)? {
            Response::Timing { latency, tail, .. } => {
                self.latency = latency;
                self.tail = tail;
                Ok(())
            }
            Response::Done => Ok(()),
            _ => Err(self.protocol_error()),
        }
    }

    fn request_timing(&mut self, request: Request<'_>) -> Result<bool, Error> {
        match self.request(request, self.timeouts.control)? {
            Response::Timing {
                latency,
                tail,
                latency_changed,
            } => {
                self.latency = latency;
                self.tail = tail;
                Ok(latency_changed)
            }
            _ => Err(self.protocol_error()),
        }
    }

    fn is_prepared(&self) -> bool {
        self.shared.is_some()
    }
}

/// Starts a helper and loads the slots' plugins, restoring each state as its plugin loads and
/// then setting the bypass.
fn start(
    helper: &Path,
    slots: &[ChainSlot],
    host: &HostIdentity,
    timeouts: Timeouts,
    remote: bool,
) -> Result<Chain, Error> {
    if remote && !cfg!(target_os = "macos") {
        return Err(Error::Operation {
            slot: None,
            failure: plughost_core::Failure::new(
                plughost_core::FailureKind::Unsupported,
                crate::errors::REMOTE_UNSUPPORTED,
            ),
        });
    }
    if slots.is_empty() {
        return Err(Error::Input {
            slot: None,
            error: plughost_core::InputError::EmptyChain,
        });
    }
    for (slot, spec) in slots.iter().enumerate() {
        if spec
            .plugin
            .bundle()
            .is_some_and(|path| path.to_str().is_none())
        {
            return Err(Error::Input {
                slot: Some(slot),
                error: plughost_core::InputError::PathEncoding,
            });
        }
        if let Some(state) = &spec.state {
            state.validate().map_err(|error| Error::Input {
                slot: Some(slot),
                error,
            })?;
        }
    }
    let plugins: Vec<PluginRef> = slots.iter().map(|spec| spec.plugin.clone()).collect();
    let plugins = plugins.as_slice();
    let mode = if remote { Mode::Remote } else { Mode::Host };
    let mut process = Helper::spawn(helper, mode)?;
    let infos = match process.load(host, plugins, timeouts.load)? {
        Response::Loaded(infos) if infos.len() == plugins.len() => infos,
        _ => return Err(Error::Protocol),
    };
    for (slot, spec) in slots.iter().enumerate() {
        if let Some(state) = &spec.state {
            let request = Request::LoadState {
                slot,
                state: std::borrow::Cow::Borrowed(state),
            };
            expect_done(process.request(request, timeouts.load)?)?;
        }
    }
    let mut chain = Chain {
        identity: host.clone(),
        helper_path: helper.to_path_buf(),
        helper: process,
        remote,
        plugins: plugins.to_vec(),
        infos,
        timeouts,
        config: None,
        shared: None,
        generation: 0,
        latency: 0,
        tail: Tail::Samples(0),
        realtime: None,
    };
    for (slot, spec) in slots.iter().enumerate() {
        if let Some(enabled) = spec.bypass {
            chain.set_bypass(slot, enabled)?;
        }
    }
    Ok(chain)
}

fn expect_done(response: Response) -> Result<(), Error> {
    match response {
        Response::Done => Ok(()),
        _ => Err(Error::Protocol),
    }
}