Skip to main content

plughost/
chain.rs

1//! A chain of plugins processed in order in one helper process.
2
3mod audio;
4mod realtime;
5mod recovery;
6mod shared;
7mod slots;
8mod state;
9
10use std::path::{Path, PathBuf};
11use std::time::Duration;
12
13use plughost_core::internal::{events_fit, validate_choice_page, validate_parameter_text};
14use plughost_core::ipc::{Request, Response};
15use plughost_core::render::Tail;
16use plughost_core::{
17    CapabilityReport, Events, HostIdentity, ParameterInfo, PluginInfo, PluginRef, PluginState,
18};
19
20use crate::errors::Error;
21use crate::helper::{Helper, Mode};
22use crate::remote;
23
24pub use recovery::ChainSnapshot;
25
26/// How long each kind of operation may go without a response from the helper. Start from
27/// [`Timeouts::default`] and change the fields that need other values. A duration too long to
28/// end at a representable instant, such as [`Duration::MAX`], waits without a deadline.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct Timeouts {
32    /// Loading plugins, restoring state, importing/loading presets, selecting factory presets,
33    /// opening editors, preparing a slot again and preparing an already configured chain again
34    /// (which reloads its plugins). Large instruments take minutes. Loading a chain and
35    /// preparing it again go through the plugins one at a time, and each plugin that finishes
36    /// renews the timeout for the next.
37    pub load: Duration,
38    /// Initial preparation, resetting, saving state, parameter access and other control calls.
39    pub control: Duration,
40    /// Processing one block.
41    pub process: Duration,
42    /// How long an AppKit menu a remote editor's plugin opens stays open without a choice. The
43    /// helper's main thread is in the menu's loop meanwhile; the helper closes it then.
44    pub menu: Duration,
45}
46
47impl Default for Timeouts {
48    fn default() -> Timeouts {
49        Timeouts {
50            load: Duration::from_secs(300),
51            control: Duration::from_secs(60),
52            process: Duration::from_secs(10),
53            menu: Duration::from_secs(60),
54        }
55    }
56}
57
58/// One plugin of a chain to start, with what its fresh instance takes before the chain is
59/// returned. Build it with [`ChainSlot::new`] (or from a [`PluginRef`]) and the `with_` methods.
60#[derive(Clone, Debug, PartialEq, Eq)]
61#[non_exhaustive]
62pub struct ChainSlot {
63    /// The plugin class to load.
64    pub plugin: PluginRef,
65    /// A state saved with [`plughost_core::StatePurpose::Project`] that the loaded instance
66    /// restores in place, before anything else, or `None` for its initial state.
67    pub state: Option<PluginState>,
68    /// The native bypass to set once the state is restored, or `None` to leave it as the plugin
69    /// has it.
70    pub bypass: Option<bool>,
71    /// Whether the slot's host bypass is on (see [`Chain::set_host_bypass`]).
72    pub host_bypass: bool,
73}
74
75impl ChainSlot {
76    /// `plugin` with its initial state and bypass, and host bypass off.
77    #[must_use]
78    pub fn new(plugin: PluginRef) -> ChainSlot {
79        ChainSlot {
80            plugin,
81            state: None,
82            bypass: None,
83            host_bypass: false,
84        }
85    }
86
87    /// Restores `state` into the loaded instance.
88    #[must_use]
89    pub fn with_state(mut self, state: PluginState) -> ChainSlot {
90        self.state = Some(state);
91        self
92    }
93
94    /// Sets the native bypass after the state.
95    #[must_use]
96    pub fn with_bypass(mut self, enabled: bool) -> ChainSlot {
97        self.bypass = Some(enabled);
98        self
99    }
100
101    /// Turns the slot's host bypass on or off.
102    #[must_use]
103    pub fn with_host_bypass(mut self, enabled: bool) -> ChainSlot {
104        self.host_bypass = enabled;
105        self
106    }
107}
108
109impl From<PluginRef> for ChainSlot {
110    fn from(plugin: PluginRef) -> ChainSlot {
111        ChainSlot::new(plugin)
112    }
113}
114
115/// How [`Chain::spawn`] starts a chain: the host identity it presents to plugins, which
116/// recovered chains keep, and its timeouts. Start from [`SpawnOptions::default`] and set the
117/// fields to change.
118#[derive(Clone, Debug, Default, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct SpawnOptions {
121    /// The calling application's identity.
122    pub host: HostIdentity,
123    /// How long the chain's operations may go without a response from the helper.
124    pub timeouts: Timeouts,
125    /// Whether the chain shows its editors remotely, to someone not in front of the machine
126    /// (macOS only; elsewhere starting fails as unsupported). Its helper never activates itself,
127    /// so it does not take the focus from other sessions on the machine, tells plugins that check
128    /// that it is active, and opens editors only with [`Chain::open_remote_editor`]. When the
129    /// application has accessibility access, the machine's own mouse does not reach its windows;
130    /// without it a warning diagnostic says so. Recovered chains keep it.
131    pub remote: bool,
132}
133
134impl SpawnOptions {
135    /// Starts chains that present `host` to plugins, with `timeouts`.
136    #[must_use]
137    pub fn new(host: HostIdentity, timeouts: Timeouts) -> SpawnOptions {
138        SpawnOptions {
139            host,
140            timeouts,
141            remote: false,
142        }
143    }
144}
145
146/// Plugins processed in order, isolated in their own helper process. If a plugin crashes or
147/// hangs, the chain's methods return [`Error::Crashed`] or [`Error::TimedOut`] (or
148/// [`Error::Cancelled`] after a [`Chain::canceller`] ended the hang), and the application
149/// decides whether to [`Chain::recover`], or [`Chain::recover_realtime`] for a chain with a
150/// realtime endpoint.
151pub struct Chain {
152    identity: HostIdentity,
153    helper_path: PathBuf,
154    helper: Helper,
155    /// Whether the helper runs in remote mode.
156    remote: bool,
157    plugins: Vec<PluginRef>,
158    infos: Vec<PluginInfo>,
159    timeouts: Timeouts,
160    config: Option<plughost_core::RoutedChainConfig>,
161    shared: Option<shared::Transport>,
162    generation: u64,
163    latency: u32,
164    tail: Tail,
165    realtime: Option<realtime::Realtime>,
166}
167
168impl std::fmt::Debug for Chain {
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        f.debug_struct("Chain")
171            .field("helper", &self.helper.monitor())
172            .field("plugins", &self.infos)
173            .field("config", &self.config)
174            .field("prepared", &self.shared.is_some())
175            .field("latency", &self.latency)
176            .field("tail", &self.tail)
177            .finish_non_exhaustive()
178    }
179}
180
181impl Chain {
182    /// Starts a helper and loads the `slots`' plugins into it, in chain order. Each loaded
183    /// instance restores its slot's state in place and then takes its bypass and host bypass,
184    /// before the chain is returned; a state of another plugin class fails with `FailureKind::StateMismatch` for its
185    /// slot. `options.host` identifies the calling application to plugins and is retained across
186    /// resets and recovery.
187    pub fn spawn(
188        helper: &Path,
189        slots: &[ChainSlot],
190        options: &SpawnOptions,
191    ) -> Result<Chain, Error> {
192        options
193            .host
194            .validate()
195            .map_err(|error| Error::Input { slot: None, error })?;
196        start(
197            helper,
198            slots,
199            &options.host,
200            options.timeouts,
201            options.remote,
202        )
203    }
204
205    /// Starts a separate chain of `slots` with this chain's helper, host identity and timeouts,
206    /// as [`Chain::spawn`] does, and prepares it with this chain's configuration when this chain
207    /// has one. Take the slots from [`Chain::snapshot`]: each holds the slot's plugin, its state
208    /// saved with [`plughost_core::StatePurpose::Project`], its native bypass and its host
209    /// bypass; for the plugins' initial states, take [`Chain::references`]. The slots are not checked against this chain's
210    /// plugins: other plugins are prepared with this chain's configuration, which can fail or
211    /// route them differently. This chain is
212    /// left as it is, crashed or not: the application switches to the returned chain when it is
213    /// ready, and keeps this one to retry after a failure. The recovered chain holds only what
214    /// the slots hold: edits made after the states were saved and DSP history such as tails are
215    /// not recovered, and editors are closed. The realtime endpoint stays with this chain: it is
216    /// not moved to the recovered one, as [`Chain::recover_realtime`] does.
217    pub fn recover(&self, slots: &[ChainSlot]) -> Result<Chain, Error> {
218        let mut chain = start(
219            &self.helper_path,
220            slots,
221            &self.identity,
222            self.timeouts,
223            self.remote,
224        )?;
225        if let Some(config) = &self.config {
226            chain.prepare_audio(config)?;
227        }
228        Ok(chain)
229    }
230
231    /// Loaded plugin metadata in zero-based chain slot order.
232    pub fn plugins(&self) -> &[PluginInfo] {
233        &self.infos
234    }
235
236    /// The references this chain loaded its plugins from, in slot order: for example to recover
237    /// it in the plugins' initial states, with `ChainSlot::from` for each.
238    pub fn references(&self) -> &[PluginRef] {
239        &self.plugins
240    }
241
242    /// Observes this helper's exit without issuing IPC requests, including while the chain is
243    /// idle. The handle stays attached to this helper after recovery or Chain drop.
244    pub fn helper_monitor(&self) -> crate::HelperMonitor {
245        self.helper.monitor()
246    }
247
248    /// Ends a call this chain is blocked in from another thread, such as a plugin that does not
249    /// return from restoring state, loading a preset, opening its editor, preparing again or
250    /// processing, by terminating this helper. Loading in [`Chain::spawn`] and recovery is bounded
251    /// by the load timeout instead: the chain and its canceller exist only once it is done. The
252    /// handle stays attached to this helper after recovery or Chain drop.
253    pub fn canceller(&self) -> crate::ChainCanceller {
254        self.helper.canceller()
255    }
256
257    /// Drains bounded plugin and helper diagnostics. Poll from application/control code.
258    /// Unread child-local logs are lost when the helper exits.
259    pub fn take_diagnostics(&mut self) -> Result<plughost_core::DiagnosticBatch, Error> {
260        match self.request(Request::Diagnostics, self.timeouts.control)? {
261            Response::Diagnostics(batch) => Ok(batch),
262            _ => Err(self.protocol_error()),
263        }
264    }
265
266    /// Queries the loaded plugin without opening its editor or saving state. Results are a
267    /// fresh snapshot, separate from scan/cache metadata. Re-query after configuration changes.
268    pub fn capabilities(&mut self, slot: usize) -> Result<CapabilityReport, Error> {
269        match self.request(Request::Capabilities { slot }, self.timeouts.control)? {
270            Response::Capabilities(report) => Ok(report),
271            _ => Err(self.protocol_error()),
272        }
273    }
274
275    /// Drains coalesced timing notifications. This is a pull channel independent of diagnostics;
276    /// an idle consumer cannot backpressure processing or shutdown. A recovered chain has its own
277    /// stream.
278    pub fn take_changes(&mut self) -> Result<plughost_core::ChangeBatch, Error> {
279        match self.request(Request::Changes, self.timeouts.control)? {
280            Response::Changes(batch) => Ok(batch),
281            _ => Err(self.protocol_error()),
282        }
283    }
284
285    /// Explicitly reactivates the saved configuration once. A repeated plugin restart request
286    /// remains visible and never causes an automatic retry loop. DSP history may be discarded.
287    /// [`Chain::reprepare_slot`] prepares one slot again, also while the realtime endpoint runs.
288    pub fn reprepare(&mut self) -> Result<(), Error> {
289        let config = self.config.clone().ok_or(Error::NotPrepared)?;
290        self.prepare_audio(&config).map(|_| ())
291    }
292
293    /// Latest reported latency of the whole chain in samples, cached between helper responses.
294    pub fn latency(&self) -> u32 {
295        self.latency
296    }
297
298    /// Latest reported tail of the whole chain, cached between helper responses.
299    pub fn tail(&self) -> Tail {
300        self.tail
301    }
302
303    /// Each parameter of the plugin in `slot`, with its current normalized value, clamped to
304    /// `0..=1`, or `None` when the plugin does not give one, or gives one or a range that is not
305    /// finite.
306    pub fn parameters(&mut self, slot: usize) -> Result<Vec<(ParameterInfo, Option<f64>)>, Error> {
307        match self.request(Request::Parameters { slot }, self.timeouts.control)? {
308            Response::Parameters(parameters) => Ok(parameters),
309            _ => Err(self.protocol_error()),
310        }
311    }
312
313    /// Reads current native range, default availability and group identity without editing.
314    pub fn parameter_details(
315        &mut self,
316        slot: usize,
317        id: u64,
318    ) -> Result<plughost_core::ParameterDetails, Error> {
319        match self.request(
320            Request::ParameterDetails { slot, id },
321            self.timeouts.control,
322        )? {
323            Response::ParameterDetails(details) => Ok(details),
324            _ => Err(self.protocol_error()),
325        }
326    }
327
328    /// Native discrete labels/values in pages of up to 256, without changing the parameter.
329    pub fn parameter_choices(
330        &mut self,
331        slot: usize,
332        id: u64,
333        start: u64,
334        count: u32,
335    ) -> Result<plughost_core::ParameterChoicePage, Error> {
336        validate_choice_page(start, count).map_err(|error| Error::Input {
337            slot: Some(slot),
338            error,
339        })?;
340        match self.request(
341            Request::ParameterChoices {
342                slot,
343                id,
344                start,
345                count,
346            },
347            self.timeouts.control,
348        )? {
349            Response::ParameterChoices(page) => Ok(page),
350            _ => Err(self.protocol_error()),
351        }
352    }
353
354    /// Changes a parameter the way an edit in the plugin's editor does.
355    pub fn set_parameter(&mut self, slot: usize, id: u64, value: f64) -> Result<(), Error> {
356        self.request_edit(Request::SetParameter { slot, id, value })
357    }
358
359    /// Uses the native formatter without changing the parameter.
360    pub fn parameter_text(&mut self, slot: usize, id: u64, value: f64) -> Result<String, Error> {
361        match self.request(
362            Request::ParameterText { slot, id, value },
363            self.timeouts.control,
364        )? {
365            Response::ParameterText(text) => Ok(text),
366            _ => Err(self.protocol_error()),
367        }
368    }
369
370    /// Parses and edits in one helper operation; rejected text does not queue an edit.
371    pub fn set_parameter_text(&mut self, slot: usize, id: u64, text: &str) -> Result<(), Error> {
372        validate_parameter_text(text).map_err(|error| Error::Input {
373            slot: Some(slot),
374            error,
375        })?;
376        self.request_edit(Request::SetParameterText {
377            slot,
378            id,
379            text: text.to_owned(),
380        })
381    }
382
383    /// Parses native display text into a normalized value without editing the parameter.
384    pub fn parameter_from_text(&mut self, slot: usize, id: u64, text: &str) -> Result<f64, Error> {
385        validate_parameter_text(text).map_err(|error| Error::Input {
386            slot: Some(slot),
387            error,
388        })?;
389        match self.request(
390            Request::ParameterFromText {
391                slot,
392                id,
393                text: text.to_owned(),
394            },
395            self.timeouts.control,
396        )? {
397            Response::ParameterValue(value) => Ok(value),
398            _ => Err(self.protocol_error()),
399        }
400    }
401
402    /// Converts a normalized value to the plugin's native parameter units.
403    pub fn parameter_to_plain(&mut self, slot: usize, id: u64, value: f64) -> Result<f64, Error> {
404        match self.request(
405            Request::ParameterToPlain { slot, id, value },
406            self.timeouts.control,
407        )? {
408            Response::ParameterValue(value) => Ok(value),
409            _ => Err(self.protocol_error()),
410        }
411    }
412
413    /// Converts native parameter units to a normalized value without editing it.
414    pub fn parameter_to_normalized(
415        &mut self,
416        slot: usize,
417        id: u64,
418        plain: f64,
419    ) -> Result<f64, Error> {
420        match self.request(
421            Request::ParameterToNormalized { slot, id, plain },
422            self.timeouts.control,
423        )? {
424            Response::ParameterValue(value) => Ok(value),
425            _ => Err(self.protocol_error()),
426        }
427    }
428
429    /// Clears every plugin's internal state (tails, delay lines), keeping its settings. Refused
430    /// while the realtime endpoint runs; [`Chain::resync_realtime`] resets the plugins under it.
431    /// A reset that fails at one slot, after earlier slots were reset, leaves the chain to be
432    /// prepared again.
433    pub fn reset(&mut self) -> Result<(), Error> {
434        self.refuse_while_realtime()?;
435        self.request_refreshed(Request::Reset)
436    }
437
438    /// Opens the editor of the plugin in `slot` in a window of the helper. The chain keeps
439    /// processing while it is open, and edits in it reach the processor.
440    pub fn open_editor(&mut self, slot: usize) -> Result<(), Error> {
441        self.request_done(Request::OpenEditor { slot }, self.timeouts.load)
442    }
443
444    /// Closes the helper-owned editor window for this slot, if open.
445    pub fn close_editor(&mut self, slot: usize) -> Result<(), Error> {
446        self.request_done(Request::CloseEditor { slot }, self.timeouts.control)
447    }
448
449    /// Whether the editor of `slot` is open; the user may have closed its window.
450    pub fn editor_open(&mut self, slot: usize) -> Result<bool, Error> {
451        match self.request(Request::EditorOpen { slot }, self.timeouts.control)? {
452            Response::EditorOpen(open) => Ok(open),
453            _ => Err(self.protocol_error()),
454        }
455    }
456
457    /// Sets where a remote chain shows its remote editors and moves those open there. The region
458    /// must have a finite position and a positive size within an existing display, or it fails
459    /// as [`InputError::RemoteRegion`](crate::InputError::RemoteRegion) and nothing changes.
460    /// Moving editors to another display changes their scale, which plugins redraw for; closing
461    /// and opening them again there avoids that.
462    pub fn set_remote_region(&mut self, region: remote::Region) -> Result<(), Error> {
463        self.request_done(Request::SetRemoteRegion { region }, self.timeouts.control)
464    }
465
466    /// Opens the editor of the plugin in `slot` for someone not in front of the machine, in a
467    /// borderless window [`remote::EDITOR_INSET`] points in from the top-left corner of the
468    /// region [`Chain::set_remote_region`] set, which the application reads and shows them. The
469    /// editor is shown and the remote editor shown before is hidden, not closed, so it keeps its
470    /// state; an editor already open is shown again. Returns the editor and its size.
471    ///
472    /// Needs a remote chain ([`SpawnOptions::remote`]) and a region, without which it fails as
473    /// [`InputError::RemoteRegion`](crate::InputError::RemoteRegion). An Audio Unit v3 editor,
474    /// which runs in its extension's process, and an editor that draws only in its own window
475    /// fail as unsupported. Close it with [`Chain::close_editor`].
476    pub fn open_remote_editor(&mut self, slot: usize) -> Result<remote::Opened, Error> {
477        match self.request(Request::OpenRemoteEditor { slot }, self.timeouts.load)? {
478            Response::RemoteEditorOpened(opened) => Ok(opened),
479            _ => Err(self.protocol_error()),
480        }
481    }
482
483    /// Shows the open remote editor of `slot` and hides the one shown before.
484    pub fn show_remote_editor(&mut self, slot: usize) -> Result<(), Error> {
485        self.request_done(Request::ShowRemoteEditor { slot }, self.timeouts.control)
486    }
487
488    /// Starts a remote session (macOS only): the channel on which the helper tells what happens
489    /// to its remote editors as it happens, beginning with the current state. A later session
490    /// ends this one. Needs a remote chain ([`SpawnOptions::remote`]).
491    #[cfg(target_os = "macos")]
492    pub fn remote_session(&mut self) -> Result<remote::Session, Error> {
493        let (commands_read, commands_write) = remote::pipe().map_err(Error::RemoteChannel)?;
494        let (notices_read, notices_write) = remote::pipe().map_err(Error::RemoteChannel)?;
495        let commands = self.helper.send_channel(&commands_read)?;
496        let notices = self.helper.send_channel(&notices_write)?;
497        drop((commands_read, notices_write));
498        let menu_timeout_ms = u64::try_from(self.timeouts.menu.as_millis()).unwrap_or(u64::MAX);
499        self.request_done(
500            Request::RemoteSession {
501                commands,
502                notices,
503                menu_timeout_ms,
504            },
505            self.timeouts.control,
506        )?;
507        Ok(remote::Session::new(notices_read, commands_write))
508    }
509
510    fn request(&mut self, request: Request<'_>, timeout: Duration) -> Result<Response, Error> {
511        let result = self.helper.request(request, timeout);
512        if matches!(
513            result,
514            Err(Error::Protocol
515                | Error::Crashed { .. }
516                | Error::TimedOut { .. }
517                | Error::Cancelled { .. })
518        ) {
519            self.shared = None;
520        }
521        result
522    }
523
524    fn request_done(&mut self, request: Request<'_>, timeout: Duration) -> Result<(), Error> {
525        match self.request(request, timeout)? {
526            Response::Done => Ok(()),
527            _ => Err(self.protocol_error()),
528        }
529    }
530
531    /// Reads the chain's latency and tail from the helper, and whether a plugin announced a
532    /// latency that is not applied yet.
533    fn read_timing(&mut self) -> Result<bool, Error> {
534        if !self.is_prepared() {
535            return Ok(false);
536        }
537        self.request_timing(Request::Timing)
538    }
539
540    /// Sends a parameter edit, after which the helper reads the timing again, except under a
541    /// running realtime endpoint, whose timing changes arrive through [`Chain::take_changes`].
542    fn request_edit(&mut self, request: Request<'_>) -> Result<(), Error> {
543        if self.realtime_running() {
544            return self.request_done(request, self.timeouts.control);
545        }
546        self.request_refreshed(request)
547    }
548
549    /// Sends a change after which the helper reads the timing again. A change that took effect
550    /// while a slot's timing could not be read is answered without the timing, keeping the
551    /// cached one; the helper's diagnostics name the slot.
552    fn request_refreshed(&mut self, request: Request<'_>) -> Result<(), Error> {
553        match self.request(request, self.timeouts.control)? {
554            Response::Timing { latency, tail, .. } => {
555                self.latency = latency;
556                self.tail = tail;
557                Ok(())
558            }
559            Response::Done => Ok(()),
560            _ => Err(self.protocol_error()),
561        }
562    }
563
564    fn request_timing(&mut self, request: Request<'_>) -> Result<bool, Error> {
565        match self.request(request, self.timeouts.control)? {
566            Response::Timing {
567                latency,
568                tail,
569                latency_changed,
570            } => {
571                self.latency = latency;
572                self.tail = tail;
573                Ok(latency_changed)
574            }
575            _ => Err(self.protocol_error()),
576        }
577    }
578
579    fn is_prepared(&self) -> bool {
580        self.shared.is_some()
581    }
582}
583
584/// Starts a helper and loads the slots' plugins, restoring each state as its plugin loads and
585/// then setting the bypass and the host bypass.
586fn start(
587    helper: &Path,
588    slots: &[ChainSlot],
589    host: &HostIdentity,
590    timeouts: Timeouts,
591    remote: bool,
592) -> Result<Chain, Error> {
593    if remote && !cfg!(target_os = "macos") {
594        return Err(Error::Operation {
595            slot: None,
596            failure: plughost_core::Failure::new(
597                plughost_core::FailureKind::Unsupported,
598                crate::errors::REMOTE_UNSUPPORTED,
599            ),
600        });
601    }
602    if slots.is_empty() {
603        return Err(Error::Input {
604            slot: None,
605            error: plughost_core::InputError::EmptyChain,
606        });
607    }
608    for (slot, spec) in slots.iter().enumerate() {
609        validate_slot(slot, spec)?;
610    }
611    let plugins: Vec<PluginRef> = slots.iter().map(|spec| spec.plugin.clone()).collect();
612    let plugins = plugins.as_slice();
613    let mode = if remote { Mode::Remote } else { Mode::Host };
614    let mut process = Helper::spawn(helper, mode)?;
615    let infos = match process.load(host, plugins, timeouts.load)? {
616        Response::Loaded(infos) if infos.len() == plugins.len() => infos,
617        _ => return Err(Error::Protocol),
618    };
619    for (slot, spec) in slots.iter().enumerate() {
620        if let Some(state) = &spec.state {
621            let request = Request::LoadState {
622                slot,
623                state: std::borrow::Cow::Borrowed(state),
624            };
625            expect_done(process.request(request, timeouts.load)?)?;
626        }
627    }
628    let mut chain = Chain {
629        identity: host.clone(),
630        helper_path: helper.to_path_buf(),
631        helper: process,
632        remote,
633        plugins: plugins.to_vec(),
634        infos,
635        timeouts,
636        config: None,
637        shared: None,
638        generation: 0,
639        latency: 0,
640        tail: Tail::Samples(0),
641        realtime: None,
642    };
643    for (slot, spec) in slots.iter().enumerate() {
644        if let Some(enabled) = spec.bypass {
645            chain.set_bypass(slot, enabled)?;
646        }
647        if spec.host_bypass {
648            chain.set_host_bypass(slot, true)?;
649        }
650    }
651    Ok(chain)
652}
653
654/// Refuses a slot whose bundle path the helper cannot be given or whose state is malformed.
655fn validate_slot(slot: usize, spec: &ChainSlot) -> Result<(), Error> {
656    if spec
657        .plugin
658        .bundle()
659        .is_some_and(|path| path.to_str().is_none())
660    {
661        return Err(Error::Input {
662            slot: Some(slot),
663            error: plughost_core::InputError::PathEncoding,
664        });
665    }
666    if let Some(state) = &spec.state {
667        state.validate().map_err(|error| Error::Input {
668            slot: Some(slot),
669            error,
670        })?;
671    }
672    Ok(())
673}
674
675fn expect_done(response: Response) -> Result<(), Error> {
676    match response {
677        Response::Done => Ok(()),
678        _ => Err(Error::Protocol),
679    }
680}