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
//! Request and response I/O on the supervising thread itself. Every read and write stops at its
//! deadline and keeps its place in the frame, so the supervisor enforces deadlines and polls
//! cancellation without handing messages to other threads. Windows named pipes have no read
//! timeout, so they use overlapped I/O; Unix sockets are polled.

use std::io;
use std::time::{Duration, Instant};

use interprocess::local_socket::Stream;
use plughost_core::ipc::{FrameDecoder, Hello, Request, Response, encode_message};

const RETAINED_BYTES: usize = 64 << 10;

pub(super) enum Incoming {
    Hello(Hello),
    Response(Response),
}

/// Why a read or write ended without its message.
#[derive(Debug)]
pub(super) enum Stopped {
    /// The deadline passed; the operation can be continued.
    TimedOut,
    /// The connection closed or failed, or the transport was closed.
    Closed,
}

/// Why a request was not queued.
#[derive(Debug)]
pub(super) enum Unqueued {
    /// The transport was closed, or the previous request is not written yet.
    Closed,
    /// The request could not be encoded, such as one larger than a message may be.
    Unencodable,
}

pub(super) struct Transport {
    pipe: Option<pipe::Pipe>,
    decoder: FrameDecoder,
    greeted: bool,
    /// The frame being written, and how much of it was written.
    outgoing: Vec<u8>,
    written: usize,
}

impl Transport {
    pub fn new(stream: Stream) -> io::Result<Self> {
        Ok(Self {
            pipe: Some(pipe::Pipe::new(stream)?),
            decoder: FrameDecoder::default(),
            greeted: false,
            outgoing: Vec::new(),
            written: 0,
        })
    }

    /// Starts writing `request`; [`Transport::flush`] writes it. The previous request must have
    /// been flushed.
    pub fn queue(&mut self, request: &Request<'_>) -> Result<(), Unqueued> {
        if self.pipe.is_none() || self.written < self.outgoing.len() {
            return Err(Unqueued::Closed);
        }
        encode_message(&mut self.outgoing, request).map_err(|_| {
            self.outgoing.shrink_to(RETAINED_BYTES);
            Unqueued::Unencodable
        })?;
        self.written = 0;
        Ok(())
    }

    /// Writes the rest of the queued request. A request that times out part-written leaves the
    /// stream mid-frame: continue it, or close the connection.
    pub fn flush(&mut self, timeout: Duration) -> Result<(), Stopped> {
        let deadline = Instant::now().checked_add(timeout);
        let pipe = self.pipe.as_mut().ok_or(Stopped::Closed)?;
        while self.written < self.outgoing.len() {
            match pipe.write(&self.outgoing[self.written..], remaining(deadline, timeout)) {
                Ok(Some(0)) | Err(_) => return Err(Stopped::Closed),
                Ok(Some(count)) => self.written += count,
                Ok(None) => return Err(Stopped::TimedOut),
            }
        }
        // Windows releases its overlapped write before returning the final byte count above.
        // Incomplete writes retain the original allocation unchanged for their next flush.
        self.outgoing.clear();
        self.outgoing.shrink_to(RETAINED_BYTES);
        self.written = 0;
        Ok(())
    }

    /// Reads the next message. The first message is the helper's hello; a read that times out
    /// part-way keeps the partial frame for the next call. A malformed frame is `InvalidData`.
    pub fn receive(&mut self, timeout: Duration) -> Result<io::Result<Incoming>, Stopped> {
        let deadline = Instant::now().checked_add(timeout);
        let pipe = self.pipe.as_mut().ok_or(Stopped::Closed)?;
        loop {
            if self.greeted {
                if let Some(message) = self.decoder.message::<Response>() {
                    return Ok(message.map(Incoming::Response));
                }
            } else if let Some(message) = self.decoder.message::<Hello>() {
                self.greeted = message.is_ok();
                return Ok(message.map(Incoming::Hello));
            }
            let unfilled = match self.decoder.unfilled() {
                Ok(unfilled) => unfilled,
                Err(error) => return Ok(Err(error)),
            };
            match pipe.read(unfilled, remaining(deadline, timeout)) {
                Ok(Some(0)) | Err(_) => return Err(Stopped::Closed),
                Ok(Some(count)) => self.decoder.advance(count),
                Ok(None) => return Err(Stopped::TimedOut),
            }
        }
    }

