Skip to main content

plughost_helper/
lib.rs

1//! Helper process that loads and runs plugins for plughost.
2//!
3//! Applications build a small executable whose `main` calls [`run`], ship it with the same
4//! plughost version, and pass its path to the plughost crate. The application starts the helper
5//! with `<scan|host> <socket name> <token> <parent pid>`; the helper connects back for control messages and
6//! completion notifications. PCM and events use prepared shared memory. On Unix, host startup
7//! takes a handle-transfer socket from stdin and restores null stdin before loading plugins.
8//! Standard output remains available to plugins and is never used for protocol messages.
9//!
10//! An IPC thread receives requests and passes audio blocks to a processing thread, so a main
11//! thread held up by a plugin (a modal dialog, a window being dragged) does not stall audio. The
12//! processing thread owns the chain's processing state and also makes the audio-thread calls
13//! plugins need between blocks. The main thread makes every other plugin call, runs the editors,
14//! and runs the OS event loop between requests, since plugins' dialogs, timers, and editors
15//! depend on it. Both threads record the slot they are calling in the application's activity
16//! mapping.
17
18mod calls;
19mod editor;
20mod errors;
21mod events;
22mod host;
23mod lifetime;
24mod presets;
25mod process;
26#[cfg(target_os = "macos")]
27mod remote;
28mod scan;
29
30use std::io;
31use std::process::ExitCode;
32use std::sync::{Arc, Mutex, PoisonError, mpsc};
33use std::thread;
34use std::time::{Duration, Instant};
35
36use interprocess::local_socket::prelude::*;
37use interprocess::local_socket::{GenericNamespaced, Stream};
38use plughost_core::internal::DiagnosticBuffer;
39use plughost_core::ipc::shared::transfer;
40use plughost_core::ipc::{
41    Hello, MessageReader, MessageWriter, PROTOCOL_VERSION, Request, Response,
42};
43use plughost_core::{Failure, FailureKind};
44
45use crate::errors::{CONNECT, USAGE};
46
47/// The audit build counts the host's allocations on the processing thread. Unit tests count
48/// allocations with their own.
49#[cfg(all(feature = "realtime-audit", not(test)))]
50#[global_allocator]
51static ALLOCATOR: plughost_core::audit::Allocator = plughost_core::audit::Allocator;
52
53/// How often the main thread services OS events, including while requests keep arriving.
54const EVENT_INTERVAL: Duration = Duration::from_millis(10);
55
56#[derive(Clone, Copy, PartialEq, Eq)]
57enum Mode {
58    Scan,
59    Host,
60    /// Host mode for remote editors (macOS): the helper never activates itself.
61    #[cfg(target_os = "macos")]
62    Remote,
63}
64
65/// Runs the helper until the application disconnects or asks it to shut down.
66pub fn run() -> ExitCode {
67    abort_on_panic();
68    let args: Vec<String> = std::env::args().skip(1).collect();
69    let parsed = match args.as_slice() {
70        [mode, name, token, parent] => {
71            let mode = match mode.as_str() {
72                "scan" => Some(Mode::Scan),
73                "host" => Some(Mode::Host),
74                #[cfg(target_os = "macos")]
75                "remote" => Some(Mode::Remote),
76                _ => None,
77            };
78            mode.zip(u64::from_str_radix(token, 16).ok())
79                .zip(parent.parse::<u32>().ok())
80                .map(|((mode, token), parent)| (mode, name.as_str(), token, parent))
81        }
82        _ => None,
83    };
84    let Some((mode, name, token, parent)) = parsed else {
85        errors::report(USAGE);
86        return ExitCode::from(2);
87    };
88    if let Err(error) = lifetime::watch_parent(parent) {
89        errors::report(&error.to_string());
90        return ExitCode::FAILURE;
91    }
92    match serve(mode, name, token) {
93        Ok(()) => {
94            #[cfg(feature = "realtime-audit")]
95            errors::report(&plughost_core::audit::report());
96            ExitCode::SUCCESS
97        }
98        Err(error) => {
99            errors::report(&format!("{CONNECT}: {error}"));
100            ExitCode::FAILURE
101        }
102    }
103}
104
105/// Ends the whole helper on any panic, after the default report. A panic that unwound instead
106/// would end one thread without a reply, clear the slot that thread recorded, and leave the
107/// application waiting for a timeout that names no slot; a panic in a VST3 or Objective-C
108/// callback cannot unwind at all. An abort keeps the slot recorded, so the application reports
109/// a crash of it. clack-host catches a panic in a CLAP host callback and goes on, which this
110/// replaces with the abort too: the state the panic left behind is not known to be sound.
111fn abort_on_panic() {
112    let report = std::panic::take_hook();
113    std::panic::set_hook(Box::new(move |info| {
114        report(info);
115        std::process::abort();
116    }));
117}
118
119fn serve(mode: Mode, name: &str, token: u64) -> io::Result<()> {
120    let _runtime = events::init(mode != Mode::Scan)?;
121    // Before any plugin loads, so none sees the helper activate or inactive.
122    #[cfg(target_os = "macos")]
123    if mode == Mode::Remote
124        && let Some(mtm) = objc2::MainThreadMarker::new()
125    {
126        remote::enter();
127        remote::input::install(mtm);
128    }
129    let stream = Arc::new(Stream::connect(name.to_ns_name::<GenericNamespaced>()?)?);
130    let receive = Connection(Arc::clone(&stream));
131    let mut send = MessageWriter::new(Connection(stream));
132    send.write(&Hello {
133        protocol: PROTOCOL_VERSION,
134        token,
135    })?;
136    let responder = Responder {
137        send: Arc::new(Mutex::new(send)),
138        waiting: Arc::new(Mutex::new(Waiting {
139            requests: 0,
140            since: Instant::now(),
141        })),
142        diagnostics: DiagnosticBuffer::default(),
143    };
144    #[cfg(target_os = "macos")]
145    if mode == Mode::Remote {
146        let responder = responder.clone();
147        thread::spawn(move || {
148            loop {
149                thread::sleep(KEEP_ALIVE / 4);
150                if responder.keep_alive().is_err() {
151                    break;
152                }
153            }
154        });
155    }
156
157    let (requests, incoming) = mpsc::channel::<Request<'static>>();
158    let mut host = None;
159    let mut blocks = None;
160    let mut transfers = None;
161    if mode != Mode::Scan {
162        let (processing, work) = process::Processing::spawn(responder.clone())?;
163        #[cfg(target_os = "macos")]
164        let remote = mode == Mode::Remote;
165        #[cfg(target_os = "windows")]
166        let remote = false;
167        let transfer = Arc::new(transfer::Receiver::take_from_stdin()?);
168        transfers = Some(Arc::clone(&transfer));
169        host = Some(host::Host::new(
170            transfer,
171            responder.clone(),
172            processing,
173            remote,
174        ));
175        blocks = Some(work);
176    }
177    let reader = responder.clone();
178    // Only a remote-mode helper keeps the requests its main thread holds alive.
179    #[cfg(target_os = "macos")]
180    let counted = mode == Mode::Remote;
181    #[cfg(target_os = "windows")]
182    let counted = false;
183    // A remote-mode helper starts its sessions on this reader.
184    let sessions = transfers.filter(|_| counted);
185    thread::spawn(move || {
186        let responder = reader;
187        let mut receive = MessageReader::new(receive);
188        while let Ok(request) = receive.read::<Request<'static>>() {
189            let handled = match (request, &blocks, &sessions) {
190                (
191                    Request::Process {
192                        context,
193                        submission,
194                    },
195                    Some(blocks),
196                    _,
197                ) => blocks
198                    .send(process::Work::Block {
199                        context,
200                        submission,
201                    })
202                    .is_ok(),
203                // Not through the main thread, which a plugin's dialog or menu may hold.
204                #[cfg(target_os = "macos")]
205                (
206                    Request::RemoteSession {
207                        commands,
208                        notices,
209                        menu_timeout_ms,
210                    },
211                    _,
212                    Some(transfer),
213                ) => {
214                    let response = remote::session::open(
215                        transfer,
216                        commands,
217                        notices,
218                        Duration::from_millis(menu_timeout_ms),
219                    );
220                    responder.send(&response).is_ok()
221                }
222                (request, _, _) => {
223                    if counted {
224                        responder.begin();
225                    }
226                    let sent = requests.send(request).is_ok();
227                    events::wake();
228                    sent
229                }
230            };
231            if !handled {
232                break;
233            }
234        }
235        // This reader must terminate a modal/hung main thread when its owner disconnects.
236        lifetime::disconnected();
237    });
238
239    let mut next_tick = Instant::now() + EVENT_INTERVAL;
240    loop {
241        if Instant::now() >= next_tick {
242            events::with_pool(|| {
243                events::pump();
244                if let Some(host) = &mut host {
245                    host.tick();
246                }
247            });
248            next_tick = Instant::now() + EVENT_INTERVAL;
249        }
250        // macOS waits on the main run loop, which the reader wakes, so run loop sources, timers
251        // and the main queue run while the helper waits.
252        #[cfg(target_os = "macos")]
253        let request = match incoming.try_recv() {
254            Ok(Request::Shutdown) | Err(mpsc::TryRecvError::Disconnected) => return Ok(()),
255            Ok(request) => request,
256            Err(mpsc::TryRecvError::Empty) => {
257                events::with_pool(|| {
258                    events::wait(next_tick.saturating_duration_since(Instant::now()));
259                });
260                continue;
261            }
262        };
263        #[cfg(target_os = "windows")]
264        let request =
265            match incoming.recv_timeout(next_tick.saturating_duration_since(Instant::now())) {
266                Ok(Request::Shutdown) | Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(()),
267                Ok(request) => request,
268                Err(mpsc::RecvTimeoutError::Timeout) => continue,
269            };
270        #[cfg(target_os = "macos")]
271        events::with_pool(|| events::handling(|| handle(&mut host, request, &responder)))?;
272        #[cfg(target_os = "windows")]
273        events::with_pool(|| handle(&mut host, request, &responder))?;
274    }
275}
276
277/// Serves one request on the main thread.
278fn handle(
279    host: &mut Option<host::Host>,
280    request: Request<'_>,
281    responder: &Responder,
282) -> io::Result<()> {
283    match (host, request) {
284        (
285            None,
286            Request::Scan {
287                bundle,
288                host,
289                interactive,
290            },
291        ) => {
292            if interactive {
293                events::activate();
294            }
295            scan::scan(&bundle, &host, responder)?
296        }
297        (None, Request::PresetProviders { bundle, host }) => {
298            presets::providers(&bundle, &host, responder)?
299        }
300        (
301            None,
302            Request::DiscoverPresets {
303                bundle,
304                host,
305                target,
306            },
307        ) => presets::discover(&bundle, &host, &target, responder)?,
308        (None, Request::ListAudioUnits) => scan::list_audio_units(responder)?,
309        (Some(host), request) => responder.answer(&host.handle(request))?,
310        (None, _) => responder.fail(
311            None,
312            Failure::new(FailureKind::Protocol, errors::WRONG_MODE),
313        )?,
314    }
315    Ok(())
316}
317
318/// How long a request the main thread holds goes without a message to the application before a
319/// remote-mode helper keeps it alive. The helper checks four times as often, so the application
320/// hears at most a quarter of it later.
321#[cfg(target_os = "macos")]
322const KEEP_ALIVE: Duration = Duration::from_secs(1);
323
324/// The requests a remote-mode helper's main thread has yet to answer, and since when it works on
325/// the first of them or last kept them alive. It is apart from the writer: the reader thread
326/// records requests while the main thread may wait to write a response the application does not
327/// read yet.
328struct Waiting {
329    requests: usize,
330    since: Instant,
331}
332
333/// The connection to the application, which the request reader and the responders share: a
334/// stream reads and writes through a shared reference, and the connection closes when the last
335/// one goes.
336pub(crate) struct Connection(Arc<Stream>);
337
338impl io::Read for Connection {
339    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
340        (&*self.0).read(buffer)
341    }
342}
343
344impl io::Write for Connection {
345    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
346        (&*self.0).write(buffer)
347    }
348
349    fn flush(&mut self) -> io::Result<()> {
350        (&*self.0).flush()
351    }
352}
353
354/// Writes responses to the application, from the main thread and the processing thread. The
355/// application sends one request at a time, so their responses do not interleave.
356#[derive(Clone)]
357pub(crate) struct Responder {
358    send: Arc<Mutex<MessageWriter<Connection>>>,
359    waiting: Arc<Mutex<Waiting>>,
360    diagnostics: DiagnosticBuffer,
361}
362
363impl Responder {
364    /// Writes one response. A failure is also kept for the application's diagnostics drain.
365    pub fn send(&self, response: &Response) -> io::Result<()> {
366        if let Response::Failed { slot, failure } = response {
367            record_failure(&self.diagnostics, *slot, failure);
368        }
369        self.writer().write(response)
370    }
371
372    /// Writes the main thread's answer to a request, which it then no longer holds.
373    fn answer(&self, response: &Response) -> io::Result<()> {
374        if let Response::Failed { slot, failure } = response {
375            record_failure(&self.diagnostics, *slot, failure);
376        }
377        let mut writer = self.writer();
378        let written = writer.write(response);
379        let mut waiting = self.waiting();
380        waiting.requests = waiting.requests.saturating_sub(1);
381        waiting.since = Instant::now();
382        written
383    }
384
385    fn writer(&self) -> std::sync::MutexGuard<'_, MessageWriter<Connection>> {
386        self.send.lock().unwrap_or_else(PoisonError::into_inner)
387    }
388
389    fn waiting(&self) -> std::sync::MutexGuard<'_, Waiting> {
390        self.waiting.lock().unwrap_or_else(PoisonError::into_inner)
391    }
392
393    /// Records that the main thread has a request to answer.
394    fn begin(&self) {
395        let mut waiting = self.waiting();
396        if waiting.requests == 0 {
397            waiting.since = Instant::now();
398        }
399        waiting.requests += 1;
400    }
401
402    /// Keeps a request the main thread has held for a while alive while its run loop runs, in
403    /// a dialog's, a menu's or a panel's loop. A main thread held up outside any loop sends
404    /// nothing, and the application's timeout ends the helper as before.
405    #[cfg(target_os = "macos")]
406    fn keep_alive(&self) -> io::Result<()> {
407        // The writer first, as `answer` takes them: an answer written meanwhile is seen.
408        let mut writer = self.writer();
409        let held = {
410            let waiting = self.waiting();
411            waiting.requests > 0 && waiting.since.elapsed() >= KEEP_ALIVE
412        };
413        if held && remote::watch::running_within(KEEP_ALIVE) {
414            writer.write(&Response::Progress)?;
415            self.waiting().since = Instant::now();
416        }
417        Ok(())
418    }
419
420    pub fn fail(&self, slot: Option<usize>, failure: Failure) -> io::Result<()> {
421        self.send(&Response::Failed { slot, failure })
422    }
423
424    /// Keeps a warning about the helper itself for the application's diagnostics drain.
425    pub fn warn(&self, message: &str) {
426        self.diagnostics.record(
427            plughost_core::DiagnosticSeverity::Warning,
428            message,
429            None,
430            None,
431            None,
432        );
433    }
434}
435
436pub(crate) fn record_failure(
437    diagnostics: &DiagnosticBuffer,
438    slot: Option<usize>,
439    failure: &Failure,
440) {
441    diagnostics.record(
442        plughost_core::DiagnosticSeverity::Error,
443        &failure.message,
444        None,
445        slot,
446        Some(failure.kind),
447    );
448}