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