    /// Closes the connection. The owner terminates the helper first; later calls report `Closed`.
    pub fn close(&mut self) {
        // Drop cancels and completes any pending Windows write before its storage is released.
        self.pipe = None;
        self.outgoing = Vec::new();
        self.written = 0;
        self.decoder = FrameDecoder::default();
    }
}

/// What is left of `timeout` before `deadline`. A timeout too long for an `Instant` deadline has
/// none and stays whole.
fn remaining(deadline: Option<Instant>, timeout: Duration) -> Duration {
    deadline.map_or(timeout, |deadline| {
        deadline.saturating_duration_since(Instant::now())
    })
}

#[cfg(windows)]
mod pipe {
    use std::io;
    use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
    use std::time::Duration;

    use interprocess::local_socket::Stream;
    use windows_sys::Win32::Foundation::{
        ERROR_BROKEN_PIPE, ERROR_IO_INCOMPLETE, ERROR_IO_PENDING, ERROR_OPERATION_ABORTED,
        GetLastError, HANDLE, WAIT_TIMEOUT,
    };
    use windows_sys::Win32::Storage::FileSystem::{ReadFile, WriteFile};
    use windows_sys::Win32::System::IO::{
        CancelIoEx, GetOverlappedResult, GetOverlappedResultEx, OVERLAPPED,
    };
    use windows_sys::Win32::System::Threading::CreateEventW;

    /// The pipe handle, which interprocess opens for overlapped I/O, and the events its reads and
    /// writes signal.
    pub struct Pipe {
        handle: OwnedHandle,
        read_event: OwnedHandle,
        write_event: OwnedHandle,
        /// A write that outlived its timeout. It is never cancelled while the connection is open:
        /// a cancelled pipe write can leave part of its buffer sent while reporting none sent.
        pending_write: Option<Box<PendingWrite>>,
    }

    /// Kernel-owned progress for the one outstanding write. Boxing it keeps its address stable
    /// when the transport moves to another thread.
    struct PendingWrite(OVERLAPPED);

    // SAFETY: no field is read or changed by Rust while Windows owns the operation. Every
    // operation needs `&mut Pipe`; the event and pipe handles have no thread affinity. Pipe's
    // Drop cancels and joins the operation before this box or its write buffer can be freed.
    unsafe impl Send for PendingWrite {}
    // SAFETY: shared references to Pipe expose no OVERLAPPED access or concurrent I/O. All
    // progress is obtained through Windows' synchronization APIs under exclusive Pipe access.
    unsafe impl Sync for PendingWrite {}

