Skip to main content

maolan_engine/plugins/
ipc.rs

1//! Shared IPC helpers for out-of-process plugin processors.
2
3use crate::audio::io::AudioIO;
4use crate::mutex::UnsafeMutex;
5use maolan_plugin_protocol::events::EventPair;
6use maolan_plugin_protocol::protocol::*;
7use maolan_plugin_protocol::shm::ShmMapping;
8use std::path::{Path, PathBuf};
9use std::process::{Child, Command, Stdio};
10use std::sync::Arc;
11use std::sync::atomic::Ordering;
12use std::time::{Duration, Instant};
13
14/// Arguments for spawning a plugin host subprocess.
15pub struct HostSpawnArgs<'a> {
16    pub host_binary: &'a Path,
17    pub format: &'a str,
18    pub plugin_spec: &'a str,
19    pub instance_id: &'a str,
20    pub extra_args: &'a [&'a str],
21}
22
23/// Spawn the unified `maolan-plugin-host` binary and set up SHM + event pipes.
24pub fn spawn_host(args: HostSpawnArgs) -> Result<(Child, ShmMapping, EventPair, String), String> {
25    let pid = std::process::id();
26    let shm_name = format!("/maolan-{pid}-{}", args.instance_id);
27
28    let mapping = ShmMapping::create(&shm_name, SHM_SIZE)
29        .map_err(|e| format!("failed to create shared memory: {e}"))?;
30    unsafe {
31        init_shm_layout(mapping.as_ptr(), mapping.size());
32    }
33
34    let mut events = EventPair::new().map_err(|e| format!("failed to create event pipes: {e}"))?;
35
36    let mut cmd = Command::new(args.host_binary);
37    cmd.arg(args.format)
38        .arg(args.plugin_spec)
39        .arg(&shm_name)
40        .arg(args.instance_id)
41        .stdin(Stdio::null())
42        .stdout(Stdio::null())
43        .stderr(Stdio::inherit());
44
45    for arg in args.extra_args {
46        cmd.arg(arg);
47    }
48
49    #[cfg(unix)]
50    {
51        cmd.arg(events.host_read_fd().to_string())
52            .arg(events.host_write_fd().to_string());
53    }
54    #[cfg(windows)]
55    {
56        cmd.arg(events.daw_to_host_name())
57            .arg(events.host_to_daw_name());
58    }
59
60    let child = cmd
61        .spawn()
62        .map_err(|e| format!("failed to spawn {} host: {e}", args.format))?;
63
64    events.close_daw_unused();
65
66    Ok((child, mapping, events, shm_name))
67}
68
69/// Poll the SHM ready flag until it becomes non-zero or `timeout` elapses.
70pub fn wait_for_ready(header: &ShmHeader, timeout: Duration) -> bool {
71    let start = Instant::now();
72    while start.elapsed() < timeout {
73        if header.ready.load(Ordering::Acquire) != 0 {
74            return true;
75        }
76        std::thread::sleep(Duration::from_millis(5));
77    }
78    false
79}
80
81/// Copy input buffers to output buffers when the plugin host is bypassed or crashed.
82pub fn bypass_copy_inputs_to_outputs(inputs: &[Arc<AudioIO>], outputs: &[Arc<AudioIO>]) {
83    for (input, output) in inputs.iter().zip(outputs.iter()) {
84        let src = input.buffer.lock();
85        let dst = output.buffer.lock();
86        dst.fill(0.0);
87        for (d, s) in dst.iter_mut().zip(src.iter()) {
88            *d = *s;
89        }
90        *output.finished.lock() = true;
91    }
92    for output in outputs.iter().skip(inputs.len()) {
93        let dst = output.buffer.lock();
94        dst.fill(0.0);
95        *output.finished.lock() = true;
96    }
97}
98
99/// Shared shutdown logic for the `Drop` impl of all OOP processors.
100pub fn drop_host(
101    mapping: &Option<ShmMapping>,
102    events: &Option<EventPair>,
103    child: &UnsafeMutex<Option<Child>>,
104    shm_name: &str,
105) {
106    if let Some(mapping) = mapping
107        && let Some(events) = events
108    {
109        let header = unsafe { header_mut(mapping.as_ptr()) };
110        header.shutdown_request.store(1, Ordering::Release);
111        let _ = events.signal_host();
112    }
113    let mut child_opt = child.lock().take();
114    if let Some(mut child) = child_opt.take() {
115        let start = Instant::now();
116        while start.elapsed() < Duration::from_secs(2) {
117            if child.try_wait().map(|s| s.is_some()).unwrap_or(true) {
118                break;
119            }
120            std::thread::sleep(Duration::from_millis(10));
121        }
122        if child.try_wait().map(|s| s.is_none()).unwrap_or(false) {
123            let _ = child.kill();
124        }
125    }
126    let _ = ShmMapping::unlink(shm_name);
127}
128
129/// Locate the `maolan-plugin-host` binary at runtime.
130///
131/// Search order:
132/// 1. Same directory as the current executable.
133/// 2. Workspace `target/debug` or `target/release` (development).
134/// 3. `PATH` environment variable.
135pub fn find_plugin_host_binary() -> Option<PathBuf> {
136    let exe_dir = std::env::current_exe()
137        .ok()
138        .and_then(|p| p.parent().map(PathBuf::from));
139
140    // 1. Same directory as current executable.
141    if let Some(ref dir) = exe_dir {
142        let candidate = dir.join("maolan-plugin-host");
143        if candidate.exists() {
144            return Some(candidate);
145        }
146    }
147
148    // 2. Development workspace paths.
149    if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") {
150        let engine_root = Path::new(&manifest);
151        for profile in ["debug", "release"] {
152            let candidate = engine_root
153                .parent()
154                .unwrap_or(Path::new(""))
155                .join("daw")
156                .join("target")
157                .join(profile)
158                .join("maolan-plugin-host");
159            if candidate.exists() {
160                return Some(candidate);
161            }
162        }
163    }
164
165    // 3. PATH.
166    if let Ok(path_var) = std::env::var("PATH") {
167        for dir in path_var.split(':') {
168            let candidate = Path::new(dir).join("maolan-plugin-host");
169            if candidate.exists() {
170                return Some(candidate);
171            }
172        }
173    }
174
175    None
176}
177
178/// Copy input AudioIO buffers to shared memory (bus 0).
179///
180/// # Safety
181/// `ptr` must be a valid pointer to the start of the plugin-host SHM region.
182pub unsafe fn copy_inputs_to_shm(inputs: &[Arc<AudioIO>], ptr: *mut u8, frames: usize) {
183    for (ch, input) in inputs.iter().enumerate() {
184        let src = input.buffer.lock();
185        let dst = unsafe { audio_channel_ptr(ptr, ch, 0) };
186        let len = frames.min(src.len());
187        unsafe {
188            std::ptr::copy_nonoverlapping(src.as_ptr(), dst, len);
189        }
190    }
191}
192
193/// Copy output shared memory (bus 1) back to AudioIO buffers.
194///
195/// # Safety
196/// `ptr` must be a valid pointer to the start of the plugin-host SHM region.
197pub unsafe fn copy_outputs_from_shm(outputs: &[Arc<AudioIO>], ptr: *mut u8, frames: usize) {
198    for (ch, output) in outputs.iter().enumerate() {
199        let dst = output.buffer.lock();
200        let src = unsafe { audio_channel_ptr(ptr, ch, 1) };
201        let len = frames.min(dst.len());
202        unsafe {
203            std::ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), len);
204        }
205        *output.finished.lock() = true;
206    }
207}
208
209/// Set the standard SHM header fields for a processing block.
210///
211/// # Safety
212/// `ptr` must be a valid pointer to the start of the plugin-host SHM region.
213pub unsafe fn configure_shm_header(ptr: *mut u8, frames: usize, num_in: usize, num_out: usize) {
214    unsafe {
215        let h = header_mut(ptr);
216        h.block_size.store(frames as u32, Ordering::Release);
217        h.num_input_channels.store(num_in as u32, Ordering::Release);
218        h.num_output_channels
219            .store(num_out as u32, Ordering::Release);
220    }
221}
222
223/// Generate `UnsafeMutex<Processor>` forwarding methods that are identical
224/// across all out-of-process plugin formats (CLAP, VST3, LV2).
225#[macro_export]
226macro_rules! impl_ipc_processor_wrapper {
227    ($processor:ty) => {
228        impl $crate::mutex::UnsafeMutex<$processor> {
229            pub fn setup_audio_ports(&self) {
230                self.lock().setup_audio_ports();
231            }
232
233            pub fn audio_inputs(&self) -> &[std::sync::Arc<$crate::audio::io::AudioIO>] {
234                self.lock().audio_inputs()
235            }
236
237            pub fn audio_outputs(&self) -> &[std::sync::Arc<$crate::audio::io::AudioIO>] {
238                self.lock().audio_outputs()
239            }
240
241            pub fn main_audio_input_count(&self) -> usize {
242                self.lock().main_audio_input_count()
243            }
244
245            pub fn main_audio_output_count(&self) -> usize {
246                self.lock().main_audio_output_count()
247            }
248
249            pub fn midi_input_count(&self) -> usize {
250                self.lock().midi_input_count()
251            }
252
253            pub fn midi_output_count(&self) -> usize {
254                self.lock().midi_output_count()
255            }
256
257            pub fn set_bypassed(&self, bypassed: bool) {
258                self.lock().set_bypassed(bypassed);
259            }
260
261            pub fn name(&self) -> String {
262                self.lock().name().to_string()
263            }
264
265            pub fn run_host_callbacks_main_thread(&self) {
266                self.lock().run_host_callbacks_main_thread();
267            }
268
269            pub fn reconfigure_ports_if_needed(&self) -> Result<bool, String> {
270                self.lock().reconfigure_ports_if_needed()
271            }
272        }
273    };
274}