Skip to main content

maolan_engine/plugins/
clap.rs

1use crate::audio::io::AudioIO;
2use crate::midi::io::MidiEvent;
3use crate::mutex::UnsafeMutex;
4#[cfg(any(
5    target_os = "macos",
6    target_os = "linux",
7    target_os = "freebsd",
8    target_os = "openbsd"
9))]
10use crate::plugins::paths;
11use libloading::Library;
12use serde::{Deserialize, Serialize};
13use std::cell::Cell;
14use std::collections::HashMap;
15use std::ffi::{CStr, CString, c_char, c_void};
16use std::fmt;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU32, Ordering};
20use std::time::{Duration, Instant};
21
22#[derive(Clone, Debug, PartialEq)]
23pub struct ClapParameterInfo {
24    pub id: u32,
25    pub name: String,
26    pub module: String,
27    pub min_value: f64,
28    pub max_value: f64,
29    pub default_value: f64,
30}
31
32#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33pub struct ClapPluginState {
34    pub bytes: Vec<u8>,
35}
36
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct ClapMidiOutputEvent {
39    pub port: usize,
40    pub event: MidiEvent,
41}
42
43#[derive(Clone, Copy, Debug, Default)]
44pub struct ClapTransportInfo {
45    pub transport_sample: usize,
46    pub playing: bool,
47    pub loop_enabled: bool,
48    pub loop_range_samples: Option<(usize, usize)>,
49    pub bpm: f64,
50    pub tsig_num: u16,
51    pub tsig_denom: u16,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct ClapGuiInfo {
56    pub api: String,
57    pub supports_embedded: bool,
58}
59
60#[derive(Clone, Copy, Debug)]
61struct PendingParamValue {
62    param_id: u32,
63    value: f64,
64}
65
66#[derive(Clone, Copy, Debug)]
67pub struct ClapParamUpdate {
68    pub param_id: u32,
69    pub value: f64,
70}
71
72#[derive(Clone, Copy, Debug)]
73enum PendingParamEvent {
74    Value {
75        param_id: u32,
76        value: f64,
77        frame: u32,
78    },
79    GestureBegin {
80        param_id: u32,
81        frame: u32,
82    },
83    GestureEnd {
84        param_id: u32,
85        frame: u32,
86    },
87}
88
89#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
90pub struct ClapPluginInfo {
91    pub name: String,
92    pub path: String,
93    pub capabilities: Option<ClapPluginCapabilities>,
94}
95
96#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
97pub struct ClapPluginCapabilities {
98    pub has_gui: bool,
99    pub gui_apis: Vec<String>,
100    pub supports_embedded: bool,
101    pub supports_floating: bool,
102    pub has_params: bool,
103    pub has_state: bool,
104    pub has_audio_ports: bool,
105    pub has_note_ports: bool,
106}
107
108#[derive(Clone)]
109pub struct ClapProcessor {
110    path: String,
111    name: String,
112    sample_rate: f64,
113    audio_inputs: Vec<Arc<AudioIO>>,
114    audio_outputs: Vec<Arc<AudioIO>>,
115    input_port_channels: Vec<usize>,
116    output_port_channels: Vec<usize>,
117    midi_input_ports: usize,
118    midi_output_ports: usize,
119    main_audio_inputs: usize,
120    main_audio_outputs: usize,
121    host_runtime: Arc<HostRuntime>,
122    plugin_handle: Arc<PluginHandle>,
123    param_infos: Arc<Vec<ClapParameterInfo>>,
124    param_values: Arc<UnsafeMutex<HashMap<u32, f64>>>,
125    pending_param_events: Arc<UnsafeMutex<Vec<PendingParamEvent>>>,
126    pending_param_events_ui: Arc<UnsafeMutex<Vec<PendingParamEvent>>>,
127    process_lock: Arc<UnsafeMutex<()>>,
128}
129
130impl fmt::Debug for ClapProcessor {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.debug_struct("ClapProcessor")
133            .field("path", &self.path)
134            .field("name", &self.name)
135            .field("audio_inputs", &self.audio_inputs.len())
136            .field("audio_outputs", &self.audio_outputs.len())
137            .field("input_port_channels", &self.input_port_channels)
138            .field("output_port_channels", &self.output_port_channels)
139            .field("midi_input_ports", &self.midi_input_ports)
140            .field("midi_output_ports", &self.midi_output_ports)
141            .field("main_audio_inputs", &self.main_audio_inputs)
142            .field("main_audio_outputs", &self.main_audio_outputs)
143            .finish()
144    }
145}
146
147impl ClapProcessor {
148    pub fn new(
149        sample_rate: f64,
150        buffer_size: usize,
151        plugin_spec: &str,
152        input_count: usize,
153        output_count: usize,
154    ) -> Result<Self, String> {
155        let _thread_scope = HostThreadScope::enter_main();
156        let (plugin_path, plugin_id) = split_plugin_spec(plugin_spec);
157        let name = Path::new(plugin_path)
158            .file_stem()
159            .map(|s| s.to_string_lossy().to_string())
160            .unwrap_or_else(|| plugin_spec.to_string());
161        let host_runtime = Arc::new(HostRuntime::new()?);
162        let plugin_handle = Arc::new(PluginHandle::load(
163            plugin_path,
164            plugin_id,
165            host_runtime.clone(),
166            sample_rate,
167            buffer_size as u32,
168        )?);
169        let (input_port_channels, output_port_channels) = plugin_handle.audio_port_channels();
170        let discovered_inputs =
171            (!input_port_channels.is_empty()).then_some(input_port_channels.len());
172        let discovered_outputs =
173            (!output_port_channels.is_empty()).then_some(output_port_channels.len());
174        let (discovered_midi_inputs, discovered_midi_outputs) = plugin_handle.note_port_layout();
175        let resolved_inputs = discovered_inputs.unwrap_or(input_count).max(1);
176        let resolved_outputs = discovered_outputs.unwrap_or(output_count).max(1);
177        let main_audio_inputs = if discovered_inputs.is_some() {
178            usize::from(resolved_inputs > 0)
179        } else {
180            input_count.max(1)
181        };
182        let main_audio_outputs = if discovered_outputs.is_some() {
183            usize::from(resolved_outputs > 0)
184        } else {
185            output_count.max(1)
186        };
187        let audio_inputs = (0..resolved_inputs)
188            .map(|_| Arc::new(AudioIO::new(buffer_size)))
189            .collect();
190        let audio_outputs = (0..resolved_outputs)
191            .map(|_| Arc::new(AudioIO::new(buffer_size)))
192            .collect();
193        let param_infos = Arc::new(plugin_handle.parameter_infos());
194        let param_values = Arc::new(UnsafeMutex::new(
195            plugin_handle.parameter_values(&param_infos),
196        ));
197        Ok(Self {
198            path: plugin_spec.to_string(),
199            name,
200            sample_rate,
201            audio_inputs,
202            audio_outputs,
203            input_port_channels: if input_port_channels.is_empty() {
204                vec![1; resolved_inputs]
205            } else {
206                input_port_channels
207            },
208            output_port_channels: if output_port_channels.is_empty() {
209                vec![1; resolved_outputs]
210            } else {
211                output_port_channels
212            },
213            midi_input_ports: discovered_midi_inputs.unwrap_or(1).max(1),
214            midi_output_ports: discovered_midi_outputs.unwrap_or(1).max(1),
215            main_audio_inputs,
216            main_audio_outputs,
217            host_runtime,
218            plugin_handle,
219            param_infos,
220            param_values,
221            pending_param_events: Arc::new(UnsafeMutex::new(Vec::new())),
222            pending_param_events_ui: Arc::new(UnsafeMutex::new(Vec::new())),
223            process_lock: Arc::new(UnsafeMutex::new(())),
224        })
225    }
226
227    pub fn setup_audio_ports(&self) {
228        for port in &self.audio_inputs {
229            port.setup();
230        }
231        for port in &self.audio_outputs {
232            port.setup();
233        }
234    }
235
236    pub fn process_with_audio_io(&self, frames: usize) {
237        let _ = self.process_with_midi(frames, &[], ClapTransportInfo::default());
238    }
239
240    pub fn process_with_midi(
241        &self,
242        frames: usize,
243        midi_in: &[MidiEvent],
244        transport: ClapTransportInfo,
245    ) -> Vec<ClapMidiOutputEvent> {
246        // CLAP processors are not guaranteed to be re-entrant. Serialize
247        // processing per instance to avoid concurrent mutation of plugin state.
248        let _process_guard = self.process_lock.lock();
249        let started = Instant::now();
250        for port in &self.audio_inputs {
251            if port.ready() {
252                port.process();
253            }
254        }
255        let (processed, processed_midi) = match self.process_native(frames, midi_in, transport) {
256            Ok(ok) => ok,
257            Err(err) => {
258                tracing::warn!(
259                    "CLAP process failed for '{}' ({}): {}",
260                    self.name,
261                    self.path,
262                    err
263                );
264                (false, Vec::new())
265            }
266        };
267        let elapsed = started.elapsed();
268        if elapsed > Duration::from_millis(20) {
269            tracing::warn!(
270                "Slow CLAP process '{}' ({}) took {:.3} ms for {} frames",
271                self.name,
272                self.path,
273                elapsed.as_secs_f64() * 1000.0,
274                frames
275            );
276        }
277        if !processed {
278            for out in &self.audio_outputs {
279                let out_buf = out.buffer.lock();
280                out_buf.fill(0.0);
281                *out.finished.lock() = true;
282            }
283        }
284        processed_midi
285    }
286
287    pub fn parameter_infos(&self) -> Vec<ClapParameterInfo> {
288        self.param_infos.as_ref().clone()
289    }
290
291    pub fn parameter_values(&self) -> HashMap<u32, f64> {
292        self.param_values.lock().clone()
293    }
294
295    pub fn set_parameter(&self, param_id: u32, value: f64) -> Result<(), String> {
296        self.set_parameter_at(param_id, value, 0)
297    }
298
299    pub fn set_parameter_at(&self, param_id: u32, value: f64, frame: u32) -> Result<(), String> {
300        let _thread_scope = HostThreadScope::enter_main();
301        let Some(info) = self.param_infos.iter().find(|p| p.id == param_id) else {
302            return Err(format!("Unknown CLAP parameter id: {param_id}"));
303        };
304        let clamped = value.clamp(info.min_value, info.max_value);
305        self.pending_param_events
306            .lock()
307            .push(PendingParamEvent::Value {
308                param_id,
309                value: clamped,
310                frame,
311            });
312        self.pending_param_events_ui
313            .lock()
314            .push(PendingParamEvent::Value {
315                param_id,
316                value: clamped,
317                frame,
318            });
319        self.param_values.lock().insert(param_id, clamped);
320        Ok(())
321    }
322
323    pub fn begin_parameter_edit(&self, param_id: u32) -> Result<(), String> {
324        self.begin_parameter_edit_at(param_id, 0)
325    }
326
327    pub fn begin_parameter_edit_at(&self, param_id: u32, frame: u32) -> Result<(), String> {
328        let _thread_scope = HostThreadScope::enter_main();
329        if !self.param_infos.iter().any(|p| p.id == param_id) {
330            return Err(format!("Unknown CLAP parameter id: {param_id}"));
331        }
332        self.pending_param_events
333            .lock()
334            .push(PendingParamEvent::GestureBegin { param_id, frame });
335        self.pending_param_events_ui
336            .lock()
337            .push(PendingParamEvent::GestureBegin { param_id, frame });
338        Ok(())
339    }
340
341    pub fn end_parameter_edit(&self, param_id: u32) -> Result<(), String> {
342        self.end_parameter_edit_at(param_id, 0)
343    }
344
345    pub fn end_parameter_edit_at(&self, param_id: u32, frame: u32) -> Result<(), String> {
346        let _thread_scope = HostThreadScope::enter_main();
347        if !self.param_infos.iter().any(|p| p.id == param_id) {
348            return Err(format!("Unknown CLAP parameter id: {param_id}"));
349        }
350        self.pending_param_events
351            .lock()
352            .push(PendingParamEvent::GestureEnd { param_id, frame });
353        self.pending_param_events_ui
354            .lock()
355            .push(PendingParamEvent::GestureEnd { param_id, frame });
356        Ok(())
357    }
358
359    pub fn snapshot_state(&self) -> Result<ClapPluginState, String> {
360        let _thread_scope = HostThreadScope::enter_main();
361        self.plugin_handle.snapshot_state()
362    }
363
364    pub fn restore_state(&self, state: &ClapPluginState) -> Result<(), String> {
365        let _thread_scope = HostThreadScope::enter_main();
366        self.plugin_handle.restore_state(state)
367    }
368
369    pub fn audio_inputs(&self) -> &[Arc<AudioIO>] {
370        &self.audio_inputs
371    }
372
373    pub fn audio_outputs(&self) -> &[Arc<AudioIO>] {
374        &self.audio_outputs
375    }
376
377    pub fn main_audio_input_count(&self) -> usize {
378        self.main_audio_inputs
379    }
380
381    pub fn main_audio_output_count(&self) -> usize {
382        self.main_audio_outputs
383    }
384
385    pub fn midi_input_count(&self) -> usize {
386        self.midi_input_ports
387    }
388
389    pub fn midi_output_count(&self) -> usize {
390        self.midi_output_ports
391    }
392
393    pub fn path(&self) -> &str {
394        &self.path
395    }
396
397    pub fn name(&self) -> &str {
398        &self.name
399    }
400
401    pub fn ui_begin_session(&self) {
402        self.host_runtime.begin_ui_session();
403    }
404
405    pub fn ui_end_session(&self) {
406        self.host_runtime.end_ui_session();
407    }
408
409    pub fn ui_should_close(&self) -> bool {
410        self.host_runtime.ui_should_close()
411    }
412
413    pub fn ui_take_due_timers(&self) -> Vec<u32> {
414        self.host_runtime.ui_take_due_timers()
415    }
416
417    pub fn ui_take_param_updates(&self) -> Vec<ClapParamUpdate> {
418        let pending_ui_events = std::mem::take(self.pending_param_events_ui.lock());
419        if pending_ui_events.is_empty() && !self.host_runtime.ui_take_param_flush_requested() {
420            return Vec::new();
421        }
422        let _thread_scope = HostThreadScope::enter_main();
423        let updates = self.plugin_handle.flush_params(&pending_ui_events);
424        if updates.is_empty() {
425            return Vec::new();
426        }
427        let values = &mut *self.param_values.lock();
428        let mut out = Vec::with_capacity(updates.len());
429        for update in updates {
430            values.insert(update.param_id, update.value);
431            out.push(ClapParamUpdate {
432                param_id: update.param_id,
433                value: update.value,
434            });
435        }
436        out
437    }
438
439    pub fn ui_take_state_update(&self) -> Option<ClapPluginState> {
440        if !self.host_runtime.ui_take_state_dirty_requested() {
441            return None;
442        }
443        let _thread_scope = HostThreadScope::enter_main();
444        self.plugin_handle.snapshot_state().ok()
445    }
446
447    pub fn gui_info(&self) -> Result<ClapGuiInfo, String> {
448        let _thread_scope = HostThreadScope::enter_main();
449        self.plugin_handle.gui_info()
450    }
451
452    pub fn gui_create(&self, api: &str, is_floating: bool) -> Result<(), String> {
453        let _thread_scope = HostThreadScope::enter_main();
454        self.plugin_handle.gui_create(api, is_floating)
455    }
456
457    pub fn gui_get_size(&self) -> Result<(u32, u32), String> {
458        let _thread_scope = HostThreadScope::enter_main();
459        self.plugin_handle.gui_get_size()
460    }
461
462    pub fn gui_set_parent_x11(&self, window: usize) -> Result<(), String> {
463        let _thread_scope = HostThreadScope::enter_main();
464        self.plugin_handle.gui_set_parent_x11(window)
465    }
466
467    pub fn gui_show(&self) -> Result<(), String> {
468        let _thread_scope = HostThreadScope::enter_main();
469        self.plugin_handle.gui_show()
470    }
471
472    pub fn gui_hide(&self) {
473        let _thread_scope = HostThreadScope::enter_main();
474        self.plugin_handle.gui_hide();
475    }
476
477    pub fn gui_destroy(&self) {
478        let _thread_scope = HostThreadScope::enter_main();
479        self.plugin_handle.gui_destroy();
480    }
481
482    pub fn gui_on_main_thread(&self) {
483        let _thread_scope = HostThreadScope::enter_main();
484        self.plugin_handle.on_main_thread();
485    }
486
487    pub fn gui_on_timer(&self, timer_id: u32) {
488        let _thread_scope = HostThreadScope::enter_main();
489        self.plugin_handle.gui_on_timer(timer_id);
490    }
491
492    pub fn run_host_callbacks_main_thread(&self) {
493        let host_flags = self.host_runtime.take_callback_flags();
494        if host_flags.restart {
495            let _thread_scope = HostThreadScope::enter_main();
496            self.plugin_handle.reset();
497        }
498        if host_flags.callback {
499            let _thread_scope = HostThreadScope::enter_main();
500            self.plugin_handle.on_main_thread();
501        }
502        if host_flags.process {
503            // Host already continuously schedules process blocks.
504        }
505    }
506
507    fn process_native(
508        &self,
509        frames: usize,
510        midi_in: &[MidiEvent],
511        transport: ClapTransportInfo,
512    ) -> Result<(bool, Vec<ClapMidiOutputEvent>), String> {
513        if frames == 0 {
514            return Ok((true, Vec::new()));
515        }
516
517        let mut in_channel_ptrs: Vec<Vec<*mut f32>> = Vec::with_capacity(self.audio_inputs.len());
518        let mut out_channel_ptrs: Vec<Vec<*mut f32>> = Vec::with_capacity(self.audio_outputs.len());
519        let mut in_channel_scratch: Vec<Vec<f32>> = Vec::new();
520        let mut out_channel_scratch: Vec<Vec<f32>> = Vec::new();
521        let mut out_channel_scratch_ranges: Vec<(usize, usize)> =
522            Vec::with_capacity(self.audio_outputs.len());
523        let mut in_buffers = Vec::with_capacity(self.audio_inputs.len());
524        let mut out_buffers = Vec::with_capacity(self.audio_outputs.len());
525
526        for (port_idx, input) in self.audio_inputs.iter().enumerate() {
527            let buf = input.buffer.lock();
528            let channel_count = self
529                .input_port_channels
530                .get(port_idx)
531                .copied()
532                .unwrap_or(1)
533                .max(1);
534            let mut ptrs = Vec::with_capacity(channel_count);
535            ptrs.push(buf.as_ptr() as *mut f32);
536            for _ in 1..channel_count {
537                in_channel_scratch.push(buf.to_vec());
538                let idx = in_channel_scratch.len().saturating_sub(1);
539                ptrs.push(in_channel_scratch[idx].as_mut_ptr());
540            }
541            in_channel_ptrs.push(ptrs);
542            in_buffers.push(buf);
543        }
544        for (port_idx, output) in self.audio_outputs.iter().enumerate() {
545            let buf = output.buffer.lock();
546            let channel_count = self
547                .output_port_channels
548                .get(port_idx)
549                .copied()
550                .unwrap_or(1)
551                .max(1);
552            let mut ptrs = Vec::with_capacity(channel_count);
553            ptrs.push(buf.as_mut_ptr());
554            let scratch_start = out_channel_scratch.len();
555            for _ in 1..channel_count {
556                out_channel_scratch.push(vec![0.0; frames]);
557                let idx = out_channel_scratch.len().saturating_sub(1);
558                ptrs.push(out_channel_scratch[idx].as_mut_ptr());
559            }
560            let scratch_end = out_channel_scratch.len();
561            out_channel_scratch_ranges.push((scratch_start, scratch_end));
562            out_channel_ptrs.push(ptrs);
563            out_buffers.push(buf);
564        }
565
566        let mut in_audio = Vec::with_capacity(self.audio_inputs.len());
567        let mut out_audio = Vec::with_capacity(self.audio_outputs.len());
568
569        for ptrs in &mut in_channel_ptrs {
570            in_audio.push(ClapAudioBuffer {
571                data32: ptrs.as_mut_ptr(),
572                data64: std::ptr::null_mut(),
573                channel_count: ptrs.len() as u32,
574                latency: 0,
575                constant_mask: 0,
576            });
577        }
578        for ptrs in &mut out_channel_ptrs {
579            out_audio.push(ClapAudioBuffer {
580                data32: ptrs.as_mut_ptr(),
581                data64: std::ptr::null_mut(),
582                channel_count: ptrs.len() as u32,
583                latency: 0,
584                constant_mask: 0,
585            });
586        }
587
588        let pending_params = std::mem::take(self.pending_param_events.lock());
589        let (in_events, in_ctx) =
590            input_events_from(midi_in, &pending_params, self.sample_rate, transport);
591        let out_cap = midi_in
592            .len()
593            .saturating_add(self.midi_output_ports.saturating_mul(64));
594        let (mut out_events, mut out_ctx) = output_events_ctx(out_cap);
595
596        let mut process = ClapProcess {
597            steady_time: -1,
598            frames_count: frames as u32,
599            transport: std::ptr::null(),
600            audio_inputs: in_audio.as_mut_ptr(),
601            audio_outputs: out_audio.as_mut_ptr(),
602            audio_inputs_count: in_audio.len() as u32,
603            audio_outputs_count: out_audio.len() as u32,
604            in_events: &in_events,
605            out_events: &mut out_events,
606        };
607
608        let _thread_scope = HostThreadScope::enter_audio();
609        let result = self.plugin_handle.process(&mut process);
610        drop(in_ctx);
611        for output in &self.audio_outputs {
612            *output.finished.lock() = true;
613        }
614        let processed = result?;
615        if processed {
616            // Downmix multi-channel CLAP output ports into track output buffers.
617            for (port_idx, out_buf) in out_buffers.iter_mut().enumerate() {
618                let Some((scratch_start, scratch_end)) = out_channel_scratch_ranges.get(port_idx)
619                else {
620                    continue;
621                };
622                let scratch_count = scratch_end.saturating_sub(*scratch_start);
623                if scratch_count == 0 {
624                    continue;
625                }
626                let ch_count = scratch_count + 1;
627                for scratch in &out_channel_scratch[*scratch_start..*scratch_end] {
628                    for (dst, src) in out_buf.iter_mut().zip(scratch.iter().take(frames)) {
629                        *dst += *src;
630                    }
631                }
632                let inv = 1.0_f32 / ch_count as f32;
633                for sample in out_buf.iter_mut().take(frames) {
634                    *sample *= inv;
635                }
636            }
637            for update in &out_ctx.param_values {
638                self.param_values
639                    .lock()
640                    .insert(update.param_id, update.value);
641            }
642            Ok((true, std::mem::take(&mut out_ctx.midi_events)))
643        } else {
644            Ok((false, Vec::new()))
645        }
646    }
647}
648
649#[repr(C)]
650#[derive(Clone, Copy)]
651struct ClapVersion {
652    major: u32,
653    minor: u32,
654    revision: u32,
655}
656
657const CLAP_VERSION: ClapVersion = ClapVersion {
658    major: 1,
659    minor: 2,
660    revision: 0,
661};
662
663#[repr(C)]
664struct ClapHost {
665    clap_version: ClapVersion,
666    host_data: *mut c_void,
667    name: *const c_char,
668    vendor: *const c_char,
669    url: *const c_char,
670    version: *const c_char,
671    get_extension: Option<unsafe extern "C" fn(*const ClapHost, *const c_char) -> *const c_void>,
672    request_restart: Option<unsafe extern "C" fn(*const ClapHost)>,
673    request_process: Option<unsafe extern "C" fn(*const ClapHost)>,
674    request_callback: Option<unsafe extern "C" fn(*const ClapHost)>,
675}
676
677#[repr(C)]
678struct ClapPluginEntry {
679    clap_version: ClapVersion,
680    init: Option<unsafe extern "C" fn(*const ClapHost) -> bool>,
681    deinit: Option<unsafe extern "C" fn()>,
682    get_factory: Option<unsafe extern "C" fn(*const c_char) -> *const c_void>,
683}
684
685#[repr(C)]
686struct ClapPluginFactory {
687    get_plugin_count: Option<unsafe extern "C" fn(*const ClapPluginFactory) -> u32>,
688    get_plugin_descriptor:
689        Option<unsafe extern "C" fn(*const ClapPluginFactory, u32) -> *const ClapPluginDescriptor>,
690    create_plugin: Option<
691        unsafe extern "C" fn(
692            *const ClapPluginFactory,
693            *const ClapHost,
694            *const c_char,
695        ) -> *const ClapPlugin,
696    >,
697}
698
699#[repr(C)]
700struct ClapPluginDescriptor {
701    clap_version: ClapVersion,
702    id: *const c_char,
703    name: *const c_char,
704    vendor: *const c_char,
705    url: *const c_char,
706    manual_url: *const c_char,
707    support_url: *const c_char,
708    version: *const c_char,
709    description: *const c_char,
710    features: *const *const c_char,
711}
712
713#[repr(C)]
714struct ClapPlugin {
715    desc: *const ClapPluginDescriptor,
716    plugin_data: *mut c_void,
717    init: Option<unsafe extern "C" fn(*const ClapPlugin) -> bool>,
718    destroy: Option<unsafe extern "C" fn(*const ClapPlugin)>,
719    activate: Option<unsafe extern "C" fn(*const ClapPlugin, f64, u32, u32) -> bool>,
720    deactivate: Option<unsafe extern "C" fn(*const ClapPlugin)>,
721    start_processing: Option<unsafe extern "C" fn(*const ClapPlugin) -> bool>,
722    stop_processing: Option<unsafe extern "C" fn(*const ClapPlugin)>,
723    reset: Option<unsafe extern "C" fn(*const ClapPlugin)>,
724    process: Option<unsafe extern "C" fn(*const ClapPlugin, *const ClapProcess) -> i32>,
725    get_extension: Option<unsafe extern "C" fn(*const ClapPlugin, *const c_char) -> *const c_void>,
726    on_main_thread: Option<unsafe extern "C" fn(*const ClapPlugin)>,
727}
728
729#[repr(C)]
730struct ClapInputEvents {
731    ctx: *const c_void,
732    size: Option<unsafe extern "C" fn(*const ClapInputEvents) -> u32>,
733    get: Option<unsafe extern "C" fn(*const ClapInputEvents, u32) -> *const ClapEventHeader>,
734}
735
736#[repr(C)]
737struct ClapOutputEvents {
738    ctx: *mut c_void,
739    try_push: Option<unsafe extern "C" fn(*const ClapOutputEvents, *const ClapEventHeader) -> bool>,
740}
741
742#[repr(C)]
743struct ClapEventHeader {
744    size: u32,
745    time: u32,
746    space_id: u16,
747    type_: u16,
748    flags: u32,
749}
750
751const CLAP_CORE_EVENT_SPACE_ID: u16 = 0;
752const CLAP_EVENT_MIDI: u16 = 10;
753const CLAP_EVENT_PARAM_VALUE: u16 = 5;
754const CLAP_EVENT_PARAM_GESTURE_BEGIN: u16 = 6;
755const CLAP_EVENT_PARAM_GESTURE_END: u16 = 7;
756const CLAP_EVENT_TRANSPORT: u16 = 9;
757const CLAP_TRANSPORT_HAS_TEMPO: u32 = 1 << 0;
758const CLAP_TRANSPORT_HAS_BEATS_TIMELINE: u32 = 1 << 1;
759const CLAP_TRANSPORT_HAS_SECONDS_TIMELINE: u32 = 1 << 2;
760const CLAP_TRANSPORT_HAS_TIME_SIGNATURE: u32 = 1 << 3;
761const CLAP_TRANSPORT_IS_PLAYING: u32 = 1 << 4;
762const CLAP_TRANSPORT_IS_LOOP_ACTIVE: u32 = 1 << 6;
763const CLAP_BEATTIME_FACTOR: i64 = 1_i64 << 31;
764const CLAP_SECTIME_FACTOR: i64 = 1_i64 << 31;
765
766#[repr(C)]
767struct ClapEventMidi {
768    header: ClapEventHeader,
769    port_index: u16,
770    data: [u8; 3],
771}
772
773#[repr(C)]
774struct ClapEventParamValue {
775    header: ClapEventHeader,
776    param_id: u32,
777    cookie: *mut c_void,
778    note_id: i32,
779    port_index: i16,
780    channel: i16,
781    key: i16,
782    value: f64,
783}
784
785#[repr(C)]
786struct ClapEventParamGesture {
787    header: ClapEventHeader,
788    param_id: u32,
789}
790
791#[repr(C)]
792struct ClapEventTransport {
793    header: ClapEventHeader,
794    flags: u32,
795    song_pos_beats: i64,
796    song_pos_seconds: i64,
797    tempo: f64,
798    tempo_inc: f64,
799    loop_start_beats: i64,
800    loop_end_beats: i64,
801    loop_start_seconds: i64,
802    loop_end_seconds: i64,
803    bar_start: i64,
804    bar_number: i32,
805    tsig_num: u16,
806    tsig_denom: u16,
807}
808
809#[repr(C)]
810struct ClapParamInfoRaw {
811    id: u32,
812    flags: u32,
813    cookie: *mut c_void,
814    name: [c_char; 256],
815    module: [c_char; 1024],
816    min_value: f64,
817    max_value: f64,
818    default_value: f64,
819}
820
821#[repr(C)]
822struct ClapPluginParams {
823    count: Option<unsafe extern "C" fn(*const ClapPlugin) -> u32>,
824    get_info: Option<unsafe extern "C" fn(*const ClapPlugin, u32, *mut ClapParamInfoRaw) -> bool>,
825    get_value: Option<unsafe extern "C" fn(*const ClapPlugin, u32, *mut f64) -> bool>,
826    value_to_text:
827        Option<unsafe extern "C" fn(*const ClapPlugin, u32, f64, *mut c_char, u32) -> bool>,
828    text_to_value:
829        Option<unsafe extern "C" fn(*const ClapPlugin, u32, *const c_char, *mut f64) -> bool>,
830    flush: Option<
831        unsafe extern "C" fn(*const ClapPlugin, *const ClapInputEvents, *const ClapOutputEvents),
832    >,
833}
834
835#[repr(C)]
836struct ClapPluginStateExt {
837    save: Option<unsafe extern "C" fn(*const ClapPlugin, *const ClapOStream) -> bool>,
838    load: Option<unsafe extern "C" fn(*const ClapPlugin, *const ClapIStream) -> bool>,
839}
840
841#[repr(C)]
842struct ClapAudioPortInfoRaw {
843    id: u32,
844    name: [c_char; 256],
845    flags: u32,
846    channel_count: u32,
847    port_type: *const c_char,
848    in_place_pair: u32,
849}
850
851#[repr(C)]
852struct ClapPluginAudioPorts {
853    count: Option<unsafe extern "C" fn(*const ClapPlugin, bool) -> u32>,
854    get: Option<
855        unsafe extern "C" fn(*const ClapPlugin, u32, bool, *mut ClapAudioPortInfoRaw) -> bool,
856    >,
857}
858
859#[repr(C)]
860struct ClapNotePortInfoRaw {
861    id: u16,
862    supported_dialects: u32,
863    preferred_dialect: u32,
864    name: [c_char; 256],
865}
866
867#[repr(C)]
868struct ClapPluginNotePorts {
869    count: Option<unsafe extern "C" fn(*const ClapPlugin, bool) -> u32>,
870    get: Option<
871        unsafe extern "C" fn(*const ClapPlugin, u32, bool, *mut ClapNotePortInfoRaw) -> bool,
872    >,
873}
874
875#[repr(C)]
876struct ClapPluginGui {
877    is_api_supported: Option<unsafe extern "C" fn(*const ClapPlugin, *const c_char, bool) -> bool>,
878    get_preferred_api:
879        Option<unsafe extern "C" fn(*const ClapPlugin, *mut *const c_char, *mut bool) -> bool>,
880    create: Option<unsafe extern "C" fn(*const ClapPlugin, *const c_char, bool) -> bool>,
881    destroy: Option<unsafe extern "C" fn(*const ClapPlugin)>,
882    set_scale: Option<unsafe extern "C" fn(*const ClapPlugin, f64) -> bool>,
883    get_size: Option<unsafe extern "C" fn(*const ClapPlugin, *mut u32, *mut u32) -> bool>,
884    can_resize: Option<unsafe extern "C" fn(*const ClapPlugin) -> bool>,
885    get_resize_hints: Option<unsafe extern "C" fn(*const ClapPlugin, *mut c_void) -> bool>,
886    adjust_size: Option<unsafe extern "C" fn(*const ClapPlugin, *mut u32, *mut u32) -> bool>,
887    set_size: Option<unsafe extern "C" fn(*const ClapPlugin, u32, u32) -> bool>,
888    set_parent: Option<unsafe extern "C" fn(*const ClapPlugin, *const ClapWindow) -> bool>,
889    set_transient: Option<unsafe extern "C" fn(*const ClapPlugin, *const ClapWindow) -> bool>,
890    suggest_title: Option<unsafe extern "C" fn(*const ClapPlugin, *const c_char)>,
891    show: Option<unsafe extern "C" fn(*const ClapPlugin) -> bool>,
892    hide: Option<unsafe extern "C" fn(*const ClapPlugin) -> bool>,
893}
894
895#[repr(C)]
896union ClapWindowHandle {
897    x11: usize,
898    native: *mut c_void,
899    cocoa: *mut c_void,
900}
901
902#[repr(C)]
903struct ClapWindow {
904    api: *const c_char,
905    handle: ClapWindowHandle,
906}
907
908#[repr(C)]
909struct ClapPluginTimerSupport {
910    on_timer: Option<unsafe extern "C" fn(*const ClapPlugin, u32)>,
911}
912
913#[repr(C)]
914struct ClapHostThreadCheck {
915    is_main_thread: Option<unsafe extern "C" fn(*const ClapHost) -> bool>,
916    is_audio_thread: Option<unsafe extern "C" fn(*const ClapHost) -> bool>,
917}
918
919#[repr(C)]
920struct ClapHostLatency {
921    changed: Option<unsafe extern "C" fn(*const ClapHost)>,
922}
923
924#[repr(C)]
925struct ClapHostTail {
926    changed: Option<unsafe extern "C" fn(*const ClapHost)>,
927}
928
929#[repr(C)]
930struct ClapHostTimerSupport {
931    register_timer: Option<unsafe extern "C" fn(*const ClapHost, u32, *mut u32) -> bool>,
932    unregister_timer: Option<unsafe extern "C" fn(*const ClapHost, u32) -> bool>,
933}
934
935#[repr(C)]
936struct ClapHostGui {
937    resize_hints_changed: Option<unsafe extern "C" fn(*const ClapHost)>,
938    request_resize: Option<unsafe extern "C" fn(*const ClapHost, u32, u32) -> bool>,
939    request_show: Option<unsafe extern "C" fn(*const ClapHost) -> bool>,
940    request_hide: Option<unsafe extern "C" fn(*const ClapHost) -> bool>,
941    closed: Option<unsafe extern "C" fn(*const ClapHost, bool)>,
942}
943
944#[repr(C)]
945struct ClapHostParams {
946    rescan: Option<unsafe extern "C" fn(*const ClapHost, u32)>,
947    clear: Option<unsafe extern "C" fn(*const ClapHost, u32, u32)>,
948    request_flush: Option<unsafe extern "C" fn(*const ClapHost)>,
949}
950
951#[repr(C)]
952struct ClapHostState {
953    mark_dirty: Option<unsafe extern "C" fn(*const ClapHost)>,
954}
955
956#[repr(C)]
957struct ClapOStream {
958    ctx: *mut c_void,
959    write: Option<unsafe extern "C" fn(*const ClapOStream, *const c_void, u64) -> i64>,
960}
961
962#[repr(C)]
963struct ClapIStream {
964    ctx: *mut c_void,
965    read: Option<unsafe extern "C" fn(*const ClapIStream, *mut c_void, u64) -> i64>,
966}
967
968#[repr(C)]
969struct ClapAudioBuffer {
970    data32: *mut *mut f32,
971    data64: *mut *mut f64,
972    channel_count: u32,
973    latency: u32,
974    constant_mask: u64,
975}
976
977#[repr(C)]
978struct ClapProcess {
979    steady_time: i64,
980    frames_count: u32,
981    transport: *const c_void,
982    audio_inputs: *mut ClapAudioBuffer,
983    audio_outputs: *mut ClapAudioBuffer,
984    audio_inputs_count: u32,
985    audio_outputs_count: u32,
986    in_events: *const ClapInputEvents,
987    out_events: *mut ClapOutputEvents,
988}
989
990enum ClapInputEvent {
991    Midi(ClapEventMidi),
992    ParamValue(ClapEventParamValue),
993    ParamGesture(ClapEventParamGesture),
994    Transport(ClapEventTransport),
995}
996
997impl ClapInputEvent {
998    fn header_ptr(&self) -> *const ClapEventHeader {
999        match self {
1000            Self::Midi(e) => &e.header as *const ClapEventHeader,
1001            Self::ParamValue(e) => &e.header as *const ClapEventHeader,
1002            Self::ParamGesture(e) => &e.header as *const ClapEventHeader,
1003            Self::Transport(e) => &e.header as *const ClapEventHeader,
1004        }
1005    }
1006}
1007
1008struct ClapInputEventsCtx {
1009    events: Vec<ClapInputEvent>,
1010}
1011
1012struct ClapOutputEventsCtx {
1013    midi_events: Vec<ClapMidiOutputEvent>,
1014    param_values: Vec<PendingParamValue>,
1015}
1016
1017struct ClapIStreamCtx<'a> {
1018    bytes: &'a [u8],
1019    offset: usize,
1020}
1021
1022#[derive(Default, Clone, Copy)]
1023struct HostCallbackFlags {
1024    restart: bool,
1025    process: bool,
1026    callback: bool,
1027}
1028
1029#[derive(Clone, Copy)]
1030struct HostTimer {
1031    id: u32,
1032    period: Duration,
1033    next_tick: Instant,
1034}
1035
1036struct HostRuntimeState {
1037    callback_flags: UnsafeMutex<HostCallbackFlags>,
1038    timers: UnsafeMutex<Vec<HostTimer>>,
1039    ui_should_close: AtomicU32,
1040    ui_active: AtomicU32,
1041    param_flush_requested: AtomicU32,
1042    state_dirty_requested: AtomicU32,
1043}
1044
1045thread_local! {
1046    static CLAP_HOST_MAIN_THREAD: Cell<bool> = const { Cell::new(true) };
1047    static CLAP_HOST_AUDIO_THREAD: Cell<bool> = const { Cell::new(false) };
1048}
1049
1050struct HostThreadScope {
1051    main: bool,
1052    prev: bool,
1053}
1054
1055impl HostThreadScope {
1056    fn enter_main() -> Self {
1057        let prev = CLAP_HOST_MAIN_THREAD.with(|flag| {
1058            let prev = flag.get();
1059            flag.set(true);
1060            prev
1061        });
1062        Self { main: true, prev }
1063    }
1064
1065    fn enter_audio() -> Self {
1066        let prev = CLAP_HOST_AUDIO_THREAD.with(|flag| {
1067            let prev = flag.get();
1068            flag.set(true);
1069            prev
1070        });
1071        Self { main: false, prev }
1072    }
1073}
1074
1075impl Drop for HostThreadScope {
1076    fn drop(&mut self) {
1077        if self.main {
1078            CLAP_HOST_MAIN_THREAD.with(|flag| flag.set(self.prev));
1079        } else {
1080            CLAP_HOST_AUDIO_THREAD.with(|flag| flag.set(self.prev));
1081        }
1082    }
1083}
1084
1085struct HostRuntime {
1086    state: Box<HostRuntimeState>,
1087    host: ClapHost,
1088}
1089
1090impl HostRuntime {
1091    fn new() -> Result<Self, String> {
1092        let mut state = Box::new(HostRuntimeState {
1093            callback_flags: UnsafeMutex::new(HostCallbackFlags::default()),
1094            timers: UnsafeMutex::new(Vec::new()),
1095            ui_should_close: AtomicU32::new(0),
1096            ui_active: AtomicU32::new(0),
1097            param_flush_requested: AtomicU32::new(0),
1098            state_dirty_requested: AtomicU32::new(0),
1099        });
1100        let host = ClapHost {
1101            clap_version: CLAP_VERSION,
1102            host_data: (&mut *state as *mut HostRuntimeState).cast::<c_void>(),
1103            name: c"Maolan".as_ptr(),
1104            vendor: c"Maolan".as_ptr(),
1105            url: c"https://example.invalid".as_ptr(),
1106            version: c"0.0.1".as_ptr(),
1107            get_extension: Some(host_get_extension),
1108            request_restart: Some(host_request_restart),
1109            request_process: Some(host_request_process),
1110            request_callback: Some(host_request_callback),
1111        };
1112        Ok(Self { state, host })
1113    }
1114
1115    fn take_callback_flags(&self) -> HostCallbackFlags {
1116        let flags = self.state.callback_flags.lock();
1117        let out = *flags;
1118        *flags = HostCallbackFlags::default();
1119        out
1120    }
1121
1122    fn begin_ui_session(&self) {
1123        self.state.ui_should_close.store(0, Ordering::Release);
1124        self.state.ui_active.store(1, Ordering::Release);
1125        self.state.param_flush_requested.store(0, Ordering::Release);
1126        self.state.state_dirty_requested.store(0, Ordering::Release);
1127        self.state.timers.lock().clear();
1128    }
1129
1130    fn end_ui_session(&self) {
1131        self.state.ui_active.store(0, Ordering::Release);
1132        self.state.ui_should_close.store(0, Ordering::Release);
1133        self.state.param_flush_requested.store(0, Ordering::Release);
1134        self.state.state_dirty_requested.store(0, Ordering::Release);
1135        self.state.timers.lock().clear();
1136    }
1137
1138    fn ui_should_close(&self) -> bool {
1139        self.state.ui_should_close.load(Ordering::Acquire) != 0
1140    }
1141
1142    fn ui_take_due_timers(&self) -> Vec<u32> {
1143        let now = Instant::now();
1144        let timers = &mut *self.state.timers.lock();
1145        let mut due = Vec::new();
1146        for timer in timers.iter_mut() {
1147            if now >= timer.next_tick {
1148                due.push(timer.id);
1149                timer.next_tick = now + timer.period;
1150            }
1151        }
1152        due
1153    }
1154
1155    fn ui_take_param_flush_requested(&self) -> bool {
1156        self.state.param_flush_requested.swap(0, Ordering::AcqRel) != 0
1157    }
1158
1159    fn ui_take_state_dirty_requested(&self) -> bool {
1160        self.state.state_dirty_requested.swap(0, Ordering::AcqRel) != 0
1161    }
1162}
1163
1164// SAFETY: HostRuntime owns stable CString storage and a CLAP host struct that
1165// contains raw pointers into that owned storage. The data is immutable after
1166// construction and safe to share/move across threads.
1167unsafe impl Send for HostRuntime {}
1168// SAFETY: See Send rationale above; HostRuntime has no interior mutation.
1169unsafe impl Sync for HostRuntime {}
1170
1171struct PluginHandle {
1172    _library: Library,
1173    entry: *const ClapPluginEntry,
1174    plugin: *const ClapPlugin,
1175}
1176
1177// SAFETY: PluginHandle only stores pointers/libraries managed by the CLAP ABI.
1178// Access to plugin processing is synchronized by the engine track scheduling.
1179unsafe impl Send for PluginHandle {}
1180// SAFETY: Shared references do not mutate PluginHandle fields directly.
1181unsafe impl Sync for PluginHandle {}
1182
1183impl PluginHandle {
1184    fn load(
1185        plugin_path: &str,
1186        plugin_id: Option<&str>,
1187        host_runtime: Arc<HostRuntime>,
1188        sample_rate: f64,
1189        frames: u32,
1190    ) -> Result<Self, String> {
1191        let factory_id = c"clap.plugin-factory";
1192
1193        // SAFETY: We keep `library` alive for at least as long as plugin and entry pointers.
1194        let library = unsafe { Library::new(plugin_path) }.map_err(|e| e.to_string())?;
1195        // SAFETY: Symbol name and type follow CLAP ABI (`clap_entry` global variable).
1196        let entry_ptr = unsafe {
1197            let sym = library
1198                .get::<*const ClapPluginEntry>(b"clap_entry\0")
1199                .map_err(|e| e.to_string())?;
1200            *sym
1201        };
1202        if entry_ptr.is_null() {
1203            return Err("CLAP entry symbol is null".to_string());
1204        }
1205        // SAFETY: entry pointer comes from validated CLAP symbol.
1206        let entry = unsafe { &*entry_ptr };
1207        let init = entry
1208            .init
1209            .ok_or_else(|| "CLAP entry missing init()".to_string())?;
1210        let host_ptr = &host_runtime.host as *const ClapHost;
1211        // SAFETY: Valid host pointer for plugin bundle.
1212        if unsafe { !init(host_ptr) } {
1213            return Err(format!("CLAP entry init failed for {plugin_path}"));
1214        }
1215        let get_factory = entry
1216            .get_factory
1217            .ok_or_else(|| "CLAP entry missing get_factory()".to_string())?;
1218        // SAFETY: Factory id is a static NUL-terminated C string.
1219        let factory = unsafe { get_factory(factory_id.as_ptr()) } as *const ClapPluginFactory;
1220        if factory.is_null() {
1221            return Err("CLAP plugin factory not found".to_string());
1222        }
1223        // SAFETY: factory pointer was validated above.
1224        let factory_ref = unsafe { &*factory };
1225        let get_count = factory_ref
1226            .get_plugin_count
1227            .ok_or_else(|| "CLAP factory missing get_plugin_count()".to_string())?;
1228        let get_desc = factory_ref
1229            .get_plugin_descriptor
1230            .ok_or_else(|| "CLAP factory missing get_plugin_descriptor()".to_string())?;
1231        let create = factory_ref
1232            .create_plugin
1233            .ok_or_else(|| "CLAP factory missing create_plugin()".to_string())?;
1234
1235        // SAFETY: factory function pointers are valid CLAP ABI function pointers.
1236        let count = unsafe { get_count(factory) };
1237        if count == 0 {
1238            return Err("CLAP factory returned zero plugins".to_string());
1239        }
1240        let mut selected_id = None::<CString>;
1241        for i in 0..count {
1242            // SAFETY: i < count.
1243            let desc = unsafe { get_desc(factory, i) };
1244            if desc.is_null() {
1245                continue;
1246            }
1247            // SAFETY: descriptor pointer comes from factory.
1248            let desc = unsafe { &*desc };
1249            if desc.id.is_null() {
1250                continue;
1251            }
1252            // SAFETY: descriptor id is NUL-terminated per CLAP ABI.
1253            let id = unsafe { CStr::from_ptr(desc.id) };
1254            let id_str = id.to_string_lossy();
1255            if plugin_id.is_none() || plugin_id == Some(id_str.as_ref()) {
1256                selected_id = Some(
1257                    CString::new(id_str.as_ref()).map_err(|e| format!("Invalid plugin id: {e}"))?,
1258                );
1259                break;
1260            }
1261        }
1262        let selected_id = selected_id.ok_or_else(|| {
1263            if let Some(id) = plugin_id {
1264                format!("CLAP descriptor id not found in bundle: {id}")
1265            } else {
1266                "CLAP descriptor not found".to_string()
1267            }
1268        })?;
1269        // SAFETY: valid host pointer and plugin id.
1270        let plugin = unsafe { create(factory, &host_runtime.host, selected_id.as_ptr()) };
1271        if plugin.is_null() {
1272            return Err("CLAP factory create_plugin failed".to_string());
1273        }
1274        // SAFETY: plugin pointer validated above.
1275        let plugin_ref = unsafe { &*plugin };
1276        let plugin_init = plugin_ref
1277            .init
1278            .ok_or_else(|| "CLAP plugin missing init()".to_string())?;
1279        // SAFETY: plugin pointer and function pointer follow CLAP ABI.
1280        if unsafe { !plugin_init(plugin) } {
1281            return Err("CLAP plugin init() failed".to_string());
1282        }
1283        if let Some(activate) = plugin_ref.activate {
1284            // SAFETY: plugin pointer and arguments are valid for current engine buffer config.
1285            if unsafe { !activate(plugin, sample_rate, frames.max(1), frames.max(1)) } {
1286                return Err("CLAP plugin activate() failed".to_string());
1287            }
1288        }
1289        if let Some(start_processing) = plugin_ref.start_processing {
1290            // SAFETY: plugin activated above.
1291            if unsafe { !start_processing(plugin) } {
1292                return Err("CLAP plugin start_processing() failed".to_string());
1293            }
1294        }
1295        Ok(Self {
1296            _library: library,
1297            entry: entry_ptr,
1298            plugin,
1299        })
1300    }
1301
1302    fn process(&self, process: &mut ClapProcess) -> Result<bool, String> {
1303        // SAFETY: plugin pointer is valid for lifetime of self.
1304        let plugin = unsafe { &*self.plugin };
1305        let Some(process_fn) = plugin.process else {
1306            return Ok(false);
1307        };
1308        // SAFETY: process struct references live buffers for the duration of call.
1309        let _status = unsafe { process_fn(self.plugin, process as *const _) };
1310        Ok(true)
1311    }
1312
1313    fn reset(&self) {
1314        // SAFETY: plugin pointer valid during self lifetime.
1315        let plugin = unsafe { &*self.plugin };
1316        if let Some(reset) = plugin.reset {
1317            // SAFETY: function pointer follows CLAP ABI.
1318            unsafe { reset(self.plugin) };
1319        }
1320    }
1321
1322    fn on_main_thread(&self) {
1323        // SAFETY: plugin pointer valid during self lifetime.
1324        let plugin = unsafe { &*self.plugin };
1325        if let Some(on_main_thread) = plugin.on_main_thread {
1326            // SAFETY: function pointer follows CLAP ABI.
1327            unsafe { on_main_thread(self.plugin) };
1328        }
1329    }
1330
1331    fn params_ext(&self) -> Option<&ClapPluginParams> {
1332        let ext_id = c"clap.params";
1333        // SAFETY: plugin pointer is valid while self is alive.
1334        let plugin = unsafe { &*self.plugin };
1335        let get_extension = plugin.get_extension?;
1336        // SAFETY: extension id is a valid static C string.
1337        let ext_ptr = unsafe { get_extension(self.plugin, ext_id.as_ptr()) };
1338        if ext_ptr.is_null() {
1339            return None;
1340        }
1341        // SAFETY: CLAP guarantees extension pointer layout for requested extension id.
1342        Some(unsafe { &*(ext_ptr as *const ClapPluginParams) })
1343    }
1344
1345    fn state_ext(&self) -> Option<&ClapPluginStateExt> {
1346        let ext_id = c"clap.state";
1347        // SAFETY: plugin pointer is valid while self is alive.
1348        let plugin = unsafe { &*self.plugin };
1349        let get_extension = plugin.get_extension?;
1350        // SAFETY: extension id is valid static C string.
1351        let ext_ptr = unsafe { get_extension(self.plugin, ext_id.as_ptr()) };
1352        if ext_ptr.is_null() {
1353            return None;
1354        }
1355        // SAFETY: extension pointer layout follows clap.state ABI.
1356        Some(unsafe { &*(ext_ptr as *const ClapPluginStateExt) })
1357    }
1358
1359    fn audio_ports_ext(&self) -> Option<&ClapPluginAudioPorts> {
1360        let ext_id = c"clap.audio-ports";
1361        // SAFETY: plugin pointer is valid while self is alive.
1362        let plugin = unsafe { &*self.plugin };
1363        let get_extension = plugin.get_extension?;
1364        // SAFETY: extension id is valid static C string.
1365        let ext_ptr = unsafe { get_extension(self.plugin, ext_id.as_ptr()) };
1366        if ext_ptr.is_null() {
1367            return None;
1368        }
1369        // SAFETY: extension pointer layout follows clap.audio-ports ABI.
1370        Some(unsafe { &*(ext_ptr as *const ClapPluginAudioPorts) })
1371    }
1372
1373    fn note_ports_ext(&self) -> Option<&ClapPluginNotePorts> {
1374        let ext_id = c"clap.note-ports";
1375        // SAFETY: plugin pointer is valid while self is alive.
1376        let plugin = unsafe { &*self.plugin };
1377        let get_extension = plugin.get_extension?;
1378        // SAFETY: extension id is valid static C string.
1379        let ext_ptr = unsafe { get_extension(self.plugin, ext_id.as_ptr()) };
1380        if ext_ptr.is_null() {
1381            return None;
1382        }
1383        // SAFETY: extension pointer layout follows clap.note-ports ABI.
1384        Some(unsafe { &*(ext_ptr as *const ClapPluginNotePorts) })
1385    }
1386
1387    fn parameter_infos(&self) -> Vec<ClapParameterInfo> {
1388        let Some(params) = self.params_ext() else {
1389            return Vec::new();
1390        };
1391        let Some(count_fn) = params.count else {
1392            return Vec::new();
1393        };
1394        let Some(get_info_fn) = params.get_info else {
1395            return Vec::new();
1396        };
1397        // SAFETY: function pointers come from plugin extension table.
1398        let count = unsafe { count_fn(self.plugin) };
1399        let mut out = Vec::with_capacity(count as usize);
1400        for idx in 0..count {
1401            let mut info = ClapParamInfoRaw {
1402                id: 0,
1403                flags: 0,
1404                cookie: std::ptr::null_mut(),
1405                name: [0; 256],
1406                module: [0; 1024],
1407                min_value: 0.0,
1408                max_value: 1.0,
1409                default_value: 0.0,
1410            };
1411            // SAFETY: info points to valid writable struct.
1412            if unsafe { !get_info_fn(self.plugin, idx, &mut info as *mut _) } {
1413                continue;
1414            }
1415            out.push(ClapParameterInfo {
1416                id: info.id,
1417                name: c_char_buf_to_string(&info.name),
1418                module: c_char_buf_to_string(&info.module),
1419                min_value: info.min_value,
1420                max_value: info.max_value,
1421                default_value: info.default_value,
1422            });
1423        }
1424        out
1425    }
1426
1427    fn parameter_values(&self, infos: &[ClapParameterInfo]) -> HashMap<u32, f64> {
1428        let mut out = HashMap::new();
1429        let Some(params) = self.params_ext() else {
1430            for info in infos {
1431                out.insert(info.id, info.default_value);
1432            }
1433            return out;
1434        };
1435        let Some(get_value_fn) = params.get_value else {
1436            for info in infos {
1437                out.insert(info.id, info.default_value);
1438            }
1439            return out;
1440        };
1441        for info in infos {
1442            let mut value = info.default_value;
1443            // SAFETY: pointer to stack `value` is valid and param id belongs to plugin metadata.
1444            if unsafe { !get_value_fn(self.plugin, info.id, &mut value as *mut _) } {
1445                value = info.default_value;
1446            }
1447            out.insert(info.id, value);
1448        }
1449        out
1450    }
1451
1452    fn flush_params(&self, param_events: &[PendingParamEvent]) -> Vec<PendingParamValue> {
1453        let Some(params) = self.params_ext() else {
1454            return Vec::new();
1455        };
1456        let Some(flush_fn) = params.flush else {
1457            return Vec::new();
1458        };
1459        let (in_events, _in_ctx) = param_input_events_from(param_events);
1460        let out_cap = param_events.len().max(32);
1461        let (out_events, mut out_ctx) = output_events_ctx(out_cap);
1462        // SAFETY: input/output event wrappers stay valid for duration of flush callback.
1463        unsafe {
1464            flush_fn(self.plugin, &in_events, &out_events);
1465        }
1466        std::mem::take(&mut out_ctx.param_values)
1467    }
1468
1469    fn snapshot_state(&self) -> Result<ClapPluginState, String> {
1470        let Some(state_ext) = self.state_ext() else {
1471            return Ok(ClapPluginState { bytes: Vec::new() });
1472        };
1473        let Some(save_fn) = state_ext.save else {
1474            return Ok(ClapPluginState { bytes: Vec::new() });
1475        };
1476        let mut bytes = Vec::<u8>::new();
1477        let mut stream = ClapOStream {
1478            ctx: (&mut bytes as *mut Vec<u8>).cast::<c_void>(),
1479            write: Some(clap_ostream_write),
1480        };
1481        // SAFETY: stream callbacks reference `bytes` for duration of call.
1482        if unsafe {
1483            !save_fn(
1484                self.plugin,
1485                &mut stream as *mut ClapOStream as *const ClapOStream,
1486            )
1487        } {
1488            return Err("CLAP state save failed".to_string());
1489        }
1490        Ok(ClapPluginState { bytes })
1491    }
1492
1493    fn restore_state(&self, state: &ClapPluginState) -> Result<(), String> {
1494        let Some(state_ext) = self.state_ext() else {
1495            return Ok(());
1496        };
1497        let Some(load_fn) = state_ext.load else {
1498            return Ok(());
1499        };
1500        let mut ctx = ClapIStreamCtx {
1501            bytes: &state.bytes,
1502            offset: 0,
1503        };
1504        let mut stream = ClapIStream {
1505            ctx: (&mut ctx as *mut ClapIStreamCtx).cast::<c_void>(),
1506            read: Some(clap_istream_read),
1507        };
1508        // SAFETY: stream callbacks reference `ctx` for duration of call.
1509        if unsafe {
1510            !load_fn(
1511                self.plugin,
1512                &mut stream as *mut ClapIStream as *const ClapIStream,
1513            )
1514        } {
1515            return Err("CLAP state load failed".to_string());
1516        }
1517        Ok(())
1518    }
1519
1520    fn audio_port_channels(&self) -> (Vec<usize>, Vec<usize>) {
1521        let Some(ext) = self.audio_ports_ext() else {
1522            return (Vec::new(), Vec::new());
1523        };
1524        let Some(count_fn) = ext.count else {
1525            return (Vec::new(), Vec::new());
1526        };
1527        let Some(get_fn) = ext.get else {
1528            return (Vec::new(), Vec::new());
1529        };
1530
1531        let read_channels = |is_input: bool| -> Vec<usize> {
1532            let mut out = Vec::new();
1533            let count = unsafe { count_fn(self.plugin, is_input) } as usize;
1534            out.reserve(count);
1535            for idx in 0..count {
1536                let mut info = ClapAudioPortInfoRaw {
1537                    id: 0,
1538                    name: [0; 256],
1539                    flags: 0,
1540                    channel_count: 1,
1541                    port_type: std::ptr::null(),
1542                    in_place_pair: u32::MAX,
1543                };
1544                if unsafe { get_fn(self.plugin, idx as u32, is_input, &mut info as *mut _) } {
1545                    out.push((info.channel_count as usize).max(1));
1546                }
1547            }
1548            out
1549        };
1550        (read_channels(true), read_channels(false))
1551    }
1552
1553    fn note_port_layout(&self) -> (Option<usize>, Option<usize>) {
1554        let Some(ext) = self.note_ports_ext() else {
1555            return (None, None);
1556        };
1557        let Some(count_fn) = ext.count else {
1558            return (None, None);
1559        };
1560        // SAFETY: function pointer comes from plugin extension table.
1561        let in_count = unsafe { count_fn(self.plugin, true) } as usize;
1562        // SAFETY: function pointer comes from plugin extension table.
1563        let out_count = unsafe { count_fn(self.plugin, false) } as usize;
1564        (Some(in_count.max(1)), Some(out_count.max(1)))
1565    }
1566
1567    fn gui_ext(&self) -> Option<&ClapPluginGui> {
1568        let ext_id = c"clap.gui";
1569        let plugin = unsafe { &*self.plugin };
1570        let get_extension = plugin.get_extension?;
1571        let ext_ptr = unsafe { get_extension(self.plugin, ext_id.as_ptr()) };
1572        if ext_ptr.is_null() {
1573            return None;
1574        }
1575        Some(unsafe { &*(ext_ptr as *const ClapPluginGui) })
1576    }
1577
1578    fn gui_timer_support_ext(&self) -> Option<&ClapPluginTimerSupport> {
1579        let ext_id = c"clap.timer-support";
1580        let plugin = unsafe { &*self.plugin };
1581        let get_extension = plugin.get_extension?;
1582        let ext_ptr = unsafe { get_extension(self.plugin, ext_id.as_ptr()) };
1583        if ext_ptr.is_null() {
1584            return None;
1585        }
1586        Some(unsafe { &*(ext_ptr as *const ClapPluginTimerSupport) })
1587    }
1588
1589    fn gui_info(&self) -> Result<ClapGuiInfo, String> {
1590        let gui = self
1591            .gui_ext()
1592            .ok_or_else(|| "CLAP plugin does not expose clap.gui".to_string())?;
1593        let is_api_supported = gui
1594            .is_api_supported
1595            .ok_or_else(|| "CLAP gui.is_api_supported is unavailable".to_string())?;
1596        for (api, supports_embedded) in [
1597            ("x11", true),
1598            ("cocoa", true),
1599            ("x11", false),
1600            ("cocoa", false),
1601        ] {
1602            let api_c = CString::new(api).map_err(|e| e.to_string())?;
1603            if unsafe { is_api_supported(self.plugin, api_c.as_ptr(), !supports_embedded) } {
1604                return Ok(ClapGuiInfo {
1605                    api: api.to_string(),
1606                    supports_embedded,
1607                });
1608            }
1609        }
1610        Err("No supported CLAP GUI API found".to_string())
1611    }
1612
1613    fn gui_create(&self, api: &str, is_floating: bool) -> Result<(), String> {
1614        let gui = self
1615            .gui_ext()
1616            .ok_or_else(|| "CLAP plugin does not expose clap.gui".to_string())?;
1617        let create = gui
1618            .create
1619            .ok_or_else(|| "CLAP gui.create is unavailable".to_string())?;
1620        let api_c = CString::new(api).map_err(|e| e.to_string())?;
1621        if unsafe { !create(self.plugin, api_c.as_ptr(), is_floating) } {
1622            return Err("CLAP gui.create failed".to_string());
1623        }
1624        Ok(())
1625    }
1626
1627    fn gui_get_size(&self) -> Result<(u32, u32), String> {
1628        let gui = self
1629            .gui_ext()
1630            .ok_or_else(|| "CLAP plugin does not expose clap.gui".to_string())?;
1631        let get_size = gui
1632            .get_size
1633            .ok_or_else(|| "CLAP gui.get_size is unavailable".to_string())?;
1634        let mut width = 0;
1635        let mut height = 0;
1636        if unsafe { !get_size(self.plugin, &mut width, &mut height) } {
1637            return Err("CLAP gui.get_size failed".to_string());
1638        }
1639        Ok((width, height))
1640    }
1641
1642    fn gui_set_parent_x11(&self, window: usize) -> Result<(), String> {
1643        let gui = self
1644            .gui_ext()
1645            .ok_or_else(|| "CLAP plugin does not expose clap.gui".to_string())?;
1646        let set_parent = gui
1647            .set_parent
1648            .ok_or_else(|| "CLAP gui.set_parent is unavailable".to_string())?;
1649        let clap_window = ClapWindow {
1650            api: c"x11".as_ptr(),
1651            handle: ClapWindowHandle { x11: window },
1652        };
1653        if unsafe { !set_parent(self.plugin, &clap_window) } {
1654            return Err("CLAP gui.set_parent failed".to_string());
1655        }
1656        Ok(())
1657    }
1658
1659    fn gui_show(&self) -> Result<(), String> {
1660        let gui = self
1661            .gui_ext()
1662            .ok_or_else(|| "CLAP plugin does not expose clap.gui".to_string())?;
1663        let show = gui
1664            .show
1665            .ok_or_else(|| "CLAP gui.show is unavailable".to_string())?;
1666        if unsafe { !show(self.plugin) } {
1667            return Err("CLAP gui.show failed".to_string());
1668        }
1669        Ok(())
1670    }
1671
1672    fn gui_hide(&self) {
1673        if let Some(gui) = self.gui_ext()
1674            && let Some(hide) = gui.hide
1675        {
1676            unsafe { hide(self.plugin) };
1677        }
1678    }
1679
1680    fn gui_destroy(&self) {
1681        if let Some(gui) = self.gui_ext()
1682            && let Some(destroy) = gui.destroy
1683        {
1684            unsafe { destroy(self.plugin) };
1685        }
1686    }
1687
1688    fn gui_on_timer(&self, timer_id: u32) {
1689        if let Some(timer_ext) = self.gui_timer_support_ext()
1690            && let Some(on_timer) = timer_ext.on_timer
1691        {
1692            unsafe { on_timer(self.plugin, timer_id) };
1693        }
1694    }
1695}
1696
1697impl Drop for PluginHandle {
1698    fn drop(&mut self) {
1699        // SAFETY: pointers were obtained from valid CLAP entry and plugin factory.
1700        unsafe {
1701            if !self.plugin.is_null() {
1702                let plugin = &*self.plugin;
1703                if let Some(stop_processing) = plugin.stop_processing {
1704                    stop_processing(self.plugin);
1705                }
1706                if let Some(deactivate) = plugin.deactivate {
1707                    deactivate(self.plugin);
1708                }
1709                if let Some(destroy) = plugin.destroy {
1710                    destroy(self.plugin);
1711                }
1712            }
1713            if !self.entry.is_null() {
1714                let entry = &*self.entry;
1715                if let Some(deinit) = entry.deinit {
1716                    deinit();
1717                }
1718            }
1719        }
1720    }
1721}
1722
1723static HOST_THREAD_CHECK_EXT: ClapHostThreadCheck = ClapHostThreadCheck {
1724    is_main_thread: Some(host_is_main_thread),
1725    is_audio_thread: Some(host_is_audio_thread),
1726};
1727static HOST_LATENCY_EXT: ClapHostLatency = ClapHostLatency {
1728    changed: Some(host_latency_changed),
1729};
1730static HOST_TAIL_EXT: ClapHostTail = ClapHostTail {
1731    changed: Some(host_tail_changed),
1732};
1733static HOST_TIMER_EXT: ClapHostTimerSupport = ClapHostTimerSupport {
1734    register_timer: Some(host_timer_register),
1735    unregister_timer: Some(host_timer_unregister),
1736};
1737static HOST_GUI_EXT: ClapHostGui = ClapHostGui {
1738    resize_hints_changed: Some(host_gui_resize_hints_changed),
1739    request_resize: Some(host_gui_request_resize),
1740    request_show: Some(host_gui_request_show),
1741    request_hide: Some(host_gui_request_hide),
1742    closed: Some(host_gui_closed),
1743};
1744static HOST_PARAMS_EXT: ClapHostParams = ClapHostParams {
1745    rescan: Some(host_params_rescan),
1746    clear: Some(host_params_clear),
1747    request_flush: Some(host_params_request_flush),
1748};
1749static HOST_STATE_EXT: ClapHostState = ClapHostState {
1750    mark_dirty: Some(host_state_mark_dirty),
1751};
1752static NEXT_TIMER_ID: AtomicU32 = AtomicU32::new(1);
1753
1754fn host_runtime_state(host: *const ClapHost) -> Option<&'static HostRuntimeState> {
1755    if host.is_null() {
1756        return None;
1757    }
1758    let state_ptr = unsafe { (*host).host_data as *const HostRuntimeState };
1759    if state_ptr.is_null() {
1760        return None;
1761    }
1762    Some(unsafe { &*state_ptr })
1763}
1764
1765unsafe extern "C" fn host_get_extension(
1766    _host: *const ClapHost,
1767    _extension_id: *const c_char,
1768) -> *const c_void {
1769    if _extension_id.is_null() {
1770        return std::ptr::null();
1771    }
1772    // SAFETY: extension id is expected to be a valid NUL-terminated string.
1773    let id = unsafe { CStr::from_ptr(_extension_id) }.to_string_lossy();
1774    match id.as_ref() {
1775        "clap.host.thread-check" => {
1776            (&HOST_THREAD_CHECK_EXT as *const ClapHostThreadCheck).cast::<c_void>()
1777        }
1778        "clap.host.latency" => (&HOST_LATENCY_EXT as *const ClapHostLatency).cast::<c_void>(),
1779        "clap.host.tail" => (&HOST_TAIL_EXT as *const ClapHostTail).cast::<c_void>(),
1780        "clap.host.timer-support" => {
1781            (&HOST_TIMER_EXT as *const ClapHostTimerSupport).cast::<c_void>()
1782        }
1783        "clap.host.gui" => host_runtime_state(_host)
1784            .filter(|state| state.ui_active.load(Ordering::Acquire) != 0)
1785            .map(|_| (&HOST_GUI_EXT as *const ClapHostGui).cast::<c_void>())
1786            .unwrap_or(std::ptr::null()),
1787        "clap.host.params" => host_runtime_state(_host)
1788            .filter(|state| state.ui_active.load(Ordering::Acquire) != 0)
1789            .map(|_| (&HOST_PARAMS_EXT as *const ClapHostParams).cast::<c_void>())
1790            .unwrap_or(std::ptr::null()),
1791        "clap.host.state" => host_runtime_state(_host)
1792            .filter(|state| state.ui_active.load(Ordering::Acquire) != 0)
1793            .map(|_| (&HOST_STATE_EXT as *const ClapHostState).cast::<c_void>())
1794            .unwrap_or(std::ptr::null()),
1795        _ => std::ptr::null(),
1796    }
1797}
1798
1799unsafe extern "C" fn host_request_process(_host: *const ClapHost) {
1800    if let Some(state) = host_runtime_state(_host) {
1801        state.callback_flags.lock().process = true;
1802    }
1803}
1804
1805unsafe extern "C" fn host_request_callback(_host: *const ClapHost) {
1806    if let Some(state) = host_runtime_state(_host) {
1807        state.callback_flags.lock().callback = true;
1808    }
1809}
1810
1811unsafe extern "C" fn host_request_restart(_host: *const ClapHost) {
1812    if let Some(state) = host_runtime_state(_host) {
1813        state.callback_flags.lock().restart = true;
1814    }
1815}
1816
1817unsafe extern "C" fn host_is_main_thread(_host: *const ClapHost) -> bool {
1818    CLAP_HOST_MAIN_THREAD.with(Cell::get)
1819}
1820
1821unsafe extern "C" fn host_is_audio_thread(_host: *const ClapHost) -> bool {
1822    CLAP_HOST_AUDIO_THREAD.with(Cell::get)
1823}
1824
1825unsafe extern "C" fn host_latency_changed(_host: *const ClapHost) {}
1826
1827unsafe extern "C" fn host_tail_changed(_host: *const ClapHost) {}
1828
1829unsafe extern "C" fn host_timer_register(
1830    _host: *const ClapHost,
1831    _period_ms: u32,
1832    timer_id: *mut u32,
1833) -> bool {
1834    if timer_id.is_null() {
1835        return false;
1836    }
1837    let id = NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed);
1838    if let Some(state) = host_runtime_state(_host) {
1839        let period_ms = _period_ms.max(1);
1840        state.timers.lock().push(HostTimer {
1841            id,
1842            period: Duration::from_millis(period_ms as u64),
1843            next_tick: Instant::now() + Duration::from_millis(period_ms as u64),
1844        });
1845    }
1846    // SAFETY: timer_id points to writable u32 provided by plugin.
1847    unsafe {
1848        *timer_id = id;
1849    }
1850    true
1851}
1852
1853unsafe extern "C" fn host_timer_unregister(_host: *const ClapHost, _timer_id: u32) -> bool {
1854    if let Some(state) = host_runtime_state(_host) {
1855        state.timers.lock().retain(|timer| timer.id != _timer_id);
1856    }
1857    true
1858}
1859
1860unsafe extern "C" fn host_gui_resize_hints_changed(_host: *const ClapHost) {}
1861
1862unsafe extern "C" fn host_gui_request_resize(
1863    _host: *const ClapHost,
1864    _width: u32,
1865    _height: u32,
1866) -> bool {
1867    true
1868}
1869
1870unsafe extern "C" fn host_gui_request_show(_host: *const ClapHost) -> bool {
1871    true
1872}
1873
1874unsafe extern "C" fn host_gui_request_hide(_host: *const ClapHost) -> bool {
1875    if let Some(state) = host_runtime_state(_host) {
1876        if state.ui_active.load(Ordering::Acquire) != 0 {
1877            state.ui_should_close.store(1, Ordering::Release);
1878        }
1879        true
1880    } else {
1881        false
1882    }
1883}
1884
1885unsafe extern "C" fn host_gui_closed(_host: *const ClapHost, _was_destroyed: bool) {
1886    if let Some(state) = host_runtime_state(_host)
1887        && state.ui_active.load(Ordering::Acquire) != 0
1888    {
1889        state.ui_should_close.store(1, Ordering::Release);
1890    }
1891}
1892
1893unsafe extern "C" fn host_params_rescan(_host: *const ClapHost, _flags: u32) {}
1894
1895unsafe extern "C" fn host_params_clear(_host: *const ClapHost, _param_id: u32, _flags: u32) {}
1896
1897unsafe extern "C" fn host_params_request_flush(_host: *const ClapHost) {
1898    if let Some(state) = host_runtime_state(_host) {
1899        state.param_flush_requested.store(1, Ordering::Release);
1900        state.callback_flags.lock().callback = true;
1901    }
1902}
1903
1904unsafe extern "C" fn host_state_mark_dirty(_host: *const ClapHost) {
1905    if let Some(state) = host_runtime_state(_host) {
1906        state.state_dirty_requested.store(1, Ordering::Release);
1907        state.callback_flags.lock().callback = true;
1908    }
1909}
1910
1911unsafe extern "C" fn input_events_size(_list: *const ClapInputEvents) -> u32 {
1912    if _list.is_null() {
1913        return 0;
1914    }
1915    // SAFETY: ctx points to ClapInputEventsCtx owned by process_native.
1916    let ctx = unsafe { (*_list).ctx as *const ClapInputEventsCtx };
1917    if ctx.is_null() {
1918        return 0;
1919    }
1920    // SAFETY: ctx is valid during process callback lifetime.
1921    unsafe { (*ctx).events.len() as u32 }
1922}
1923
1924unsafe extern "C" fn input_events_get(
1925    _list: *const ClapInputEvents,
1926    _index: u32,
1927) -> *const ClapEventHeader {
1928    if _list.is_null() {
1929        return std::ptr::null();
1930    }
1931    // SAFETY: ctx points to ClapInputEventsCtx owned by process_native.
1932    let ctx = unsafe { (*_list).ctx as *const ClapInputEventsCtx };
1933    if ctx.is_null() {
1934        return std::ptr::null();
1935    }
1936    // SAFETY: ctx is valid during process callback lifetime.
1937    let events = unsafe { &(*ctx).events };
1938    let Some(event) = events.get(_index as usize) else {
1939        return std::ptr::null();
1940    };
1941    event.header_ptr()
1942}
1943
1944unsafe extern "C" fn output_events_try_push(
1945    _list: *const ClapOutputEvents,
1946    _event: *const ClapEventHeader,
1947) -> bool {
1948    if _list.is_null() || _event.is_null() {
1949        return false;
1950    }
1951    // SAFETY: ctx points to ClapOutputEventsCtx owned by process_native.
1952    let ctx = unsafe { (*_list).ctx as *mut ClapOutputEventsCtx };
1953    if ctx.is_null() {
1954        return false;
1955    }
1956    // SAFETY: event pointer is valid for callback lifetime.
1957    let header = unsafe { &*_event };
1958    if header.space_id != CLAP_CORE_EVENT_SPACE_ID {
1959        return false;
1960    }
1961    match header.type_ {
1962        CLAP_EVENT_MIDI => {
1963            if (header.size as usize) < std::mem::size_of::<ClapEventMidi>() {
1964                return false;
1965            }
1966            // SAFETY: validated type/size above.
1967            let midi = unsafe { &*(_event as *const ClapEventMidi) };
1968            // SAFETY: ctx pointer is valid and uniquely owned during processing.
1969            unsafe {
1970                (*ctx).midi_events.push(ClapMidiOutputEvent {
1971                    port: midi.port_index as usize,
1972                    event: MidiEvent::new(header.time, midi.data.to_vec()),
1973                });
1974            }
1975            true
1976        }
1977        CLAP_EVENT_PARAM_VALUE => {
1978            if (header.size as usize) < std::mem::size_of::<ClapEventParamValue>() {
1979                return false;
1980            }
1981            // SAFETY: validated type/size above.
1982            let param = unsafe { &*(_event as *const ClapEventParamValue) };
1983            // SAFETY: ctx pointer is valid and uniquely owned during processing.
1984            unsafe {
1985                (*ctx).param_values.push(PendingParamValue {
1986                    param_id: param.param_id,
1987                    value: param.value,
1988                });
1989            }
1990            true
1991        }
1992        _ => false,
1993    }
1994}
1995
1996fn input_events_from(
1997    midi_events: &[MidiEvent],
1998    param_events: &[PendingParamEvent],
1999    sample_rate: f64,
2000    transport: ClapTransportInfo,
2001) -> (ClapInputEvents, Box<ClapInputEventsCtx>) {
2002    let mut events = Vec::with_capacity(midi_events.len() + param_events.len() + 1);
2003    let bpm = transport.bpm.max(1.0);
2004    let sample_rate = sample_rate.max(1.0);
2005    let seconds = transport.transport_sample as f64 / sample_rate;
2006    let song_pos_seconds = (seconds * CLAP_SECTIME_FACTOR as f64) as i64;
2007    let beats = seconds * (bpm / 60.0);
2008    let song_pos_beats = (beats * CLAP_BEATTIME_FACTOR as f64) as i64;
2009    let mut flags = CLAP_TRANSPORT_HAS_TEMPO
2010        | CLAP_TRANSPORT_HAS_BEATS_TIMELINE
2011        | CLAP_TRANSPORT_HAS_SECONDS_TIMELINE
2012        | CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
2013    if transport.playing {
2014        flags |= CLAP_TRANSPORT_IS_PLAYING;
2015    }
2016    let (loop_start_seconds, loop_end_seconds, loop_start_beats, loop_end_beats) =
2017        if transport.loop_enabled {
2018            if let Some((loop_start, loop_end)) = transport.loop_range_samples {
2019                flags |= CLAP_TRANSPORT_IS_LOOP_ACTIVE;
2020                let ls_sec = loop_start as f64 / sample_rate;
2021                let le_sec = loop_end as f64 / sample_rate;
2022                let ls_beats = ls_sec * (bpm / 60.0);
2023                let le_beats = le_sec * (bpm / 60.0);
2024                (
2025                    (ls_sec * CLAP_SECTIME_FACTOR as f64) as i64,
2026                    (le_sec * CLAP_SECTIME_FACTOR as f64) as i64,
2027                    (ls_beats * CLAP_BEATTIME_FACTOR as f64) as i64,
2028                    (le_beats * CLAP_BEATTIME_FACTOR as f64) as i64,
2029                )
2030            } else {
2031                (0, 0, 0, 0)
2032            }
2033        } else {
2034            (0, 0, 0, 0)
2035        };
2036    let ts_num = transport.tsig_num.max(1);
2037    let ts_denom = transport.tsig_denom.max(1);
2038    let beats_per_bar = ts_num as f64 * (4.0 / ts_denom as f64);
2039    let bar_number = if beats_per_bar > 0.0 {
2040        (beats / beats_per_bar).floor().max(0.0) as i32
2041    } else {
2042        0
2043    };
2044    let bar_start_beats = (bar_number as f64 * beats_per_bar * CLAP_BEATTIME_FACTOR as f64) as i64;
2045    events.push(ClapInputEvent::Transport(ClapEventTransport {
2046        header: ClapEventHeader {
2047            size: std::mem::size_of::<ClapEventTransport>() as u32,
2048            time: 0,
2049            space_id: CLAP_CORE_EVENT_SPACE_ID,
2050            type_: CLAP_EVENT_TRANSPORT,
2051            flags: 0,
2052        },
2053        flags,
2054        song_pos_beats,
2055        song_pos_seconds,
2056        tempo: bpm,
2057        tempo_inc: 0.0,
2058        loop_start_beats,
2059        loop_end_beats,
2060        loop_start_seconds,
2061        loop_end_seconds,
2062        bar_start: bar_start_beats,
2063        bar_number,
2064        tsig_num: ts_num,
2065        tsig_denom: ts_denom,
2066    }));
2067    for event in midi_events {
2068        if event.data.is_empty() {
2069            continue;
2070        }
2071        let mut data = [0_u8; 3];
2072        let bytes = event.data.len().min(3);
2073        data[..bytes].copy_from_slice(&event.data[..bytes]);
2074        events.push(ClapInputEvent::Midi(ClapEventMidi {
2075            header: ClapEventHeader {
2076                size: std::mem::size_of::<ClapEventMidi>() as u32,
2077                time: event.frame,
2078                space_id: CLAP_CORE_EVENT_SPACE_ID,
2079                type_: CLAP_EVENT_MIDI,
2080                flags: 0,
2081            },
2082            port_index: 0,
2083            data,
2084        }));
2085    }
2086    for param in param_events {
2087        match *param {
2088            PendingParamEvent::Value {
2089                param_id,
2090                value,
2091                frame,
2092            } => events.push(ClapInputEvent::ParamValue(ClapEventParamValue {
2093                header: ClapEventHeader {
2094                    size: std::mem::size_of::<ClapEventParamValue>() as u32,
2095                    time: frame,
2096                    space_id: CLAP_CORE_EVENT_SPACE_ID,
2097                    type_: CLAP_EVENT_PARAM_VALUE,
2098                    flags: 0,
2099                },
2100                param_id,
2101                cookie: std::ptr::null_mut(),
2102                note_id: -1,
2103                port_index: -1,
2104                channel: -1,
2105                key: -1,
2106                value,
2107            })),
2108            PendingParamEvent::GestureBegin { param_id, frame } => {
2109                events.push(ClapInputEvent::ParamGesture(ClapEventParamGesture {
2110                    header: ClapEventHeader {
2111                        size: std::mem::size_of::<ClapEventParamGesture>() as u32,
2112                        time: frame,
2113                        space_id: CLAP_CORE_EVENT_SPACE_ID,
2114                        type_: CLAP_EVENT_PARAM_GESTURE_BEGIN,
2115                        flags: 0,
2116                    },
2117                    param_id,
2118                }))
2119            }
2120            PendingParamEvent::GestureEnd { param_id, frame } => {
2121                events.push(ClapInputEvent::ParamGesture(ClapEventParamGesture {
2122                    header: ClapEventHeader {
2123                        size: std::mem::size_of::<ClapEventParamGesture>() as u32,
2124                        time: frame,
2125                        space_id: CLAP_CORE_EVENT_SPACE_ID,
2126                        type_: CLAP_EVENT_PARAM_GESTURE_END,
2127                        flags: 0,
2128                    },
2129                    param_id,
2130                }))
2131            }
2132        }
2133    }
2134    events.sort_by_key(|event| match event {
2135        ClapInputEvent::Midi(e) => e.header.time,
2136        ClapInputEvent::ParamValue(e) => e.header.time,
2137        ClapInputEvent::ParamGesture(e) => e.header.time,
2138        ClapInputEvent::Transport(e) => e.header.time,
2139    });
2140    let mut ctx = Box::new(ClapInputEventsCtx { events });
2141    let list = ClapInputEvents {
2142        ctx: (&mut *ctx as *mut ClapInputEventsCtx).cast::<c_void>(),
2143        size: Some(input_events_size),
2144        get: Some(input_events_get),
2145    };
2146    (list, ctx)
2147}
2148
2149fn param_input_events_from(
2150    param_events: &[PendingParamEvent],
2151) -> (ClapInputEvents, Box<ClapInputEventsCtx>) {
2152    let mut events = Vec::with_capacity(param_events.len());
2153    for param in param_events {
2154        match *param {
2155            PendingParamEvent::Value {
2156                param_id,
2157                value,
2158                frame,
2159            } => events.push(ClapInputEvent::ParamValue(ClapEventParamValue {
2160                header: ClapEventHeader {
2161                    size: std::mem::size_of::<ClapEventParamValue>() as u32,
2162                    time: frame,
2163                    space_id: CLAP_CORE_EVENT_SPACE_ID,
2164                    type_: CLAP_EVENT_PARAM_VALUE,
2165                    flags: 0,
2166                },
2167                param_id,
2168                cookie: std::ptr::null_mut(),
2169                note_id: -1,
2170                port_index: -1,
2171                channel: -1,
2172                key: -1,
2173                value,
2174            })),
2175            PendingParamEvent::GestureBegin { param_id, frame } => {
2176                events.push(ClapInputEvent::ParamGesture(ClapEventParamGesture {
2177                    header: ClapEventHeader {
2178                        size: std::mem::size_of::<ClapEventParamGesture>() as u32,
2179                        time: frame,
2180                        space_id: CLAP_CORE_EVENT_SPACE_ID,
2181                        type_: CLAP_EVENT_PARAM_GESTURE_BEGIN,
2182                        flags: 0,
2183                    },
2184                    param_id,
2185                }))
2186            }
2187            PendingParamEvent::GestureEnd { param_id, frame } => {
2188                events.push(ClapInputEvent::ParamGesture(ClapEventParamGesture {
2189                    header: ClapEventHeader {
2190                        size: std::mem::size_of::<ClapEventParamGesture>() as u32,
2191                        time: frame,
2192                        space_id: CLAP_CORE_EVENT_SPACE_ID,
2193                        type_: CLAP_EVENT_PARAM_GESTURE_END,
2194                        flags: 0,
2195                    },
2196                    param_id,
2197                }))
2198            }
2199        }
2200    }
2201    events.sort_by_key(|event| match event {
2202        ClapInputEvent::Midi(e) => e.header.time,
2203        ClapInputEvent::ParamValue(e) => e.header.time,
2204        ClapInputEvent::ParamGesture(e) => e.header.time,
2205        ClapInputEvent::Transport(e) => e.header.time,
2206    });
2207    let mut ctx = Box::new(ClapInputEventsCtx { events });
2208    let list = ClapInputEvents {
2209        ctx: (&mut *ctx as *mut ClapInputEventsCtx).cast::<c_void>(),
2210        size: Some(input_events_size),
2211        get: Some(input_events_get),
2212    };
2213    (list, ctx)
2214}
2215
2216fn output_events_ctx(capacity: usize) -> (ClapOutputEvents, Box<ClapOutputEventsCtx>) {
2217    let mut ctx = Box::new(ClapOutputEventsCtx {
2218        midi_events: Vec::with_capacity(capacity),
2219        param_values: Vec::with_capacity(capacity / 2),
2220    });
2221    let list = ClapOutputEvents {
2222        ctx: (&mut *ctx as *mut ClapOutputEventsCtx).cast::<c_void>(),
2223        try_push: Some(output_events_try_push),
2224    };
2225    (list, ctx)
2226}
2227
2228fn c_char_buf_to_string<const N: usize>(buf: &[c_char; N]) -> String {
2229    let bytes = buf
2230        .iter()
2231        .take_while(|&&b| b != 0)
2232        .map(|&b| b as u8)
2233        .collect::<Vec<u8>>();
2234    String::from_utf8_lossy(&bytes).to_string()
2235}
2236
2237fn split_plugin_spec(spec: &str) -> (&str, Option<&str>) {
2238    if let Some((path, id)) = spec.split_once("::")
2239        && !id.trim().is_empty()
2240    {
2241        return (path, Some(id.trim()));
2242    }
2243    (spec, None)
2244}
2245
2246unsafe extern "C" fn clap_ostream_write(
2247    stream: *const ClapOStream,
2248    buffer: *const c_void,
2249    size: u64,
2250) -> i64 {
2251    if stream.is_null() || buffer.is_null() {
2252        return -1;
2253    }
2254    // SAFETY: ctx is initialized by snapshot_state and valid during callback.
2255    let ctx = unsafe { (*stream).ctx as *mut Vec<u8> };
2256    if ctx.is_null() {
2257        return -1;
2258    }
2259    let n = (size as usize).min(isize::MAX as usize);
2260    // SAFETY: source pointer is valid for `n` bytes per caller contract.
2261    let src = unsafe { std::slice::from_raw_parts(buffer.cast::<u8>(), n) };
2262    // SAFETY: ctx points to writable Vec<u8>.
2263    unsafe {
2264        (*ctx).extend_from_slice(src);
2265    }
2266    n as i64
2267}
2268
2269unsafe extern "C" fn clap_istream_read(
2270    stream: *const ClapIStream,
2271    buffer: *mut c_void,
2272    size: u64,
2273) -> i64 {
2274    if stream.is_null() || buffer.is_null() {
2275        return -1;
2276    }
2277    // SAFETY: ctx is initialized by restore_state and valid during callback.
2278    let ctx = unsafe { (*stream).ctx as *mut ClapIStreamCtx<'_> };
2279    if ctx.is_null() {
2280        return -1;
2281    }
2282    // SAFETY: ctx points to valid read context.
2283    let ctx = unsafe { &mut *ctx };
2284    let remaining = ctx.bytes.len().saturating_sub(ctx.offset);
2285    if remaining == 0 {
2286        return 0;
2287    }
2288    let n = remaining.min(size as usize);
2289    // SAFETY: destination pointer is valid for `n` bytes per caller contract.
2290    let dst = unsafe { std::slice::from_raw_parts_mut(buffer.cast::<u8>(), n) };
2291    dst.copy_from_slice(&ctx.bytes[ctx.offset..ctx.offset + n]);
2292    ctx.offset += n;
2293    n as i64
2294}
2295
2296pub fn list_plugins() -> Vec<ClapPluginInfo> {
2297    list_plugins_with_capabilities(false)
2298}
2299
2300pub fn list_plugins_with_capabilities(scan_capabilities: bool) -> Vec<ClapPluginInfo> {
2301    let mut roots = default_clap_search_roots();
2302
2303    if let Ok(extra) = std::env::var("CLAP_PATH") {
2304        for p in std::env::split_paths(&extra) {
2305            if !p.as_os_str().is_empty() {
2306                roots.push(p);
2307            }
2308        }
2309    }
2310
2311    let mut out = Vec::new();
2312    for root in roots {
2313        collect_clap_plugins(&root, &mut out, scan_capabilities);
2314    }
2315
2316    out.sort_by_key(|a| a.name.to_lowercase());
2317    out.dedup_by(|a, b| a.path.eq_ignore_ascii_case(&b.path));
2318    out
2319}
2320
2321fn collect_clap_plugins(root: &Path, out: &mut Vec<ClapPluginInfo>, scan_capabilities: bool) {
2322    let Ok(entries) = std::fs::read_dir(root) else {
2323        return;
2324    };
2325    for entry in entries.flatten() {
2326        let path = entry.path();
2327        let Ok(ft) = entry.file_type() else {
2328            continue;
2329        };
2330        if ft.is_dir() {
2331            collect_clap_plugins(&path, out, scan_capabilities);
2332            continue;
2333        }
2334
2335        if path
2336            .extension()
2337            .is_some_and(|ext| ext.eq_ignore_ascii_case("clap"))
2338        {
2339            let infos = scan_bundle_descriptors(&path, scan_capabilities);
2340            if infos.is_empty() {
2341                let name = path
2342                    .file_stem()
2343                    .map(|s| s.to_string_lossy().to_string())
2344                    .unwrap_or_else(|| path.to_string_lossy().to_string());
2345                out.push(ClapPluginInfo {
2346                    name,
2347                    path: path.to_string_lossy().to_string(),
2348                    capabilities: None,
2349                });
2350            } else {
2351                out.extend(infos);
2352            }
2353        }
2354    }
2355}
2356
2357fn scan_bundle_descriptors(path: &Path, scan_capabilities: bool) -> Vec<ClapPluginInfo> {
2358    let path_str = path.to_string_lossy().to_string();
2359    let factory_id = c"clap.plugin-factory";
2360    let host_runtime = match HostRuntime::new() {
2361        Ok(runtime) => runtime,
2362        Err(_) => return Vec::new(),
2363    };
2364    // SAFETY: path points to plugin module file.
2365    let library = match unsafe { Library::new(path) } {
2366        Ok(lib) => lib,
2367        Err(_) => return Vec::new(),
2368    };
2369    // SAFETY: symbol is CLAP entry pointer.
2370    let entry_ptr = unsafe {
2371        match library.get::<*const ClapPluginEntry>(b"clap_entry\0") {
2372            Ok(sym) => *sym,
2373            Err(_) => return Vec::new(),
2374        }
2375    };
2376    if entry_ptr.is_null() {
2377        return Vec::new();
2378    }
2379    // SAFETY: entry pointer validated above.
2380    let entry = unsafe { &*entry_ptr };
2381    let Some(init) = entry.init else {
2382        return Vec::new();
2383    };
2384    let host_ptr = &host_runtime.host;
2385    // SAFETY: valid host pointer.
2386    if unsafe { !init(host_ptr) } {
2387        return Vec::new();
2388    }
2389    let mut out = Vec::new();
2390    if let Some(get_factory) = entry.get_factory {
2391        // SAFETY: static factory id.
2392        let factory = unsafe { get_factory(factory_id.as_ptr()) } as *const ClapPluginFactory;
2393        if !factory.is_null() {
2394            // SAFETY: factory pointer validated above.
2395            let factory_ref = unsafe { &*factory };
2396            if let (Some(get_count), Some(get_desc)) = (
2397                factory_ref.get_plugin_count,
2398                factory_ref.get_plugin_descriptor,
2399            ) {
2400                // SAFETY: function pointer from plugin.
2401                let count = unsafe { get_count(factory) };
2402                for i in 0..count {
2403                    // SAFETY: i < count.
2404                    let desc = unsafe { get_desc(factory, i) };
2405                    if desc.is_null() {
2406                        continue;
2407                    }
2408                    // SAFETY: descriptor pointer from plugin factory.
2409                    let desc = unsafe { &*desc };
2410                    if desc.id.is_null() || desc.name.is_null() {
2411                        continue;
2412                    }
2413                    // SAFETY: CLAP descriptor strings are NUL-terminated.
2414                    let id = unsafe { CStr::from_ptr(desc.id) }
2415                        .to_string_lossy()
2416                        .to_string();
2417                    // SAFETY: CLAP descriptor strings are NUL-terminated.
2418                    let name = unsafe { CStr::from_ptr(desc.name) }
2419                        .to_string_lossy()
2420                        .to_string();
2421
2422                    let capabilities = if scan_capabilities {
2423                        scan_plugin_capabilities(factory_ref, factory, &host_runtime.host, &id)
2424                    } else {
2425                        None
2426                    };
2427
2428                    out.push(ClapPluginInfo {
2429                        name,
2430                        path: format!("{path_str}::{id}"),
2431                        capabilities,
2432                    });
2433                }
2434            }
2435        }
2436    }
2437    // SAFETY: deinit belongs to entry and is valid after init.
2438    if let Some(deinit) = entry.deinit {
2439        unsafe { deinit() };
2440    }
2441    out
2442}
2443
2444fn scan_plugin_capabilities(
2445    factory: &ClapPluginFactory,
2446    factory_ptr: *const ClapPluginFactory,
2447    host: &ClapHost,
2448    plugin_id: &str,
2449) -> Option<ClapPluginCapabilities> {
2450    let create = factory.create_plugin?;
2451
2452    let id_cstring = CString::new(plugin_id).ok()?;
2453    // SAFETY: valid factory, host, and id pointers.
2454    let plugin = unsafe { create(factory_ptr, host, id_cstring.as_ptr()) };
2455    if plugin.is_null() {
2456        return None;
2457    }
2458
2459    // SAFETY: plugin pointer validated above.
2460    let plugin_ref = unsafe { &*plugin };
2461    let plugin_init = plugin_ref.init?;
2462
2463    // SAFETY: plugin pointer and function pointer follow CLAP ABI.
2464    if unsafe { !plugin_init(plugin) } {
2465        return None;
2466    }
2467
2468    let mut capabilities = ClapPluginCapabilities {
2469        has_gui: false,
2470        gui_apis: Vec::new(),
2471        supports_embedded: false,
2472        supports_floating: false,
2473        has_params: false,
2474        has_state: false,
2475        has_audio_ports: false,
2476        has_note_ports: false,
2477    };
2478
2479    // Check for extensions
2480    if let Some(get_extension) = plugin_ref.get_extension {
2481        // Check GUI extension
2482        let gui_ext_id = c"clap.gui";
2483        // SAFETY: extension id is valid static C string.
2484        let gui_ptr = unsafe { get_extension(plugin, gui_ext_id.as_ptr()) };
2485        if !gui_ptr.is_null() {
2486            capabilities.has_gui = true;
2487            // SAFETY: CLAP guarantees extension pointer layout for requested extension id.
2488            let gui = unsafe { &*(gui_ptr as *const ClapPluginGui) };
2489
2490            // Check which GUI APIs are supported
2491            if let Some(is_api_supported) = gui.is_api_supported {
2492                for api in ["x11", "cocoa"] {
2493                    if let Ok(api_cstr) = CString::new(api) {
2494                        // Check embedded mode
2495                        // SAFETY: valid plugin and API string pointers.
2496                        if unsafe { is_api_supported(plugin, api_cstr.as_ptr(), false) } {
2497                            capabilities.gui_apis.push(format!("{} (embedded)", api));
2498                            capabilities.supports_embedded = true;
2499                        }
2500                        // Check floating mode
2501                        // SAFETY: valid plugin and API string pointers.
2502                        if unsafe { is_api_supported(plugin, api_cstr.as_ptr(), true) } {
2503                            if !capabilities.supports_embedded {
2504                                capabilities.gui_apis.push(format!("{} (floating)", api));
2505                            }
2506                            capabilities.supports_floating = true;
2507                        }
2508                    }
2509                }
2510            }
2511        }
2512
2513        // Check params extension
2514        let params_ext_id = c"clap.params";
2515        // SAFETY: extension id is valid static C string.
2516        let params_ptr = unsafe { get_extension(plugin, params_ext_id.as_ptr()) };
2517        capabilities.has_params = !params_ptr.is_null();
2518
2519        // Check state extension
2520        let state_ext_id = c"clap.state";
2521        // SAFETY: extension id is valid static C string.
2522        let state_ptr = unsafe { get_extension(plugin, state_ext_id.as_ptr()) };
2523        capabilities.has_state = !state_ptr.is_null();
2524
2525        // Check audio-ports extension
2526        let audio_ports_ext_id = c"clap.audio-ports";
2527        // SAFETY: extension id is valid static C string.
2528        let audio_ports_ptr = unsafe { get_extension(plugin, audio_ports_ext_id.as_ptr()) };
2529        capabilities.has_audio_ports = !audio_ports_ptr.is_null();
2530
2531        // Check note-ports extension
2532        let note_ports_ext_id = c"clap.note-ports";
2533        // SAFETY: extension id is valid static C string.
2534        let note_ports_ptr = unsafe { get_extension(plugin, note_ports_ext_id.as_ptr()) };
2535        capabilities.has_note_ports = !note_ports_ptr.is_null();
2536    }
2537
2538    // Clean up plugin instance
2539    if let Some(destroy) = plugin_ref.destroy {
2540        // SAFETY: plugin pointer is valid.
2541        unsafe { destroy(plugin) };
2542    }
2543
2544    Some(capabilities)
2545}
2546
2547fn default_clap_search_roots() -> Vec<PathBuf> {
2548    let mut roots = Vec::new();
2549
2550    #[cfg(target_os = "macos")]
2551    {
2552        paths::push_macos_audio_plugin_roots(&mut roots, "CLAP");
2553    }
2554
2555    #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
2556    {
2557        paths::push_unix_plugin_roots(&mut roots, "clap");
2558    }
2559
2560    roots
2561}
2562
2563#[cfg(test)]
2564mod tests {
2565    use super::collect_clap_plugins;
2566    use std::fs;
2567    use std::path::PathBuf;
2568    use std::time::{SystemTime, UNIX_EPOCH};
2569
2570    #[cfg(unix)]
2571    fn make_symlink(src: &PathBuf, dst: &PathBuf) {
2572        std::os::unix::fs::symlink(src, dst).expect("should create symlink");
2573    }
2574
2575    #[cfg(unix)]
2576    #[test]
2577    fn collect_clap_plugins_includes_symlinked_clap_files() {
2578        let nanos = SystemTime::now()
2579            .duration_since(UNIX_EPOCH)
2580            .expect("time should be valid")
2581            .as_nanos();
2582        let root = std::env::temp_dir().join(format!(
2583            "maolan-clap-symlink-test-{}-{nanos}",
2584            std::process::id()
2585        ));
2586        fs::create_dir_all(&root).expect("should create temp dir");
2587
2588        let target_file = root.join("librural_modeler.so");
2589        fs::write(&target_file, b"not a real clap binary").expect("should create target file");
2590        let clap_link = root.join("RuralModeler.clap");
2591        make_symlink(&PathBuf::from("librural_modeler.so"), &clap_link);
2592
2593        let mut out = Vec::new();
2594        collect_clap_plugins(&root, &mut out, false);
2595
2596        assert!(
2597            out.iter()
2598                .any(|info| info.path == clap_link.to_string_lossy()),
2599            "scanner should include symlinked .clap files"
2600        );
2601
2602        fs::remove_dir_all(&root).expect("should remove temp dir");
2603    }
2604}