    fn event() -> io::Result<OwnedHandle> {
        // SAFETY: a manual-reset event with default security; the handle is owned below.
        let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
        if event.is_null() {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: CreateEventW returned a new handle that nothing else owns.
        Ok(unsafe { OwnedHandle::from_raw_handle(event) })
    }

    /// Milliseconds to wait, rounded up so that a remaining fraction still waits.
    fn millis(timeout: Duration) -> u32 {
        u32::try_from(timeout.as_micros().div_ceil(1000))
            .unwrap_or(u32::MAX - 1)
            .min(u32::MAX - 1)
    }

    impl Pipe {
        pub fn new(stream: Stream) -> io::Result<Self> {
            let Stream::NamedPipe(pipe) = stream;
            Ok(Self {
                handle: OwnedHandle::from(pipe),
                read_event: event()?,
                write_event: event()?,
                pending_write: None,
            })
        }

        /// Reads into `buffer`: the byte count, 0 at the end of the stream, or `None` when the
        /// timeout passes first.
        pub fn read(&mut self, buffer: &mut [u8], timeout: Duration) -> io::Result<Option<usize>> {
            let length = u32::try_from(buffer.len()).unwrap_or(u32::MAX);
            let data = buffer.as_mut_ptr();
            // SAFETY: `buffer` outlives the operation, which `overlapped` waits for or cancels.
            self.overlapped(timeout, |handle, overlapped| unsafe {
                ReadFile(handle, data, length, std::ptr::null_mut(), overlapped)
            })
        }

        /// Writes from `buffer`, returning the byte count or `None` when the timeout passes first.
        /// A write that times out stays in progress: the next call waits for it and must pass
        /// the same, unchanged buffer, which stays in use until the write completes or the pipe
        /// is dropped.
        pub fn write(&mut self, buffer: &[u8], timeout: Duration) -> io::Result<Option<usize>> {
            let handle = self.handle.as_raw_handle();
            if self.pending_write.is_none() {
                // SAFETY: OVERLAPPED is plain C data, boxed so it stays in place while the write
                // is in progress.
                let mut overlapped = Box::new(PendingWrite(unsafe { std::mem::zeroed() }));
                overlapped.0.hEvent = self.write_event.as_raw_handle();
                let length = u32::try_from(buffer.len()).unwrap_or(u32::MAX);
                // SAFETY: the caller keeps `buffer` unchanged until the write completes, and
                // `Drop` waits for a write still in progress.
                let started = unsafe {
                    WriteFile(
                        handle,
                        buffer.as_ptr(),
                        length,
                        std::ptr::null_mut(),
                        &mut overlapped.0,
                    )
                };
                if started == 0 {
                    match unsafe { GetLastError() } {
                        ERROR_IO_PENDING => {}
                        ERROR_BROKEN_PIPE => return Ok(Some(0)),
                        error => return Err(io::Error::from_raw_os_error(error as i32)),
                    }
                }
                self.pending_write = Some(overlapped);
            }
            let Some(overlapped) = &self.pending_write else {
                unreachable!()
            };
            let mut count = 0;
            // SAFETY: `overlapped` belongs to the write in progress on this handle.
            let done = unsafe {
                GetOverlappedResultEx(handle, &overlapped.0, &mut count, millis(timeout), 0)
            };
            if done != 0 {
                self.pending_write = None;
                return Ok(Some(count as usize));
            }
            match unsafe { GetLastError() } {
                // A zero timeout reports an unfinished operation as incomplete instead.
                WAIT_TIMEOUT | ERROR_IO_INCOMPLETE => Ok(None),
                ERROR_BROKEN_PIPE => {
                    self.pending_write = None;
                    Ok(Some(0))
                }
                error => {
                    self.pending_write = None;
                    Err(io::Error::from_raw_os_error(error as i32))
                }
            }
        }

        /// Starts a read and waits for it until the timeout; a timed-out read is cancelled and
        /// waited for, since it may have completed meanwhile.
        fn overlapped(
            &mut self,
            timeout: Duration,
            start: impl FnOnce(HANDLE, *mut OVERLAPPED) -> i32,
        ) -> io::Result<Option<usize>> {
            let handle = self.handle.as_raw_handle();
            // SAFETY: OVERLAPPED is plain C data; the operation owns it until it completes.
            let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
            overlapped.hEvent = self.read_event.as_raw_handle();
            if start(handle, &mut overlapped) == 0 {
                match unsafe { GetLastError() } {
                    ERROR_IO_PENDING => {}
                    ERROR_BROKEN_PIPE => return Ok(Some(0)),
                    error => return Err(io::Error::from_raw_os_error(error as i32)),
                }
            }
            let mut count = 0;
            // SAFETY: `overlapped` belongs to the operation started above on this handle.
            let done = unsafe {
                GetOverlappedResultEx(handle, &overlapped, &mut count, millis(timeout), 0)
            };
            if done != 0 {
                return Ok(Some(count as usize));
            }
            // A zero timeout reports an unfinished operation as incomplete instead.
            match unsafe { GetLastError() } {
                WAIT_TIMEOUT | ERROR_IO_INCOMPLETE => {
                    // SAFETY: as above; the final result is read before `overlapped` is dropped.
                    unsafe { CancelIoEx(handle, &overlapped) };
                    if unsafe { GetOverlappedResult(handle, &overlapped, &mut count, 1) } != 0 {
                        return Ok(Some(count as usize));
                    }
                    match unsafe { GetLastError() } {
                        ERROR_OPERATION_ABORTED => Ok(None),
                        ERROR_BROKEN_PIPE => Ok(Some(0)),
                        error => Err(io::Error::from_raw_os_error(error as i32)),
                    }
                }
                ERROR_BROKEN_PIPE => Ok(Some(0)),
                error => Err(io::Error::from_raw_os_error(error as i32)),
            }
        }
    }

    impl Drop for Pipe {
        /// Stops a write still in progress and waits for it, so that neither its OVERLAPPED nor
        /// the buffer it reads is freed while Windows uses them. The owner terminates the helper
        /// first, so the stream is abandoned either way.
        fn drop(&mut self) {
            if let Some(overlapped) = &self.pending_write {
                let handle = self.handle.as_raw_handle();
                let mut count = 0;
                // SAFETY: `overlapped` belongs to the write in progress on this handle.
                unsafe {
                    CancelIoEx(handle, &overlapped.0);
                    GetOverlappedResult(handle, &overlapped.0, &mut count, 1);
                }
            }
        }
    }
}

#[cfg(unix)]
mod pipe {
    use std::io::{self, Read};
    use std::os::unix::net::UnixStream;
    use std::time::{Duration, Instant};

