1use crate::audio::io::AudioIO;
2use crate::midi::io::{MIDIIO, MidiEvent};
3use crate::plugins::ipc;
4use crate::plugins::types::{
5 ClapMidiOutputEvent, ClapParamUpdate, ClapParameterInfo, ClapTransportInfo,
6};
7use arc_swap::{ArcSwap, ArcSwapOption};
8use maolan_plugin_protocol::events::EventPair;
9use maolan_plugin_protocol::protocol::*;
10use maolan_plugin_protocol::ringbuf::RingBuffer;
11use maolan_plugin_protocol::shm::ShmMapping;
12use std::cell::UnsafeCell;
13use std::collections::HashMap;
14use std::path::PathBuf;
15use std::process::{Child, ChildStderr};
16use std::sync::Arc;
17use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
18use std::time::{Duration, Instant};
19
20const SHM_LATENCY_SAMPLES_OFFSET: usize = 84;
21const REQUEST_CLAP_AUDIO_PORTS: u32 = 12;
22
23unsafe fn latency_samples_atomic(ptr: *mut u8) -> &'static AtomicU32 {
24 unsafe { &*(ptr.add(SHM_LATENCY_SAMPLES_OFFSET) as *const AtomicU32) }
25}
26
27fn wait_for_host_request_complete(
28 header: &ShmHeader,
29 events: &EventPair,
30 timeout: Duration,
31) -> Result<(), String> {
32 let start = Instant::now();
33 loop {
34 if header.request_type.load(Ordering::Acquire) == 0
38 || header.request_status.load(Ordering::Acquire) != 0
39 {
40 return Ok(());
41 }
42 let elapsed = start.elapsed();
43 if elapsed >= timeout {
44 return Err("Host did not respond to request".to_string());
45 }
46 if let Err(e) = events.wait_host(timeout - elapsed) {
47 return Err(format!("Host did not respond to request: {e}"));
48 }
49 }
50}
51
52pub struct ClapProcessor {
53 path: String,
54 plugin_id: String,
55 name: String,
56 buffer_size: usize,
57 audio_inputs: ArcSwap<Vec<Arc<AudioIO>>>,
58 audio_outputs: ArcSwap<Vec<Arc<AudioIO>>>,
59 main_audio_inputs: AtomicUsize,
60 main_audio_outputs: AtomicUsize,
61 midi_input_count: usize,
62 midi_output_count: usize,
63 midi_input_ports: Vec<Arc<MIDIIO>>,
64 midi_output_ports: Vec<Arc<MIDIIO>>,
65 param_infos: Vec<ClapParameterInfo>,
66 param_values: HashMap<u32, AtomicU64>,
70 bypassed: Arc<AtomicBool>,
71
72 child: UnsafeCell<Option<Child>>,
80 stderr: ArcSwapOption<ChildStderr>,
83 mapping: Option<ShmMapping>,
84 events: Option<EventPair>,
85 shm_name: String,
86
87 crash_count: AtomicU32,
88 last_latency_samples: AtomicUsize,
89 latency_changed: AtomicBool,
90}
91
92unsafe impl Sync for ClapProcessor {}
96
97pub type SharedClapProcessor = Arc<ClapProcessor>;
98
99impl ClapProcessor {
100 pub fn new(
101 _sample_rate: f64,
102 buffer_size: usize,
103 plugin_spec: &str,
104 input_count: usize,
105 output_count: usize,
106 host_binary: PathBuf,
107 ) -> Result<Self, String> {
108 let (plugin_path, plugin_id) = split_plugin_spec(plugin_spec);
109
110 let instance_id = ipc::unique_instance_id("clap");
111 let plugin_spec = if plugin_id.is_empty() {
112 plugin_path.to_string()
113 } else {
114 format!("{plugin_path}::{plugin_id}")
115 };
116 let (mut child, mapping, events, shm_name, stderr) = ipc::spawn_host(ipc::HostSpawnArgs {
117 host_binary: &host_binary,
118 format: "clap",
119 plugin_spec: &plugin_spec,
120 instance_id: &instance_id,
121 extra_args: &[],
122 })?;
123
124 let header = unsafe { header_ref(mapping.as_ptr()) };
125 if !ipc::wait_for_ready(header, &mut child, Duration::from_secs(10)) {
126 let _ = child.kill();
127 return Err("host did not signal ready".to_string());
128 }
129
130 let name = unsafe {
131 maolan_plugin_protocol::protocol::read_plugin_name_from_scratch(mapping.as_ptr())
132 .unwrap_or_else(|| plugin_id.to_string())
133 };
134
135 let (actual_audio_in, actual_audio_out, actual_midi_in, actual_midi_out) = unsafe {
136 let counts =
137 maolan_plugin_protocol::protocol::read_port_counts_from_scratch(mapping.as_ptr());
138
139 counts.unwrap_or((input_count as u32, output_count as u32, 0, 0))
140 };
141
142 let audio_inputs = (0..actual_audio_in as usize)
143 .map(|_| Arc::new(AudioIO::new(buffer_size)))
144 .collect::<Vec<_>>();
145 let audio_outputs = (0..actual_audio_out as usize)
146 .map(|_| Arc::new(AudioIO::new(buffer_size)))
147 .collect::<Vec<_>>();
148 let midi_input_ports = (0..actual_midi_in as usize)
149 .map(|_| Arc::new(MIDIIO::new()))
150 .collect::<Vec<_>>();
151 let midi_output_ports = (0..actual_midi_out as usize)
152 .map(|_| Arc::new(MIDIIO::new()))
153 .collect::<Vec<_>>();
154
155 let param_infos = Self::fetch_parameter_infos(&mapping, &events).unwrap_or_else(|e| {
156 tracing::warn!("Failed to fetch CLAP parameter infos: {e}");
157 Vec::new()
158 });
159 let param_values = param_infos
160 .iter()
161 .map(|info| (info.id, AtomicU64::new(info.default_value.to_bits())))
162 .collect();
163
164 Ok(Self {
165 path: plugin_spec.to_string(),
166 plugin_id: plugin_id.to_string(),
167 name,
168 buffer_size,
169 audio_inputs: ArcSwap::from_pointee(audio_inputs),
170 audio_outputs: ArcSwap::from_pointee(audio_outputs),
171 main_audio_inputs: AtomicUsize::new(actual_audio_in as usize),
172 main_audio_outputs: AtomicUsize::new(actual_audio_out as usize),
173 midi_input_count: actual_midi_in as usize,
174 midi_output_count: actual_midi_out as usize,
175 midi_input_ports,
176 midi_output_ports,
177 param_infos,
178 param_values,
179 bypassed: Arc::new(AtomicBool::new(false)),
180 child: UnsafeCell::new(Some(child)),
181 stderr: ArcSwapOption::from_pointee(stderr),
182 mapping: Some(mapping),
183 events: Some(events),
184 shm_name,
185 crash_count: AtomicU32::new(0),
186 last_latency_samples: AtomicUsize::new(0),
187 latency_changed: AtomicBool::new(false),
188 })
189 }
190
191 unsafe fn with_child<R>(&self, f: impl FnOnce(&mut Option<Child>) -> R) -> R {
199 f(unsafe { &mut *self.child.get() })
200 }
201
202 pub fn setup_audio_ports(&self) {
203 for port in self.audio_inputs() {
204 port.setup();
205 }
206 for port in self.audio_outputs() {
207 port.setup();
208 }
209 }
210
211 fn disconnect_all(port: &Arc<AudioIO>) {
212 let connections = port.connections();
213 for other in connections.iter() {
214 let _ = AudioIO::disconnect(other, port);
215 }
216 }
217
218 fn resize_audio_ports(ports: &mut Vec<Arc<AudioIO>>, len: usize, buffer_size: usize) {
219 if ports.len() > len {
220 for port in &ports[len..] {
221 Self::disconnect_all(port);
222 }
223 ports.truncate(len);
224 }
225 while ports.len() < len {
226 ports.push(Arc::new(AudioIO::new(buffer_size)));
227 }
228 }
229
230 fn refresh_audio_ports_from_scratch(&self, ptr: *mut u8) -> bool {
231 let Some((audio_in, audio_out, _, _)) = (unsafe { read_port_counts_from_scratch(ptr) })
232 else {
233 return false;
234 };
235 let audio_in = audio_in as usize;
236 let audio_out = audio_out as usize;
237 let mut changed = false;
238
239 let current_inputs = self.audio_inputs.load_full();
240 let current_input_len = current_inputs.len();
241 drop(current_inputs);
242 if current_input_len != audio_in
243 || self.main_audio_inputs.load(Ordering::Acquire) != audio_in
244 {
245 let mut inputs = self.audio_inputs.load_full().as_ref().clone();
246 Self::resize_audio_ports(&mut inputs, audio_in, self.buffer_size);
247 self.audio_inputs.store(Arc::new(inputs));
248 self.main_audio_inputs.store(audio_in, Ordering::Release);
249 changed = true;
250 }
251
252 let current_outputs = self.audio_outputs.load_full();
253 let current_output_len = current_outputs.len();
254 drop(current_outputs);
255 if current_output_len != audio_out
256 || self.main_audio_outputs.load(Ordering::Acquire) != audio_out
257 {
258 let mut outputs = self.audio_outputs.load_full().as_ref().clone();
259 Self::resize_audio_ports(&mut outputs, audio_out, self.buffer_size);
260 self.audio_outputs.store(Arc::new(outputs));
261 self.main_audio_outputs.store(audio_out, Ordering::Release);
262 changed = true;
263 }
264 changed
265 }
266
267 pub fn setup_midi_ports(&self) {
268 for port in &self.midi_input_ports {
269 unsafe { port.setup() };
273 }
274 for port in &self.midi_output_ports {
275 unsafe { port.setup() };
277 }
278 }
279
280 pub fn audio_inputs(&self) -> Vec<Arc<AudioIO>> {
281 self.audio_inputs.load_full().as_ref().clone()
282 }
283
284 pub fn audio_outputs(&self) -> Vec<Arc<AudioIO>> {
285 self.audio_outputs.load_full().as_ref().clone()
286 }
287
288 pub fn main_audio_input_count(&self) -> usize {
289 self.main_audio_inputs.load(Ordering::Acquire)
290 }
291
292 pub fn main_audio_output_count(&self) -> usize {
293 self.main_audio_outputs.load(Ordering::Acquire)
294 }
295
296 pub fn midi_input_count(&self) -> usize {
297 self.midi_input_count
298 }
299
300 pub fn midi_output_count(&self) -> usize {
301 self.midi_output_count
302 }
303
304 pub fn midi_input_ports(&self) -> &[Arc<MIDIIO>] {
305 &self.midi_input_ports
306 }
307
308 pub fn midi_output_ports(&self) -> &[Arc<MIDIIO>] {
309 &self.midi_output_ports
310 }
311
312 pub fn set_bypassed(&self, bypassed: bool) {
313 let previous = self.bypassed.swap(bypassed, Ordering::Relaxed);
314 if previous != bypassed {
315 self.latency_changed.store(true, Ordering::Release);
316 }
317 }
318
319 pub fn is_bypassed(&self) -> bool {
320 self.bypassed.load(Ordering::Relaxed)
321 }
322
323 pub fn latency_samples(&self) -> usize {
324 if self.bypassed.load(Ordering::Relaxed) {
325 let previous = self.last_latency_samples.swap(0, Ordering::AcqRel);
326 if previous != 0 {
327 self.latency_changed.store(true, Ordering::Release);
328 }
329 return 0;
330 }
331 let latency = self
332 .mapping
333 .as_ref()
334 .map(|mapping| unsafe {
335 latency_samples_atomic(mapping.as_ptr()).load(Ordering::Acquire) as usize
336 })
337 .unwrap_or(0);
338 let previous = self.last_latency_samples.swap(latency, Ordering::AcqRel);
339 if previous != latency {
340 self.latency_changed.store(true, Ordering::Release);
341 }
342 latency
343 }
344
345 pub fn take_latency_changed(&self) -> bool {
346 self.latency_changed.swap(false, Ordering::AcqRel)
347 }
348
349 pub fn parameter_infos(&self) -> Vec<ClapParameterInfo> {
350 self.param_infos.clone()
351 }
352
353 fn fetch_parameter_infos(
354 mapping: &ShmMapping,
355 events: &EventPair,
356 ) -> Result<Vec<ClapParameterInfo>, String> {
357 let ptr = mapping.as_ptr();
358 let header = unsafe { header_mut(ptr) };
359
360 header
361 .request_type
362 .store(REQUEST_CLAP_PARAMETERS, Ordering::Release);
363 header.request_status.store(0, Ordering::Release);
364 if let Err(e) = events.signal_host() {
365 header.request_type.store(0, Ordering::Release);
366 return Err(format!("Failed to signal host for CLAP parameters: {e}"));
367 }
368
369 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
370 header.request_type.store(0, Ordering::Release);
371 return Err(format!("Host did not respond to CLAP parameters: {e}"));
372 }
373
374 let status = header.request_status.load(Ordering::Acquire);
375 let size = header.scratch_size.load(Ordering::Acquire) as usize;
376 if status != 1 {
377 header.request_type.store(0, Ordering::Release);
378 return Err("CLAP parameter enumeration failed in host".to_string());
379 }
380
381 let scratch = unsafe { scratch_ptr(ptr) };
382 let result = Self::deserialize_clap_parameters(scratch, size);
383 header.request_type.store(0, Ordering::Release);
384 result
385 }
386
387 fn deserialize_clap_parameters(
388 scratch: *const u8,
389 size: usize,
390 ) -> Result<Vec<ClapParameterInfo>, String> {
391 if size < 4 {
392 return Err("scratch too small for CLAP parameters".to_string());
393 }
394 let mut offset = 0usize;
395
396 let count = unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
397 offset += 4;
398
399 let mut params = Vec::with_capacity(count);
400 for _ in 0..count {
401 if offset + 4 > size {
402 return Err("scratch underflow".to_string());
403 }
404 let id = unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) };
405 offset += 4;
406
407 if offset + 4 > size {
408 return Err("scratch underflow".to_string());
409 }
410 let name_len =
411 unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
412 offset += 4;
413 if offset + name_len > size {
414 return Err("scratch underflow".to_string());
415 }
416 let mut name_bytes = vec![0u8; name_len];
417 unsafe {
418 std::ptr::copy_nonoverlapping(
419 scratch.add(offset),
420 name_bytes.as_mut_ptr(),
421 name_len,
422 );
423 }
424 offset += name_len;
425 let name = String::from_utf8(name_bytes).map_err(|e| e.to_string())?;
426
427 if offset + 4 > size {
428 return Err("scratch underflow".to_string());
429 }
430 let module_len =
431 unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
432 offset += 4;
433 if offset + module_len > size {
434 return Err("scratch underflow".to_string());
435 }
436 let mut module_bytes = vec![0u8; module_len];
437 unsafe {
438 std::ptr::copy_nonoverlapping(
439 scratch.add(offset),
440 module_bytes.as_mut_ptr(),
441 module_len,
442 );
443 }
444 offset += module_len;
445 let module = String::from_utf8(module_bytes).map_err(|e| e.to_string())?;
446
447 if offset + 24 > size {
448 return Err("scratch underflow".to_string());
449 }
450 let min_value = f64::from_bits(unsafe {
451 std::ptr::read_unaligned(scratch.add(offset) as *const u64)
452 });
453 let max_value = f64::from_bits(unsafe {
454 std::ptr::read_unaligned(scratch.add(offset + 8) as *const u64)
455 });
456 let default_value = f64::from_bits(unsafe {
457 std::ptr::read_unaligned(scratch.add(offset + 16) as *const u64)
458 });
459 offset += 24;
460
461 params.push(ClapParameterInfo {
462 id,
463 name,
464 module,
465 min_value,
466 max_value,
467 default_value,
468 });
469 }
470
471 Ok(params)
472 }
473
474 pub fn parameter_values(&self) -> HashMap<u32, f64> {
475 self.param_values
476 .iter()
477 .map(|(&id, value)| (id, f64::from_bits(value.load(Ordering::Relaxed))))
478 .collect()
479 }
480
481 pub fn set_parameter(&self, param_id: u32, value: f64) -> Result<(), String> {
482 self.set_parameter_at(param_id, value, 0)
483 }
484
485 pub fn set_parameter_at(&self, param_id: u32, value: f64, _frame: u32) -> Result<(), String> {
486 if let Some(slot) = self.param_values.get(¶m_id) {
487 slot.store(value.to_bits(), Ordering::Relaxed);
488 } else {
489 tracing::warn!("CLAP set_parameter_at: unknown parameter id {param_id}");
490 }
491
492 if let Some(ref mapping) = self.mapping {
493 let ring = unsafe {
494 let buf = param_ring_ptr(mapping.as_ptr());
495 let (w, r) = param_indices(mapping.as_ptr());
496 RingBuffer::new(buf, w, r, RING_CAPACITY)
497 };
498 let ev = ParameterEvent {
499 param_index: param_id,
500 value: value as f32,
501 sample_offset: 0,
502 event_kind: maolan_plugin_protocol::PARAM_EVENT_VALUE,
503 };
504 if !ring.push(ev) {}
505 }
506 Ok(())
507 }
508
509 pub fn begin_parameter_edit(&self, _param_id: u32) -> Result<(), String> {
510 Ok(())
511 }
512
513 pub fn end_parameter_edit(&self, _param_id: u32) -> Result<(), String> {
514 Ok(())
515 }
516
517 pub fn is_parameter_edit_active(&self, _param_id: u32) -> bool {
518 false
519 }
520
521 pub fn take_state_dirty(&self) -> bool {
522 let header = match self.mapping.as_ref() {
523 Some(m) => unsafe { header_mut(m.as_ptr()) },
524 None => return false,
525 };
526 header.state_dirty.swap(0, Ordering::Acquire) != 0
527 }
528
529 pub fn snapshot_state(&self) -> Result<crate::plugins::types::ClapPluginState, String> {
530 let (mapping, events) = match (&self.mapping, &self.events) {
531 (Some(m), Some(e)) => (m, e),
532 _ => return Err("CLAP processor not initialized".to_string()),
533 };
534 let ptr = mapping.as_ptr();
535 let header = unsafe { header_mut(ptr) };
536
537 header.request_type.store(1, Ordering::Release);
538 header.request_status.store(0, Ordering::Release);
539 if let Err(e) = events.signal_host() {
540 header.request_type.store(0, Ordering::Release);
541 return Err(format!("Failed to signal host for state save: {e}"));
542 }
543
544 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
545 header.request_type.store(0, Ordering::Release);
546 return Err(format!("Host did not respond to state save: {e}"));
547 }
548
549 let status = header.request_status.load(Ordering::Acquire);
550 let size = header.scratch_size.load(Ordering::Acquire) as usize;
551 if status != 1 {
552 header.request_type.store(0, Ordering::Release);
553 return Err("State save failed in host".to_string());
554 }
555 if size > SCRATCH_SIZE {
556 header.request_type.store(0, Ordering::Release);
557 return Err(format!("Host returned invalid CLAP state size: {size}"));
558 }
559
560 let scratch = unsafe { scratch_ptr(ptr) };
561 let mut bytes = vec![0u8; size];
562 unsafe {
563 std::ptr::copy_nonoverlapping(scratch, bytes.as_mut_ptr(), size);
564 }
565 header.request_type.store(0, Ordering::Release);
566 Ok(crate::plugins::types::ClapPluginState { bytes })
567 }
568
569 pub fn restore_state(
570 &self,
571 state: &crate::plugins::types::ClapPluginState,
572 ) -> Result<(), String> {
573 let (mapping, events) = match (&self.mapping, &self.events) {
574 (Some(m), Some(e)) => (m, e),
575 _ => return Err("CLAP processor not initialized".to_string()),
576 };
577 if state.bytes.len() > SCRATCH_SIZE {
578 return Err(format!(
579 "CLAP state is too large for scratch buffer: {} bytes",
580 state.bytes.len()
581 ));
582 }
583
584 let ptr = mapping.as_ptr();
585 let header = unsafe { header_mut(ptr) };
586 let scratch = unsafe { scratch_ptr(ptr) };
587 unsafe {
588 std::ptr::copy_nonoverlapping(state.bytes.as_ptr(), scratch, state.bytes.len());
589 }
590 header
591 .scratch_size
592 .store(state.bytes.len() as u32, Ordering::Release);
593
594 header.request_type.store(2, Ordering::Release);
595 header.request_status.store(0, Ordering::Release);
596 if let Err(e) = events.signal_host() {
597 header.request_type.store(0, Ordering::Release);
598 return Err(format!("Failed to signal host for state restore: {e}"));
599 }
600
601 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
602 header.request_type.store(0, Ordering::Release);
603 return Err(format!("Host did not respond to state restore: {e}"));
604 }
605
606 let status = header.request_status.load(Ordering::Acquire);
607 header.request_type.store(0, Ordering::Release);
608 if status != 1 {
609 return Err("State restore failed in host".to_string());
610 }
611 Ok(())
612 }
613
614 pub fn set_resource_directory(
615 &self,
616 dir: &std::path::Path,
617 shared: bool,
618 ) -> Result<(), String> {
619 let (mapping, events) = match (&self.mapping, &self.events) {
620 (Some(m), Some(e)) => (m, e),
621 _ => return Err("CLAP processor not initialized".to_string()),
622 };
623 let ptr = mapping.as_ptr();
624 let header = unsafe { header_mut(ptr) };
625 let path_str = dir.to_string_lossy().to_string();
626 unsafe {
627 write_resource_directory_to_scratch(ptr, &path_str, shared)
628 .map_err(|e| format!("Failed to write resource directory: {e}"))?;
629 }
630 std::sync::atomic::fence(Ordering::SeqCst);
631
632 header.request_type.store(5, Ordering::Release);
633 header.request_status.store(0, Ordering::Release);
634 if let Err(e) = events.signal_host() {
635 header.request_type.store(0, Ordering::Release);
636 return Err(format!("Failed to signal host for resource directory: {e}"));
637 }
638
639 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
640 header.request_type.store(0, Ordering::Release);
641 return Err(format!("Host did not respond to resource directory: {e}"));
642 }
643
644 let status = header.request_status.load(Ordering::Acquire);
645 header.request_type.store(0, Ordering::Release);
646 if status != 1 {
647 return Err("Resource directory update failed in host".to_string());
648 }
649 Ok(())
650 }
651
652 pub fn collect_resources(&self) -> Result<(), String> {
653 let (mapping, events) = match (&self.mapping, &self.events) {
654 (Some(m), Some(e)) => (m, e),
655 _ => return Err("CLAP processor not initialized".to_string()),
656 };
657 let ptr = mapping.as_ptr();
658 let header = unsafe { header_mut(ptr) };
659
660 header
661 .request_type
662 .store(REQUEST_COLLECT_RESOURCES, Ordering::Release);
663 header.request_status.store(0, Ordering::Release);
664 if let Err(e) = events.signal_host() {
665 header.request_type.store(0, Ordering::Release);
666 return Err(format!(
667 "Failed to signal host for resource collection: {e}"
668 ));
669 }
670
671 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
672 header.request_type.store(0, Ordering::Release);
673 return Err(format!("Host did not respond to resource collection: {e}"));
674 }
675
676 let status = header.request_status.load(Ordering::Acquire);
677 header.request_type.store(0, Ordering::Release);
678 if status != 1 {
679 return Err("Resource collection failed in host".to_string());
680 }
681 Ok(())
682 }
683
684 pub fn resource_files(
685 &self,
686 ) -> Result<Vec<maolan_plugin_protocol::protocol::ResourceFile>, String> {
687 let (mapping, events) = match (&self.mapping, &self.events) {
688 (Some(m), Some(e)) => (m, e),
689 _ => return Err("CLAP processor not initialized".to_string()),
690 };
691 let ptr = mapping.as_ptr();
692 let header = unsafe { header_mut(ptr) };
693
694 header
695 .request_type
696 .store(REQUEST_RESOURCE_FILES, Ordering::Release);
697 header.request_status.store(0, Ordering::Release);
698 if let Err(e) = events.signal_host() {
699 header.request_type.store(0, Ordering::Release);
700 return Err(format!("Failed to signal host for resource files: {e}"));
701 }
702
703 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
704 header.request_type.store(0, Ordering::Release);
705 return Err(format!("Host did not respond to resource files: {e}"));
706 }
707
708 let status = header.request_status.load(Ordering::Acquire);
709 if status != 1 {
710 header.request_type.store(0, Ordering::Release);
711 return Err("Resource files enumeration failed in host".to_string());
712 }
713
714 let files = unsafe { read_resource_files_from_scratch(ptr) }
715 .ok_or("Failed to read resource files from scratch")?;
716 header.request_type.store(0, Ordering::Release);
717 Ok(files)
718 }
719
720 pub fn process_with_audio_buffers(
721 &self,
722 frames: usize,
723 midi_in: &[MidiEvent],
724 transport: ClapTransportInfo,
725 audio_inputs: &[&[f32]],
726 audio_outputs: &mut [&mut [f32]],
727 ) -> Vec<ClapMidiOutputEvent> {
728 if self.bypassed.load(Ordering::Relaxed) {
729 ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
730 return Vec::new();
731 }
732
733 let crashed = unsafe {
736 self.with_child(|child| {
737 if let Some(c) = child.as_mut()
738 && let Ok(Some(status)) = c.try_wait()
739 && !status.success()
740 {
741 self.crash_count.fetch_add(1, Ordering::Relaxed);
742 return true;
743 }
744 false
745 })
746 };
747 if crashed {
748 ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
749 return Vec::new();
750 }
751
752 let (mapping, events) = match (&self.mapping, &self.events) {
753 (Some(m), Some(e)) => (m, e),
754 _ => {
755 ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
756 return Vec::new();
757 }
758 };
759
760 let ptr = mapping.as_ptr();
761 unsafe {
762 ipc::configure_shm_header(
763 ptr,
764 frames,
765 audio_inputs.len(),
766 audio_outputs.len(),
767 self.midi_input_ports.len(),
768 self.midi_output_ports.len(),
769 );
770 ipc::copy_input_slices_to_shm(audio_inputs, ptr, frames);
771
772 let t = transport_mut(ptr);
773 t.playhead_sample = transport.transport_sample as u64;
774 t.tempo = transport.bpm;
775 t.numerator = transport.tsig_num as u32;
776 t.denominator = transport.tsig_denom as u32;
777 t.flags = if transport.playing { 1 } else { 0 };
778
779 if let Some(port0) = self.midi_input_ports.first() {
783 let mut buffer = port0.buffer_mut();
787 buffer.extend_from_slice(midi_in);
788 port0.mark_finished();
789 }
790
791 for (port_idx, port) in self.midi_input_ports.iter().enumerate() {
792 let midi_buf = midi_in_ring_ptr(ptr, port_idx);
793 let (midi_w, midi_r) = midi_in_indices(ptr, port_idx);
794 let midi_ring = RingBuffer::new(midi_buf, midi_w, midi_r, RING_CAPACITY);
795 let port_buffer = port.buffer();
798 for ev in port_buffer {
799 let midi_event = maolan_plugin_protocol::protocol::MidiEvent {
800 sample_offset: ev.frame,
801 data: [
802 ev.data.first().copied().unwrap_or(0),
803 ev.data.get(1).copied().unwrap_or(0),
804 ev.data.get(2).copied().unwrap_or(0),
805 ],
806 channel: ev.data.first().map(|b| b & 0x0F).unwrap_or(0),
807 flags: 0,
808 _pad: 0,
809 };
810 if !midi_ring.push(midi_event) {
811 tracing::warn!(port = port_idx, "clap_proc MIDI ring full");
812 break;
813 }
814 }
815 }
816 }
817
818 if events.signal_host().is_err() {
819 ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
820 return Vec::new();
821 }
822
823 let timeout = Duration::from_millis(100);
824 if events.wait_host(timeout).is_err() {
825 ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
826 return Vec::new();
827 }
828
829 let crashed = unsafe {
831 self.with_child(|child| {
832 if let Some(c) = child.as_mut()
833 && let Ok(Some(status)) = c.try_wait()
834 && !status.success()
835 {
836 self.crash_count.fetch_add(1, Ordering::Relaxed);
837 return true;
838 }
839 false
840 })
841 };
842 if crashed {
843 ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
844 return Vec::new();
845 }
846
847 unsafe {
848 ipc::copy_outputs_from_shm_to_slices(audio_outputs, ptr, frames);
849 }
850
851 let mut midi_out = Vec::new();
852 unsafe {
853 for (port_idx, port) in self.midi_output_ports.iter().enumerate() {
854 let mut port_buffer = port.buffer_mut();
857 port_buffer.clear();
858 let midi_out_buf = midi_out_ring_ptr(ptr, port_idx);
859 let (midi_out_w, midi_out_r) = midi_out_indices(ptr, port_idx);
860 let midi_out_ring =
861 RingBuffer::new(midi_out_buf, midi_out_w, midi_out_r, RING_CAPACITY);
862 while let Some(ev) = midi_out_ring.pop() {
863 let event = crate::midi::io::MidiEvent::new(ev.sample_offset, ev.data.to_vec());
864 port_buffer.push(event.clone());
865 midi_out.push(ClapMidiOutputEvent {
866 port: port_idx,
867 event,
868 });
869 }
870 port.mark_finished();
871 }
872 }
873
874 midi_out
875 }
876
877 pub fn path(&self) -> &str {
878 &self.path
879 }
880
881 pub fn plugin_id(&self) -> &str {
882 &self.plugin_id
883 }
884
885 pub fn name(&self) -> &str {
886 &self.name
887 }
888
889 pub fn take_stderr(&self) -> Option<ChildStderr> {
890 self.stderr.swap(None).and_then(|s| Arc::try_unwrap(s).ok())
893 }
894
895 pub fn begin_parameter_edit_at(&self, _param_id: u32, _frame: u32) -> Result<(), String> {
896 Ok(())
897 }
898
899 pub fn end_parameter_edit_at(&self, _param_id: u32, _frame: u32) -> Result<(), String> {
900 Ok(())
901 }
902
903 pub fn run_host_callbacks_main_thread(&self) {}
904
905 pub fn reconfigure_ports_if_needed(&self) -> Result<bool, String> {
906 let Some(mapping) = self.mapping.as_ref() else {
907 return Ok(false);
908 };
909 Ok(self.refresh_audio_ports_from_scratch(mapping.as_ptr()))
910 }
911
912 pub fn refresh_audio_ports_from_host(&self) -> Result<bool, String> {
913 let (mapping, events) = match (&self.mapping, &self.events) {
914 (Some(mapping), Some(events)) => (mapping, events),
915 _ => return Ok(false),
916 };
917 let ptr = mapping.as_ptr();
918 let header = unsafe { header_mut(ptr) };
919 header
920 .request_type
921 .store(REQUEST_CLAP_AUDIO_PORTS, Ordering::Release);
922 header.request_status.store(0, Ordering::Release);
923 if let Err(e) = events.signal_host() {
924 header.request_type.store(0, Ordering::Release);
925 return Err(format!("Failed to signal host for CLAP audio ports: {e}"));
926 }
927
928 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
929 header.request_type.store(0, Ordering::Release);
930 return Err(format!("Host did not respond to CLAP audio ports: {e}"));
931 }
932
933 let status = header.request_status.load(Ordering::Acquire);
934 header.request_type.store(0, Ordering::Release);
935 if status != 1 {
936 return Err("CLAP audio port enumeration failed in host".to_string());
937 }
938 Ok(self.refresh_audio_ports_from_scratch(ptr))
939 }
940
941 pub fn ui_begin_session(&self) {}
942 pub fn ui_end_session(&self) {}
943 pub fn ui_should_close(&self) -> bool {
944 false
945 }
946 pub fn ui_take_due_timers(&self) -> Vec<u32> {
947 Vec::new()
948 }
949 pub fn ui_take_param_updates(&self) -> Vec<ClapParamUpdate> {
950 Vec::new()
951 }
952 pub fn ui_take_state_update(&self) -> Option<crate::plugins::types::ClapPluginState> {
953 None
954 }
955
956 pub fn gui_info(&self) -> Result<crate::plugins::types::ClapGuiInfo, String> {
957 Err("GUI not yet supported for CLAP plugins".to_string())
958 }
959
960 pub fn gui_create(&self, _api: &str, _is_floating: bool) -> Result<(), String> {
961 Err("GUI not yet supported for CLAP plugins".to_string())
962 }
963
964 pub fn gui_get_size(&self) -> Result<(u32, u32), String> {
965 Err("GUI not yet supported for CLAP plugins".to_string())
966 }
967
968 pub fn gui_set_parent_x11(&self, window: usize) -> Result<(), String> {
969 if let Some(ref mapping) = self.mapping {
970 let header = unsafe { header_mut(mapping.as_ptr()) };
971 header.set_parent_window(window);
972 header.set_gui_parent_api(maolan_plugin_protocol::protocol::GuiParentApi::X11);
973 return Ok(());
974 }
975 Err("No active host to set parent window".to_string())
976 }
977
978 pub fn gui_set_parent_wayland(&self, window: usize) -> Result<(), String> {
979 if let Some(ref mapping) = self.mapping {
980 let header = unsafe { header_mut(mapping.as_ptr()) };
981 header.set_parent_window(window);
982 header.set_gui_parent_api(maolan_plugin_protocol::protocol::GuiParentApi::Wayland);
983 return Ok(());
984 }
985 Err("No active host to set parent window".to_string())
986 }
987
988 pub fn gui_set_floating_mode(&self, floating: bool) -> Result<(), String> {
989 if let Some(ref mapping) = self.mapping {
990 let header = unsafe { header_mut(mapping.as_ptr()) };
991 header.set_gui_mode(if floating {
992 GuiMode::Floating
993 } else {
994 GuiMode::Embedded
995 });
996 if floating {
997 header.set_parent_window(0);
998 header.set_gui_parent_api(maolan_plugin_protocol::protocol::GuiParentApi::None);
999 }
1000 return Ok(());
1001 }
1002 Err("No active host to set GUI mode".to_string())
1003 }
1004
1005 pub fn gui_show(&self) -> Result<(), String> {
1006 if let Some(ref mapping) = self.mapping
1007 && let Some(ref events) = self.events
1008 {
1009 let header = unsafe { header_mut(mapping.as_ptr()) };
1010 header.request_type.store(3, Ordering::Release);
1011 let _ = events.signal_host();
1012 return Ok(());
1013 }
1014 Err("No active host to show GUI".to_string())
1015 }
1016
1017 pub fn gui_hide(&self) {
1018 if let Some(ref mapping) = self.mapping
1019 && let Some(ref events) = self.events
1020 {
1021 let header = unsafe { header_mut(mapping.as_ptr()) };
1022 header.request_type.store(4, Ordering::Release);
1023 let _ = events.signal_host();
1024 }
1025 }
1026
1027 pub fn gui_destroy(&self) {}
1028
1029 pub fn gui_on_main_thread(&self) {}
1030
1031 pub fn gui_on_timer(&self, _timer_id: u32) {}
1032
1033 fn deserialize_clap_note_names(
1034 scratch: *const u8,
1035 size: usize,
1036 ) -> Result<HashMap<u8, String>, String> {
1037 if size < 4 {
1038 return Err("scratch too small for CLAP note names".to_string());
1039 }
1040 let mut offset = 0usize;
1041 let count = unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
1042 offset += 4;
1043
1044 let mut note_names = HashMap::with_capacity(count);
1045 for _ in 0..count {
1046 if offset + 4 > size {
1047 return Err("scratch underflow".to_string());
1048 }
1049 let note = unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) };
1050 offset += 4;
1051 if note > 127 {
1052 return Err(format!("CLAP note name key out of range: {note}"));
1053 }
1054
1055 if offset + 4 > size {
1056 return Err("scratch underflow".to_string());
1057 }
1058 let name_len =
1059 unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
1060 offset += 4;
1061 if offset + name_len > size {
1062 return Err("scratch underflow".to_string());
1063 }
1064 let mut name_bytes = vec![0u8; name_len];
1065 unsafe {
1066 std::ptr::copy_nonoverlapping(
1067 scratch.add(offset),
1068 name_bytes.as_mut_ptr(),
1069 name_len,
1070 );
1071 }
1072 offset += name_len;
1073 let name = String::from_utf8(name_bytes).map_err(|e| e.to_string())?;
1074 note_names.insert(note as u8, name);
1075 }
1076
1077 Ok(note_names)
1078 }
1079
1080 pub fn note_names(&self) -> Result<HashMap<u8, String>, String> {
1081 let (mapping, events) = match (&self.mapping, &self.events) {
1082 (Some(m), Some(e)) => (m, e),
1083 _ => return Err("CLAP processor not initialized".to_string()),
1084 };
1085 let ptr = mapping.as_ptr();
1086 let header = unsafe { header_mut(ptr) };
1087
1088 header
1089 .request_type
1090 .store(REQUEST_CLAP_NOTE_NAMES, Ordering::Release);
1091 header.request_status.store(0, Ordering::Release);
1092 if let Err(e) = events.signal_host() {
1093 header.request_type.store(0, Ordering::Release);
1094 return Err(format!("Failed to signal host for CLAP note names: {e}"));
1095 }
1096
1097 if let Err(e) = wait_for_host_request_complete(header, events, Duration::from_secs(5)) {
1098 header.request_type.store(0, Ordering::Release);
1099 return Err(format!("Host did not respond to CLAP note names: {e}"));
1100 }
1101
1102 let status = header.request_status.load(Ordering::Acquire);
1103 let size = header.scratch_size.load(Ordering::Acquire) as usize;
1104 if status != 1 {
1105 header.request_type.store(0, Ordering::Release);
1106 return Err("CLAP note name enumeration failed in host".to_string());
1107 }
1108
1109 let scratch = unsafe { scratch_ptr(ptr) };
1110 let result = Self::deserialize_clap_note_names(scratch, size);
1111 header.request_type.store(0, Ordering::Release);
1112 result
1113 }
1114
1115 pub fn drain_echoed_parameters(&self) -> Vec<ParameterEvent> {
1116 let mut result = Vec::new();
1117 if let Some(ref mapping) = self.mapping {
1118 let ring = unsafe {
1119 let buf = echo_ring_ptr(mapping.as_ptr());
1120 let (w, r) = echo_indices(mapping.as_ptr());
1121 RingBuffer::new(buf, w, r, RING_CAPACITY)
1122 };
1123 while let Some(ev) = ring.pop() {
1124 result.push(ev);
1125 }
1126 }
1127 result
1128 }
1129
1130 pub fn drain_midi_outputs(&self) -> Vec<crate::midi::io::MidiEvent> {
1131 let mut result = Vec::new();
1132 if let Some(ref mapping) = self.mapping {
1133 let ring = unsafe {
1134 let buf = midi_out_ring_ptr(mapping.as_ptr(), 0);
1135 let (w, r) = midi_out_indices(mapping.as_ptr(), 0);
1136 RingBuffer::new(buf, w, r, RING_CAPACITY)
1137 };
1138 while let Some(ev) = ring.pop() {
1139 result.push(crate::midi::io::MidiEvent {
1140 frame: ev.sample_offset,
1141 data: ev.data.to_vec(),
1142 });
1143 }
1144 }
1145 result
1146 }
1147}
1148
1149impl Drop for ClapProcessor {
1150 fn drop(&mut self) {
1151 let mapping = self.mapping.take();
1152 let events = self.events.take();
1153 let child = self.child.get_mut().take();
1154 let shm_name = std::mem::take(&mut self.shm_name);
1155 ipc::drop_host(mapping, events, child, shm_name);
1156 }
1157}
1158
1159fn split_plugin_spec(spec: &str) -> (&str, &str) {
1160 if let Some(pos) = spec.rfind("::") {
1161 (&spec[..pos], &spec[pos + 2..])
1162 } else if let Some(pos) = spec.rfind('#') {
1163 (&spec[..pos], &spec[pos + 1..])
1164 } else {
1165 (spec, "")
1166 }
1167}
1168
1169#[cfg(test)]
1170mod tests {
1171 use super::*;
1172 use std::sync::Arc;
1173
1174 fn find_host_binary() -> PathBuf {
1175 let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
1176 let workspace_root = std::path::Path::new(&manifest)
1177 .parent()
1178 .unwrap()
1179 .join("maolan");
1180 workspace_root
1181 .join("target")
1182 .join("debug")
1183 .join("maolan-plugin-host")
1184 }
1185
1186 #[test]
1187 fn resize_audio_ports_disconnects_truncated_connected_ports() {
1188 let first = Arc::new(AudioIO::new(256));
1189 let second = Arc::new(AudioIO::new(256));
1190 let target = Arc::new(AudioIO::new(256));
1191 AudioIO::connect(&second, &target);
1192 let mut ports = vec![first, second.clone()];
1193
1194 ClapProcessor::resize_audio_ports(&mut ports, 1, 256);
1195
1196 assert_eq!(ports.len(), 1);
1197 assert!(second.connections().is_empty());
1198 assert!(target.connections().is_empty());
1199 }
1200
1201 #[cfg_attr(
1202 all(miri, target_os = "freebsd"),
1203 ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
1204 )]
1205 #[test]
1206 fn clap_processor_processes_audio() {
1207 let host_bin = find_host_binary();
1208 if !host_bin.exists() {
1209 return;
1210 }
1211
1212 let plugin_path = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
1213 .parent()
1214 .unwrap()
1215 .join("daw")
1216 .join("plugin-host")
1217 .join("tests")
1218 .join("test_passthrough.clap");
1219
1220 if !plugin_path.exists() {
1221 return;
1222 }
1223
1224 let processor = ClapProcessor::new(
1225 48000.0,
1226 256,
1227 &format!("{}#com.maolan.test.passthrough", plugin_path.display()),
1228 2,
1229 2,
1230 host_bin,
1231 )
1232 .expect("should create processor");
1233
1234 processor.setup_audio_ports();
1235
1236 let input_buffers = (0..processor.audio_inputs().len())
1237 .map(|i| (0..256).map(|j| (i * 1000 + j) as f32).collect::<Vec<_>>())
1238 .collect::<Vec<_>>();
1239 let mut output_buffers = vec![vec![0.0; 256]; processor.audio_outputs().len()];
1240 let inputs = input_buffers.iter().map(Vec::as_slice).collect::<Vec<_>>();
1241 let mut outputs = output_buffers
1242 .iter_mut()
1243 .map(Vec::as_mut_slice)
1244 .collect::<Vec<_>>();
1245 processor.process_with_audio_buffers(
1246 256,
1247 &[],
1248 ClapTransportInfo::default(),
1249 &inputs,
1250 &mut outputs,
1251 );
1252
1253 for output in output_buffers.iter() {
1254 assert!(
1255 output.iter().any(|&s| s != 0.0),
1256 "output buffer should contain non-zero samples"
1257 );
1258 }
1259 }
1260
1261 #[cfg_attr(
1262 all(miri, target_os = "freebsd"),
1263 ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
1264 )]
1265 #[test]
1266 fn clap_processor_crash_bypass() {
1267 let host_bin = find_host_binary();
1268 if !host_bin.exists() {
1269 return;
1270 }
1271
1272 let processor = ClapProcessor::new(48000.0, 256, "__crash__", 1, 1, host_bin)
1273 .expect("should create processor for crash test");
1274
1275 processor.setup_audio_ports();
1276
1277 let input_buffers = [vec![1.0; 256]];
1278 let mut output_buffers = [vec![0.0; 256]];
1279 let inputs = input_buffers.iter().map(Vec::as_slice).collect::<Vec<_>>();
1280 let mut outputs = output_buffers
1281 .iter_mut()
1282 .map(Vec::as_mut_slice)
1283 .collect::<Vec<_>>();
1284
1285 std::thread::sleep(std::time::Duration::from_millis(50));
1287
1288 processor.process_with_audio_buffers(
1289 256,
1290 &[],
1291 ClapTransportInfo::default(),
1292 &inputs,
1293 &mut outputs,
1294 );
1295
1296 assert!(
1297 output_buffers[0].iter().all(|&s| s == 1.0),
1298 "after crash, output should be bypass copy of input"
1299 );
1300 }
1301
1302 #[cfg_attr(
1303 all(miri, target_os = "freebsd"),
1304 ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
1305 )]
1306 #[test]
1307 fn clap_bypass_reports_zero_latency() {
1308 let host_bin = find_host_binary();
1309 if !host_bin.exists() {
1310 return;
1311 }
1312 let Ok(processor) = ClapProcessor::new(48000.0, 256, "__test__", 1, 1, host_bin) else {
1313 return;
1314 };
1315 let mapping = processor.mapping.as_ref().expect("mapping exists");
1316 unsafe {
1317 latency_samples_atomic(mapping.as_ptr()).store(128, Ordering::Release);
1318 }
1319
1320 assert_eq!(processor.latency_samples(), 128);
1321 processor.set_bypassed(true);
1322 assert_eq!(processor.latency_samples(), 0);
1323 assert!(processor.take_latency_changed());
1324 }
1325
1326 #[cfg_attr(
1327 all(miri, target_os = "freebsd"),
1328 ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
1329 )]
1330 #[test]
1331 fn clap_track_integration() {
1332 use crate::track::Track;
1333
1334 let host_bin = find_host_binary();
1335 if !host_bin.exists() {
1336 return;
1337 }
1338
1339 let plugin_path = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
1340 .parent()
1341 .unwrap()
1342 .join("daw")
1343 .join("plugin-host")
1344 .join("tests")
1345 .join("test_passthrough.clap");
1346
1347 if !plugin_path.exists() {
1348 return;
1349 }
1350
1351 let mut track = Track::new("test-track".to_string(), 2, 2, 0, 0, 256, 48000.0);
1352
1353 track
1354 .load_clap_plugin(
1355 &format!("{}::com.maolan.test.passthrough", plugin_path.display()),
1356 None,
1357 )
1358 .expect("should load CLAP plugin on track");
1359
1360 assert_eq!(track.clap_plugins.len(), 1);
1361
1362 let processor = track.clap_plugins[0].processor.clone();
1363 processor.setup_audio_ports();
1364
1365 let input_buffers = (0..processor.audio_inputs().len())
1366 .map(|i| (0..256).map(|j| (i * 1000 + j) as f32).collect::<Vec<_>>())
1367 .collect::<Vec<_>>();
1368 let mut output_buffers = vec![vec![0.0; 256]; processor.audio_outputs().len()];
1369 let inputs = input_buffers.iter().map(Vec::as_slice).collect::<Vec<_>>();
1370 let mut outputs = output_buffers
1371 .iter_mut()
1372 .map(Vec::as_mut_slice)
1373 .collect::<Vec<_>>();
1374 processor.process_with_audio_buffers(
1375 256,
1376 &[],
1377 ClapTransportInfo::default(),
1378 &inputs,
1379 &mut outputs,
1380 );
1381
1382 for (ch, output) in output_buffers.iter().enumerate() {
1383 assert!(
1384 output.iter().any(|&s| s != 0.0),
1385 "plugin output ch={ch} should contain non-zero samples after CLAP processing"
1386 );
1387 }
1388 }
1389
1390 #[cfg_attr(
1391 all(miri, target_os = "freebsd"),
1392 ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
1393 )]
1394 #[test]
1395 fn clap_processor_forwards_midi_input_port_events_to_synth() {
1396 let host_bin = find_host_binary();
1397 if !host_bin.exists() {
1398 return;
1399 }
1400
1401 let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
1402 let plugin_path = std::path::Path::new(&manifest)
1403 .parent()
1404 .unwrap()
1405 .join("plugins")
1406 .join("target")
1407 .join("release")
1408 .join("libmaolan_plugins.so");
1409
1410 if !plugin_path.exists() {
1411 return;
1412 }
1413
1414 let processor = ClapProcessor::new(
1415 48000.0,
1416 256,
1417 &format!("{}::rs.maolan.synth", plugin_path.display()),
1418 0,
1419 2,
1420 host_bin,
1421 )
1422 .expect("should create Maolan Synth processor");
1423
1424 processor.setup_audio_ports();
1425
1426 let port0 = processor
1427 .midi_input_ports()
1428 .first()
1429 .expect("Maolan Synth should expose a MIDI input port");
1430 unsafe {
1431 let mut buffer = port0.buffer_mut();
1432 buffer.push(MidiEvent::new(0, vec![0x90, 48, 100]));
1433 }
1434
1435 let input_buffers: Vec<Vec<f32>> = vec![];
1436 let mut output_buffers = vec![vec![0.0; 256]; processor.audio_outputs().len()];
1437 let inputs = input_buffers.iter().map(Vec::as_slice).collect::<Vec<_>>();
1438 let mut outputs = output_buffers
1439 .iter_mut()
1440 .map(Vec::as_mut_slice)
1441 .collect::<Vec<_>>();
1442
1443 processor.process_with_audio_buffers(
1444 256,
1445 &[],
1446 ClapTransportInfo::default(),
1447 &inputs,
1448 &mut outputs,
1449 );
1450
1451 let peak = output_buffers
1452 .iter()
1453 .flat_map(|ch| ch.iter().map(|&s| s.abs()))
1454 .fold(0.0f32, f32::max);
1455 assert!(
1456 peak > 0.001,
1457 "MIDI note-on did not reach the synth; output is silent (peak={})",
1458 peak
1459 );
1460 }
1461}