    use interprocess::local_socket::Stream;
    use rustix::event::{PollFd, PollFlags, Timespec, poll};

    /// A non-blocking socket, waited on with `poll`.
    pub struct Pipe {
        stream: UnixStream,
    }

    impl Pipe {
        pub fn new(stream: Stream) -> io::Result<Self> {
            let Stream::UdSocket(socket) = stream;
            let stream = socket.inner().try_clone()?;
            stream.set_nonblocking(true)?;
            Ok(Self { stream })
        }

        /// Reads into `buffer`: the byte count, 0 at the end of the stream, or `None` when the
        /// timeout passes first.
        pub fn read(&mut self, buffer: &mut [u8], timeout: Duration) -> io::Result<Option<usize>> {
            self.retry(timeout, PollFlags::IN, |stream| stream.read(buffer))
        }

        /// Writes from `buffer`, returning the byte count or `None` when the timeout passes first.
        pub fn write(&mut self, buffer: &[u8], timeout: Duration) -> io::Result<Option<usize>> {
            self.retry(timeout, PollFlags::OUT, |stream| {
                // Per-send suppression works even if the peer disconnected before accept.
                // rustix does not expose Apple's flag, so take it from the system bindings.
                let flags = rustix::net::SendFlags::from_bits_retain(libc::MSG_NOSIGNAL as u32);
                rustix::net::send(stream, buffer, flags).map_err(Into::into)
            })
        }

        fn retry(
            &mut self,
            timeout: Duration,
            ready: PollFlags,
            mut operation: impl FnMut(&mut UnixStream) -> io::Result<usize>,
        ) -> io::Result<Option<usize>> {
            let deadline = Instant::now().checked_add(timeout);
            loop {
                match operation(&mut self.stream) {
                    Ok(count) => return Ok(Some(count)),
                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
                    Err(error) => return Err(error),
                }
                // Without a representable deadline the wait has no end.
                let timespec = match deadline {
                    Some(deadline) => {
                        let remaining = deadline.saturating_duration_since(Instant::now());
                        if remaining.is_zero() {
                            return Ok(None);
                        }
                        Some(Timespec::try_from(remaining).map_err(io::Error::other)?)
                    }
                    None => None,
                };
                let mut fds = [PollFd::new(&self.stream, ready)];
                match poll(&mut fds, timespec.as_ref()) {
                    Ok(_) | Err(rustix::io::Errno::INTR) => {}
                    Err(error) => return Err(error.into()),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests;