Skip to main content

aura_clap/
lib.rs

1//! Minimal CLAP wrapper for AURA.
2//!
3//! **Spec:** [free-audio/clap](https://github.com/free-audio/clap) is the source of truth.
4//! Bindings: [`clap-sys`](https://crates.io/crates/clap-sys) (may lag free-audio *revision*;
5//! see crate README). Extensions and layouts always follow free-audio headers.
6//!
7//! ```ignore
8//! aura_clap::export!(MyPlugin);
9//! ```
10//!
11//! Covers: factory, audio-ports (+ config, sidechain), note-ports, params
12//! (sample-accurate + mono + per-note mod), note expressions, state, GUI,
13//! remote-controls, latency, tail, render, preset-load (+ discovery),
14//! MIDI 2 (`CLAP_EVENT_MIDI2` → `ProcessContext.ump`, 7-bit image on `midi`).
15
16#![allow(clippy::missing_safety_doc)]
17// ponytail: CLAP FFI glue — raw-pointer casts and C-int size conversions are
18// spec-shaped; the "safer" spellings add noise without changing semantics.
19#![allow(
20    clippy::ptr_as_ptr,
21    clippy::ref_as_ptr,
22    clippy::borrow_as_ptr,
23    clippy::cast_ptr_alignment,
24    clippy::cast_possible_truncation,
25    clippy::cast_sign_loss,
26    clippy::cast_possible_wrap
27)]
28
29use std::ffi::{CStr, CString, c_char, c_void};
30use std::ptr;
31use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
32use std::sync::{Arc, OnceLock};
33
34use aura_core::editor::{Editor, EditorBridge, PluginContext, RawWindowHandle};
35use aura_core::events::{ParamEvent, ParamEventQueue};
36use aura_core::info::PluginCategory;
37use aura_core::transport::Transport;
38use aura_core::{
39    AudioBuffer, AudioConfig, BusLayout, ChannelConfig, NoteBuffer, NoteEvent, NoteEventKind,
40    NoteExpression, NoteTarget, PluginLogic, ProcessContext, ProcessMode, ProcessStatus,
41    TimedParamEvent, Tuning, apply_at_time, apply_non_chunked, host_callback, host_callback_with,
42    layout_at, route_param_mod, route_param_value, split_points_into,
43};
44use aura_core::{MidiBuffer, MidiMessage, Ump, UmpBuffer};
45use aura_params::{ParamFlags, ParamInfo, ParamRange, Params};
46use clap_sys::events::{
47    CLAP_CORE_EVENT_SPACE_ID, CLAP_EVENT_IS_LIVE, CLAP_EVENT_MIDI, CLAP_EVENT_MIDI2,
48    CLAP_EVENT_NOTE_CHOKE, CLAP_EVENT_NOTE_END, CLAP_EVENT_NOTE_EXPRESSION, CLAP_EVENT_NOTE_OFF,
49    CLAP_EVENT_NOTE_ON, CLAP_EVENT_PARAM_GESTURE_BEGIN, CLAP_EVENT_PARAM_GESTURE_END,
50    CLAP_EVENT_PARAM_MOD, CLAP_EVENT_PARAM_VALUE, CLAP_TRANSPORT_HAS_BEATS_TIMELINE,
51    CLAP_TRANSPORT_HAS_SECONDS_TIMELINE, CLAP_TRANSPORT_HAS_TEMPO,
52    CLAP_TRANSPORT_HAS_TIME_SIGNATURE, CLAP_TRANSPORT_IS_LOOP_ACTIVE, CLAP_TRANSPORT_IS_PLAYING,
53    CLAP_TRANSPORT_IS_RECORDING, clap_event_header, clap_event_midi, clap_event_midi2,
54    clap_event_note, clap_event_note_expression, clap_event_param_gesture, clap_event_param_mod,
55    clap_event_param_value, clap_event_transport, clap_event_type, clap_input_events,
56    clap_output_events,
57};
58use clap_sys::ext::audio_ports::{
59    CLAP_AUDIO_PORT_IS_MAIN, CLAP_EXT_AUDIO_PORTS, CLAP_PORT_MONO, CLAP_PORT_STEREO,
60    clap_audio_port_info, clap_plugin_audio_ports,
61};
62use clap_sys::ext::audio_ports_config::{
63    CLAP_EXT_AUDIO_PORTS_CONFIG, clap_audio_ports_config, clap_plugin_audio_ports_config,
64};
65use clap_sys::ext::draft::tuning::CLAP_EXT_TUNING;
66use clap_sys::ext::gui::{
67    CLAP_EXT_GUI, CLAP_WINDOW_API_COCOA, CLAP_WINDOW_API_WIN32, CLAP_WINDOW_API_X11, clap_host_gui,
68    clap_plugin_gui, clap_window,
69};
70use clap_sys::ext::latency::{CLAP_EXT_LATENCY, clap_host_latency, clap_plugin_latency};
71use clap_sys::ext::note_name::{CLAP_EXT_NOTE_NAME, clap_plugin_note_name};
72use clap_sys::ext::note_ports::{
73    CLAP_EXT_NOTE_PORTS, CLAP_NOTE_DIALECT_CLAP, CLAP_NOTE_DIALECT_MIDI, CLAP_NOTE_DIALECT_MIDI2,
74    clap_note_port_info, clap_plugin_note_ports,
75};
76use clap_sys::ext::param_indication::{
77    CLAP_EXT_PARAM_INDICATION, CLAP_EXT_PARAM_INDICATION_COMPAT, clap_plugin_param_indication,
78};
79use clap_sys::ext::params::{
80    CLAP_EXT_PARAMS, CLAP_PARAM_IS_AUTOMATABLE, CLAP_PARAM_IS_AUTOMATABLE_PER_CHANNEL,
81    CLAP_PARAM_IS_AUTOMATABLE_PER_KEY, CLAP_PARAM_IS_AUTOMATABLE_PER_NOTE_ID, CLAP_PARAM_IS_BYPASS,
82    CLAP_PARAM_IS_HIDDEN, CLAP_PARAM_IS_MODULATABLE, CLAP_PARAM_IS_MODULATABLE_PER_CHANNEL,
83    CLAP_PARAM_IS_MODULATABLE_PER_KEY, CLAP_PARAM_IS_MODULATABLE_PER_NOTE_ID,
84    CLAP_PARAM_IS_READONLY, CLAP_PARAM_IS_STEPPED, CLAP_PARAM_RESCAN_VALUES, clap_host_params,
85    clap_param_info, clap_plugin_params,
86};
87use clap_sys::ext::remote_controls::{
88    CLAP_EXT_REMOTE_CONTROLS, CLAP_EXT_REMOTE_CONTROLS_COMPAT, CLAP_REMOTE_CONTROLS_COUNT,
89    clap_plugin_remote_controls, clap_remote_controls_page,
90};
91use clap_sys::ext::render::{
92    CLAP_EXT_RENDER, CLAP_RENDER_OFFLINE, CLAP_RENDER_REALTIME, clap_plugin_render,
93    clap_plugin_render_mode,
94};
95use clap_sys::ext::state::{CLAP_EXT_STATE, clap_plugin_state};
96use clap_sys::ext::tail::{CLAP_EXT_TAIL, clap_host_tail, clap_plugin_tail};
97use clap_sys::ext::voice_info::{
98    CLAP_EXT_VOICE_INFO, CLAP_VOICE_INFO_SUPPORTS_OVERLAPPING_NOTES, clap_plugin_voice_info,
99    clap_voice_info,
100};
101use clap_sys::factory::plugin_factory::{CLAP_PLUGIN_FACTORY_ID, clap_plugin_factory};
102use clap_sys::host::clap_host;
103use clap_sys::id::{CLAP_INVALID_ID, clap_id};
104use clap_sys::plugin::{clap_plugin, clap_plugin_descriptor};
105use clap_sys::plugin_features::{
106    CLAP_PLUGIN_FEATURE_ANALYZER, CLAP_PLUGIN_FEATURE_AUDIO_EFFECT, CLAP_PLUGIN_FEATURE_INSTRUMENT,
107    CLAP_PLUGIN_FEATURE_NOTE_EFFECT,
108};
109use clap_sys::process::{
110    CLAP_PROCESS_CONTINUE, CLAP_PROCESS_ERROR, CLAP_PROCESS_TAIL, clap_process, clap_process_status,
111};
112use clap_sys::stream::{clap_istream, clap_ostream};
113use clap_sys::string_sizes::{CLAP_NAME_SIZE, CLAP_PATH_SIZE};
114use clap_sys::version::CLAP_VERSION;
115
116mod preset_load;
117mod tuning;
118
119// ---------------------------------------------------------------------------
120// Export macro
121// ---------------------------------------------------------------------------
122
123/// Hidden re-export so [`export!`] can name clap-sys types without a
124/// direct plugin dependency on `clap-sys`.
125#[doc(hidden)]
126pub use clap_sys as __clap_sys;
127
128/// Export `$logic` ([`PluginLogic`]) as this cdylib's CLAP entry point.
129#[macro_export]
130macro_rules! export {
131    ($logic:ty) => {
132        #[allow(non_upper_case_globals)]
133        #[unsafe(no_mangle)]
134        pub static clap_entry: $crate::__clap_sys::entry::clap_plugin_entry =
135            $crate::__clap_sys::entry::clap_plugin_entry {
136                clap_version: $crate::__clap_sys::version::CLAP_VERSION,
137                init: Some($crate::entry_init),
138                deinit: Some($crate::entry_deinit),
139                get_factory: Some($crate::get_factory::<$logic>),
140            };
141    };
142}
143
144/// Alias of [`export!`] for symmetry with `export_vst3!` / `export_lv2!`.
145///
146/// Prefer [`export!`] in new code; this name exists so format exports read as a set.
147#[macro_export]
148macro_rules! export_clap {
149    ($logic:ty) => {
150        $crate::export!($logic);
151    };
152}
153
154// ---------------------------------------------------------------------------
155// Entry
156// ---------------------------------------------------------------------------
157
158#[must_use]
159pub unsafe extern "C" fn entry_init(_plugin_path: *const c_char) -> bool {
160    true
161}
162
163pub unsafe extern "C" fn entry_deinit() {}
164
165#[must_use]
166pub unsafe extern "C" fn get_factory<L: PluginLogic>(factory_id: *const c_char) -> *const c_void {
167    if factory_id.is_null() {
168        return ptr::null();
169    }
170    let id = unsafe { CStr::from_ptr(factory_id) };
171    if id == CLAP_PLUGIN_FACTORY_ID {
172        factory::<L>() as *const clap_plugin_factory as *const c_void
173    } else if preset_load::is_discovery_factory_id(id) && !L::factory_presets().is_empty() {
174        preset_load::discovery_factory::<L>() as *const c_void
175    } else {
176        ptr::null()
177    }
178}
179
180fn factory<L: PluginLogic>() -> &'static clap_plugin_factory {
181    // Monomorphized static: unique per L.
182    static CELL: OnceLock<clap_plugin_factory> = OnceLock::new();
183    CELL.get_or_init(|| clap_plugin_factory {
184        get_plugin_count: Some(factory_get_plugin_count),
185        get_plugin_descriptor: Some(factory_get_plugin_descriptor::<L>),
186        create_plugin: Some(factory_create_plugin::<L>),
187    })
188}
189
190unsafe extern "C" fn factory_get_plugin_count(_factory: *const clap_plugin_factory) -> u32 {
191    1
192}
193
194unsafe extern "C" fn factory_get_plugin_descriptor<L: PluginLogic>(
195    _factory: *const clap_plugin_factory,
196    index: u32,
197) -> *const clap_plugin_descriptor {
198    if index != 0 {
199        return ptr::null();
200    }
201    descriptor::<L>()
202}
203
204unsafe extern "C" fn factory_create_plugin<L: PluginLogic>(
205    _factory: *const clap_plugin_factory,
206    host: *const clap_host,
207    plugin_id: *const c_char,
208) -> *const clap_plugin {
209    if plugin_id.is_null() {
210        return ptr::null();
211    }
212    let want = unsafe { CStr::from_ptr(plugin_id) };
213    let info = L::info();
214    let Ok(id) = CString::new(info.clap_id) else {
215        return ptr::null();
216    };
217    if want.to_bytes() != id.as_bytes() {
218        return ptr::null();
219    }
220
221    let params = Arc::new(L::Params::default());
222    let desc = descriptor::<L>();
223    let tuning_state = tuning::TuningState::new(host);
224
225    let instance = Box::new(Instance::<L> {
226        host,
227        params,
228        editor: None,
229        param_events: Arc::new(ParamEventQueue::default()),
230        host_scale: Arc::new(AtomicU64::new(1.0f64.to_bits())),
231        state: None,
232        sample_rate: 44_100.0,
233        max_frames: 0,
234        active: false,
235        layout_index: 0,
236        latency_cache: AtomicU32::new(0),
237        latency_dirty: AtomicBool::new(false),
238        tail_cache: AtomicU32::new(0),
239        process_mode: ProcessMode::Realtime,
240        scratch: ProcessScratch::new(),
241        tuning_state,
242        tuning_pool_changed: AtomicBool::new(false),
243    });
244
245    let plugin = Box::new(clap_plugin {
246        desc,
247        plugin_data: Box::into_raw(instance) as *mut c_void,
248        init: Some(plugin_init::<L>),
249        destroy: Some(plugin_destroy::<L>),
250        activate: Some(plugin_activate::<L>),
251        deactivate: Some(plugin_deactivate::<L>),
252        start_processing: Some(plugin_start_processing::<L>),
253        stop_processing: Some(plugin_stop_processing::<L>),
254        reset: Some(plugin_reset::<L>),
255        process: Some(plugin_process::<L>),
256        get_extension: Some(plugin_get_extension::<L>),
257        on_main_thread: Some(plugin_on_main_thread::<L>),
258    });
259
260    Box::into_raw(plugin)
261}
262
263// ---------------------------------------------------------------------------
264// Descriptor (leaked, pointer-stable)
265// ---------------------------------------------------------------------------
266
267struct DescStorage {
268    id: CString,
269    name: CString,
270    vendor: CString,
271    url: CString,
272    version: CString,
273    description: CString,
274    feature_ptrs: Vec<*const c_char>,
275    desc: clap_plugin_descriptor,
276}
277
278fn descriptor<L: PluginLogic>() -> &'static clap_plugin_descriptor {
279    // Unique static per monomorphization of L.
280    static CELL: OnceLock<&'static clap_plugin_descriptor> = OnceLock::new();
281    CELL.get_or_init(|| {
282        let info = L::info();
283        let id = CString::new(info.clap_id).unwrap_or_default();
284        let name = CString::new(info.name).unwrap_or_default();
285        let vendor = CString::new(info.vendor).unwrap_or_default();
286        let url = CString::new(info.url).unwrap_or_default();
287        let version = CString::new(info.version).unwrap_or_default();
288        let description = CString::new(info.name).unwrap_or_default();
289
290        let feature: &CStr = match info.category {
291            PluginCategory::Instrument => CLAP_PLUGIN_FEATURE_INSTRUMENT,
292            PluginCategory::Analyzer => CLAP_PLUGIN_FEATURE_ANALYZER,
293            PluginCategory::NoteEffect => CLAP_PLUGIN_FEATURE_NOTE_EFFECT,
294            PluginCategory::Effect => CLAP_PLUGIN_FEATURE_AUDIO_EFFECT,
295        };
296
297        let storage = Box::leak(Box::new(DescStorage {
298            id,
299            name,
300            vendor,
301            url,
302            version,
303            description,
304            feature_ptrs: Vec::new(),
305            desc: unsafe { std::mem::zeroed() },
306        }));
307
308        storage.feature_ptrs = vec![feature.as_ptr(), ptr::null()];
309        storage.desc = clap_plugin_descriptor {
310            clap_version: CLAP_VERSION,
311            id: storage.id.as_ptr(),
312            name: storage.name.as_ptr(),
313            vendor: storage.vendor.as_ptr(),
314            url: storage.url.as_ptr(),
315            manual_url: storage.url.as_ptr(),
316            support_url: storage.url.as_ptr(),
317            version: storage.version.as_ptr(),
318            description: storage.description.as_ptr(),
319            features: storage.feature_ptrs.as_ptr(),
320        };
321        &storage.desc
322    })
323}
324
325// ---------------------------------------------------------------------------
326// Instance
327// ---------------------------------------------------------------------------
328
329pub(crate) struct Instance<L: PluginLogic> {
330    pub(crate) host: *const clap_host,
331    pub(crate) params: Arc<L::Params>,
332    /// Created on the main thread in `plugin_init`; `None` = no GUI.
333    editor: Option<Box<dyn Editor>>,
334    /// GUI → host param events, drained in process/flush.
335    param_events: Arc<ParamEventQueue>,
336    /// Host content scale from `gui.set_scale` (f64 bits, default 1.0).
337    /// Shared with [`ClapBridge`] so `request_resize` matches `get_size`.
338    host_scale: Arc<AtomicU64>,
339    state: Option<L::DspState>,
340    sample_rate: f64,
341    max_frames: u32,
342    active: bool,
343    /// Index into `L::bus_layouts()` selected via `audio-ports-config`.
344    layout_index: usize,
345    /// Last latency reported to the host (audio/main shared).
346    latency_cache: AtomicU32,
347    /// Set on the audio thread when latency changes; drained on main thread.
348    latency_dirty: AtomicBool,
349    /// Last tail length reported to the host.
350    tail_cache: AtomicU32,
351    /// Host render mode (`clap.render`) → `ProcessContext.process_mode`.
352    process_mode: ProcessMode,
353    /// Audio-thread scratch — reserved in `activate`, reused every `process`.
354    scratch: ProcessScratch,
355    /// CLAP `clap.tuning/2` host state (event space + active tuning ids).
356    tuning_state: Arc<tuning::TuningState>,
357    /// Set by the host's `clap.tuning` `changed()` callback; consumed in process.
358    tuning_pool_changed: AtomicBool,
359}
360
361/// Pre-sized process working set. Heap growth here is a Bitwig-crash class bug
362/// (note-expression flood used to `Vec::new` + copy every block).
363struct ProcessScratch {
364    timed: Vec<TimedParamEvent>,
365    tuning_events: Vec<aura_core::TuningEvent>,
366    midi: MidiBuffer,
367    midi_out: MidiBuffer,
368    notes: NoteBuffer,
369    notes_out: NoteBuffer,
370    notes_chunk: NoteBuffer,
371    midi_chunk: MidiBuffer,
372    ump: UmpBuffer,
373    ump_out: UmpBuffer,
374    ump_chunk: UmpBuffer,
375    splits: Vec<u32>,
376    /// Zeroed fallback when a host input pointer is null.
377    silence: Vec<f32>,
378}
379
380/// Bitwig can emit a note-expression per sample per voice. Cap extras; keep
381/// on/off/choke so notes cannot stick. Slack in the reserve covers those.
382const MAX_NOTE_EVENTS: usize = 4096;
383
384impl ProcessScratch {
385    fn new() -> Self {
386        Self {
387            timed: Vec::new(),
388            tuning_events: Vec::new(),
389            midi: MidiBuffer::new(),
390            midi_out: MidiBuffer::new(),
391            notes: NoteBuffer::new(),
392            notes_out: NoteBuffer::new(),
393            notes_chunk: NoteBuffer::new(),
394            midi_chunk: MidiBuffer::new(),
395            ump: UmpBuffer::new(),
396            ump_out: UmpBuffer::new(),
397            ump_chunk: UmpBuffer::new(),
398            splits: Vec::new(),
399            silence: Vec::new(),
400        }
401    }
402
403    fn prepare(&mut self, max_frames: usize) {
404        self.timed.reserve(256);
405        self.tuning_events.reserve(16);
406        self.midi.reserve(MAX_NOTE_EVENTS);
407        self.midi_out.reserve(256);
408        self.notes.reserve(MAX_NOTE_EVENTS + 128);
409        self.notes_out.reserve(256);
410        self.notes_chunk.reserve(MAX_NOTE_EVENTS + 128);
411        self.midi_chunk.reserve(MAX_NOTE_EVENTS);
412        self.ump.reserve(MAX_NOTE_EVENTS);
413        self.ump_out.reserve(256);
414        self.ump_chunk.reserve(MAX_NOTE_EVENTS);
415        self.splits.reserve(64);
416        if self.silence.len() < max_frames {
417            self.silence.resize(max_frames, 0.0);
418        }
419    }
420}
421
422/// Stereo + optional stereo SC today; headroom if a layout grows.
423const MAX_AUDIO_CH: usize = 8;
424
425fn accept_note_event(len: usize, essential: bool) -> bool {
426    essential || len < MAX_NOTE_EVENTS
427}
428
429impl<L: PluginLogic> Instance<L> {
430    fn host_scale(&self) -> f64 {
431        f64::from_bits(self.host_scale.load(Ordering::Relaxed))
432    }
433
434    fn set_host_scale(&self, scale: f64) {
435        if scale.is_finite() && scale > 0.0 {
436            self.host_scale.store(scale.to_bits(), Ordering::Relaxed);
437        }
438    }
439
440    fn selected_layout(&self) -> BusLayout {
441        let layouts = L::bus_layouts();
442        layout_at(&layouts, self.layout_index)
443    }
444
445    /// Snapshot `PluginLogic::latency` into the cache. Returns `true` if it changed.
446    fn update_latency_cache(&self) -> bool {
447        let Some(state) = self.state.as_ref() else {
448            return false;
449        };
450        let new = L::latency(state);
451        let old = self.latency_cache.swap(new, Ordering::Relaxed);
452        old != new
453    }
454
455    /// Snapshot `PluginLogic::tail_length` into the cache. Returns `true` if changed.
456    fn update_tail_cache(&self) -> bool {
457        let Some(state) = self.state.as_ref() else {
458            return false;
459        };
460        let new = L::tail_length(state);
461        let old = self.tail_cache.swap(new, Ordering::Relaxed);
462        old != new
463    }
464
465    pub(crate) unsafe fn from_plugin<'a>(plugin: *const clap_plugin) -> Option<&'a mut Self> {
466        if plugin.is_null() {
467            return None;
468        }
469        let data = unsafe { (*plugin).plugin_data as *mut Self };
470        if data.is_null() {
471            return None;
472        }
473        Some(unsafe { &mut *data })
474    }
475}
476
477/// Call `clap_host_latency.changed` if the host exposes it (main thread).
478fn host_latency_changed(host: *const clap_host) {
479    if host.is_null() {
480        return;
481    }
482    let Some(get) = (unsafe { (*host).get_extension }) else {
483        return;
484    };
485    let ext = unsafe { get(host, CLAP_EXT_LATENCY.as_ptr()) };
486    if ext.is_null() {
487        return;
488    }
489    let host_lat = unsafe { &*(ext as *const clap_host_latency) };
490    if let Some(changed) = host_lat.changed {
491        unsafe { changed(host) };
492    }
493}
494
495/// Call `clap_host_tail.changed` if the host exposes it (main thread).
496fn host_tail_changed(host: *const clap_host) {
497    if host.is_null() {
498        return;
499    }
500    let Some(get) = (unsafe { (*host).get_extension }) else {
501        return;
502    };
503    let ext = unsafe { get(host, CLAP_EXT_TAIL.as_ptr()) };
504    if ext.is_null() {
505        return;
506    }
507    let host_tail = unsafe { &*(ext as *const clap_host_tail) };
508    if let Some(changed) = host_tail.changed {
509        unsafe { changed(host) };
510    }
511}
512
513/// Ask the host to call `on_main_thread` soon (audio-thread safe).
514fn host_request_callback(host: *const clap_host) {
515    if host.is_null() {
516        return;
517    }
518    if let Some(req) = unsafe { (*host).request_callback } {
519        unsafe { req(host) };
520    }
521}
522
523/// Host restart so PDC can re-read latency after a mid-run change.
524fn host_request_restart(host: *const clap_host) {
525    if host.is_null() {
526        return;
527    }
528    if let Some(req) = unsafe { (*host).request_restart } {
529        unsafe { req(host) };
530    }
531}
532
533// ---------------------------------------------------------------------------
534// Plugin callbacks
535// ---------------------------------------------------------------------------
536
537unsafe extern "C" fn plugin_init<L: PluginLogic>(plugin: *const clap_plugin) -> bool {
538    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
539        return false;
540    };
541    // GUI factory runs on the main thread; gui.create only checks presence.
542    inst.editor = L::editor(Arc::clone(&inst.params));
543    true
544}
545
546unsafe extern "C" fn plugin_destroy<L: PluginLogic>(plugin: *const clap_plugin) {
547    if plugin.is_null() {
548        return;
549    }
550    // Drop (editor teardown, GPU) must not unwind across the C ABI.
551    host_callback("CLAP", "destroy", || {
552        let plugin = unsafe { Box::from_raw(plugin.cast_mut()) };
553        if !plugin.plugin_data.is_null() {
554            drop(unsafe { Box::from_raw(plugin.plugin_data as *mut Instance<L>) });
555        }
556    });
557}
558
559unsafe extern "C" fn plugin_activate<L: PluginLogic>(
560    plugin: *const clap_plugin,
561    sample_rate: f64,
562    _min_frames: u32,
563    max_frames: u32,
564) -> bool {
565    host_callback_with("CLAP", "activate", false, || {
566        let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
567            return false;
568        };
569        inst.sample_rate = sample_rate;
570        inst.max_frames = max_frames;
571        inst.scratch.prepare(max_frames as usize);
572        let layout = inst.selected_layout();
573        let config = AudioConfig::new(sample_rate, max_frames as usize)
574            .with_channels(layout.main_input_channels(), layout.main_output_channels())
575            .with_sidechain_channels(layout.sidechain_input_channels())
576            .with_aux_channels(layout.aux_output_channels());
577        let mut state = L::init(&inst.params, sample_rate);
578        L::reset(&mut state, &inst.params, &config);
579        inst.params.set_sample_rate(sample_rate);
580        let latency = L::latency(&state);
581        let tail = L::tail_length(&state);
582        inst.state = Some(state);
583        inst.latency_cache.store(latency, Ordering::Relaxed);
584        inst.latency_dirty.store(false, Ordering::Relaxed);
585        inst.tail_cache.store(tail, Ordering::Relaxed);
586        inst.active = true;
587        // Spec: latency.changed is [main-thread]; host re-reads get after activate.
588        host_latency_changed(inst.host);
589        // tail.changed is [audio-thread] when active — host calls get() after
590        // activate; mid-run changes notify from process (see plugin_process).
591        true
592    })
593}
594
595unsafe extern "C" fn plugin_deactivate<L: PluginLogic>(plugin: *const clap_plugin) {
596    host_callback("CLAP", "deactivate", || {
597        if let Some(inst) = unsafe { Instance::<L>::from_plugin(plugin) } {
598            inst.active = false;
599            inst.state = None;
600        }
601    });
602}
603
604unsafe extern "C" fn plugin_start_processing<L: PluginLogic>(plugin: *const clap_plugin) -> bool {
605    unsafe { Instance::<L>::from_plugin(plugin) }.is_some()
606}
607
608unsafe extern "C" fn plugin_stop_processing<L: PluginLogic>(_plugin: *const clap_plugin) {}
609
610unsafe extern "C" fn plugin_reset<L: PluginLogic>(plugin: *const clap_plugin) {
611    host_callback("CLAP", "reset", || {
612        let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
613            return;
614        };
615        let layout = inst.selected_layout();
616        let config = AudioConfig::new(inst.sample_rate, inst.max_frames as usize)
617            .with_channels(layout.main_input_channels(), layout.main_output_channels())
618            .with_sidechain_channels(layout.sidechain_input_channels())
619            .with_aux_channels(layout.aux_output_channels());
620        if let Some(state) = inst.state.as_mut() {
621            L::reset(state, &inst.params, &config);
622            inst.params.snap_smoothers();
623        }
624        if inst.update_latency_cache() {
625            // Reset runs while active; free-audio wants restart for mid-run changes.
626            host_latency_changed(inst.host);
627            host_request_restart(inst.host);
628        }
629    });
630}
631
632// CLAP process owns host buffers, timed events, and optional multi-chunk
633// process loops — length is inherent to the ABI glue.
634#[allow(clippy::too_many_lines)]
635unsafe extern "C" fn plugin_process<L: PluginLogic>(
636    plugin: *const clap_plugin,
637    process: *const clap_process,
638) -> clap_process_status {
639    // Author `process` + buffer glue: never unwind into the host.
640    host_callback_with("CLAP", "process", CLAP_PROCESS_ERROR, || {
641        let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
642            return CLAP_PROCESS_ERROR;
643        };
644        if process.is_null() || !inst.active {
645            return CLAP_PROCESS_ERROR;
646        }
647        let process = unsafe { &*process };
648        let frames = process.frames_count as usize;
649        if frames == 0 {
650            return CLAP_PROCESS_CONTINUE;
651        }
652        if inst.max_frames == 0 || frames > inst.max_frames as usize {
653            return CLAP_PROCESS_ERROR;
654        }
655
656        inst.scratch.timed.clear();
657        inst.scratch.tuning_events.clear();
658        inst.scratch.midi.clear();
659        inst.scratch.notes.clear();
660        inst.scratch.midi_out.clear();
661        inst.scratch.notes_out.clear();
662        inst.scratch.ump.clear();
663        inst.scratch.ump_out.clear();
664        let tuning_space_id = inst.tuning_state.space_id();
665        if !process.in_events.is_null() {
666            unsafe {
667                collect_input_events(
668                    process.in_events,
669                    &mut inst.scratch.timed,
670                    &mut inst.scratch.tuning_events,
671                    tuning_space_id,
672                    &mut inst.scratch.midi,
673                    &mut inst.scratch.notes,
674                    &mut inst.scratch.ump,
675                );
676            };
677        }
678        unsafe { emit_param_events(&inst.param_events, process.out_events) };
679
680        let transport = if process.transport.is_null() {
681            None
682        } else {
683            Some(map_transport(unsafe { &*process.transport }))
684        };
685
686        let layout = inst.selected_layout();
687        let process_mode = inst.process_mode;
688        let sample_rate = inst.sample_rate;
689
690        let Some(state) = inst.state.as_mut() else {
691            return CLAP_PROCESS_ERROR;
692        };
693        let main_in_ch = layout.main_input_channels() as usize;
694        let sidechain_in_ch = layout.sidechain_input_channels() as usize;
695        let main_out_ch = layout.main_output_channels() as usize;
696        let total_in_ch = main_in_ch + sidechain_in_ch;
697        let mut out_ch = layout.total_output_channels() as usize;
698        if out_ch > MAX_AUDIO_CH || total_in_ch > MAX_AUDIO_CH {
699            return CLAP_PROCESS_ERROR;
700        }
701
702        // Host pointers only — no per-block audio copies. Extra host input
703        // ports on an output-only instrument are ignored (used to panic).
704        let mut in_ptrs = [ptr::null::<f32>(); MAX_AUDIO_CH];
705        let mut filled_in = 0usize;
706        if !process.audio_inputs.is_null() {
707            for port_i in 0..process.audio_inputs_count as usize {
708                if filled_in >= total_in_ch {
709                    break;
710                }
711                let port = unsafe { &*process.audio_inputs.add(port_i) };
712                if port.data32.is_null() {
713                    continue;
714                }
715                for c in 0..port.channel_count as usize {
716                    if filled_in >= total_in_ch {
717                        break;
718                    }
719                    in_ptrs[filled_in] = unsafe { *port.data32.add(c) };
720                    filled_in += 1;
721                }
722            }
723        }
724
725        let mut out_ptrs = [ptr::null_mut::<f32>(); MAX_AUDIO_CH];
726        let mut filled_out = 0usize;
727        if !process.audio_outputs.is_null() {
728            for port_i in 0..process.audio_outputs_count as usize {
729                if filled_out >= out_ch {
730                    break;
731                }
732                let port = unsafe { &*process.audio_outputs.add(port_i) };
733                if port.data32.is_null() {
734                    continue;
735                }
736                for c in 0..port.channel_count as usize {
737                    if filled_out >= out_ch {
738                        break;
739                    }
740                    out_ptrs[filled_out] = unsafe { *port.data32.add(c) };
741                    filled_out += 1;
742                }
743            }
744        }
745        // Note-FX racks (Bitwig) often pass 0 audio ports. Still process events.
746        // If the host only wired main outs, shrink to what we got (aux silent).
747        if filled_out != out_ch {
748            if filled_out <= MAX_AUDIO_CH {
749                out_ch = filled_out;
750            } else {
751                return CLAP_PROCESS_ERROR;
752            }
753        }
754        let main_out_for_buf = main_out_ch.min(out_ch);
755
756        // Sample-accurate: non-CHUNKED params apply at block start; CHUNKED
757        // params split the block at their event times.
758        let infos = inst.params.param_infos();
759        apply_non_chunked(&*inst.params, &inst.scratch.timed, &infos);
760        let frames_u = frames as u32;
761        split_points_into(
762            &mut inst.scratch.splits,
763            frames_u,
764            &inst.scratch.timed,
765            &infos,
766        );
767        for ev in &inst.scratch.tuning_events {
768            let t = ev.sample_offset;
769            if t > 0 && t < frames_u {
770                inst.scratch.splits.push(t);
771            }
772        }
773        inst.scratch.splits.sort_unstable();
774        inst.scratch.splits.dedup();
775
776        let tuning =
777            Tuning::new(Arc::clone(&inst.tuning_state) as Arc<dyn aura_core::TuningProvider>);
778
779        let mut status = ProcessStatus::Continue;
780        let n_splits = inst.scratch.splits.len();
781
782        for si in 0..n_splits.saturating_sub(1) {
783            let t0 = inst.scratch.splits[si] as usize;
784            let t1 = inst.scratch.splits[si + 1] as usize;
785            if t1 <= t0 {
786                continue;
787            }
788            let chunk_len = t1 - t0;
789            apply_at_time(
790                &*inst.params,
791                &inst.scratch.timed,
792                inst.scratch.splits[si],
793                &infos,
794            );
795            let chunk_t0 = inst.scratch.splits[si];
796            for ev in &inst.scratch.tuning_events {
797                if ev.sample_offset == chunk_t0 {
798                    tuning.apply_event(ev);
799                }
800            }
801
802            if inst.scratch.silence.len() < t1 {
803                return CLAP_PROCESS_ERROR;
804            }
805            let silence = &inst.scratch.silence[t0..t1];
806            let mut in_store = [&[] as &[f32]; MAX_AUDIO_CH];
807            for i in 0..total_in_ch {
808                in_store[i] = if in_ptrs[i].is_null() {
809                    silence
810                } else {
811                    unsafe { std::slice::from_raw_parts(in_ptrs[i].add(t0), chunk_len) }
812                };
813            }
814            let in_refs = &in_store[..total_in_ch];
815            if in_refs.iter().any(|ch| ch.len() < chunk_len) {
816                return CLAP_PROCESS_ERROR;
817            }
818            if out_ptrs[..out_ch].iter().any(|p| p.is_null()) {
819                return CLAP_PROCESS_ERROR;
820            }
821
822            let single = n_splits == 2;
823            if !single {
824                let (a, b) = (inst.scratch.splits[si], inst.scratch.splits[si + 1]);
825                inst.scratch
826                    .midi_chunk
827                    .copy_range_rebased(&inst.scratch.midi, a, b);
828                inst.scratch
829                    .notes_chunk
830                    .copy_range_rebased(&inst.scratch.notes, a, b);
831                inst.scratch
832                    .ump_chunk
833                    .copy_range_rebased(&inst.scratch.ump, a, b);
834            }
835            let midi = if single {
836                std::mem::take(&mut inst.scratch.midi)
837            } else {
838                std::mem::take(&mut inst.scratch.midi_chunk)
839            };
840            let notes = if single {
841                std::mem::take(&mut inst.scratch.notes)
842            } else {
843                std::mem::take(&mut inst.scratch.notes_chunk)
844            };
845            let ump = if single {
846                std::mem::take(&mut inst.scratch.ump)
847            } else {
848                std::mem::take(&mut inst.scratch.ump_chunk)
849            };
850            let mut ctx = ProcessContext::new(sample_rate, chunk_len)
851                .with_process_mode(process_mode)
852                .with_midi(midi)
853                .with_notes(notes)
854                .with_ump(ump)
855                .with_midi_out(std::mem::take(&mut inst.scratch.midi_out))
856                .with_notes_out(std::mem::take(&mut inst.scratch.notes_out))
857                .with_ump_out(std::mem::take(&mut inst.scratch.ump_out))
858                .with_tuning(tuning.clone());
859            ctx.transport = transport;
860
861            let chunk_status = unsafe {
862                run_process_chunk::<L>(
863                    state,
864                    &inst.params,
865                    in_refs,
866                    out_ptrs,
867                    out_ch,
868                    main_out_for_buf,
869                    t0,
870                    chunk_len,
871                    main_in_ch,
872                    sidechain_in_ch,
873                    &mut ctx,
874                )
875            };
876
877            if single {
878                inst.scratch.midi = std::mem::take(&mut ctx.midi);
879                inst.scratch.notes = std::mem::take(&mut ctx.notes);
880                inst.scratch.ump = std::mem::take(&mut ctx.ump);
881            } else {
882                inst.scratch.midi_chunk = std::mem::take(&mut ctx.midi);
883                inst.scratch.notes_chunk = std::mem::take(&mut ctx.notes);
884                inst.scratch.ump_chunk = std::mem::take(&mut ctx.ump);
885                inst.scratch.midi_chunk.clear();
886                inst.scratch.notes_chunk.clear();
887                inst.scratch.ump_chunk.clear();
888            }
889            unsafe {
890                emit_midi_events_at(process.out_events, &ctx.midi_out, inst.scratch.splits[si]);
891                emit_note_events_at(process.out_events, &ctx.notes_out, inst.scratch.splits[si]);
892                emit_ump_events_at(process.out_events, &ctx.ump_out, inst.scratch.splits[si]);
893            }
894            inst.scratch.midi_out = std::mem::take(&mut ctx.midi_out);
895            inst.scratch.midi_out.clear();
896            inst.scratch.notes_out = std::mem::take(&mut ctx.notes_out);
897            inst.scratch.notes_out.clear();
898            inst.scratch.ump_out = std::mem::take(&mut ctx.ump_out);
899            inst.scratch.ump_out.clear();
900
901            match chunk_status {
902                ProcessStatus::Error => {
903                    status = ProcessStatus::Error;
904                    break;
905                }
906                ProcessStatus::TailFinished => status = ProcessStatus::TailFinished,
907                ProcessStatus::Continue => {
908                    if status != ProcessStatus::TailFinished {
909                        status = ProcessStatus::Continue;
910                    }
911                }
912            }
913        }
914
915        if inst.tuning_pool_changed.swap(false, Ordering::Relaxed) {
916            L::tuning_changed(state, &inst.params);
917        }
918        // PDC: latency.changed is [main-thread] only — schedule callback.
919        if inst.update_latency_cache() {
920            inst.latency_dirty.store(true, Ordering::Relaxed);
921            host_request_callback(inst.host);
922        }
923        // tail.changed is [audio-thread] when active — notify here, not via
924        // on_main_thread (clap-validator enforces the thread rule).
925        if inst.update_tail_cache() {
926            host_tail_changed(inst.host);
927        }
928
929        match status {
930            ProcessStatus::Continue => CLAP_PROCESS_CONTINUE,
931            ProcessStatus::TailFinished => CLAP_PROCESS_TAIL,
932            ProcessStatus::Error => CLAP_PROCESS_ERROR,
933        }
934    })
935}
936
937/// Write one chunk into host output pointers (main + optional aux, ≤4 ch).
938#[allow(clippy::too_many_arguments)]
939unsafe fn run_process_chunk<L: PluginLogic>(
940    state: &mut L::DspState,
941    params: &L::Params,
942    in_refs: &[&[f32]],
943    out_ptrs: [*mut f32; MAX_AUDIO_CH],
944    out_ch: usize,
945    main_out_ch: usize,
946    t0: usize,
947    chunk_len: usize,
948    main_in_ch: usize,
949    sidechain_in_ch: usize,
950    ctx: &mut ProcessContext,
951) -> ProcessStatus {
952    unsafe fn slice_out<'a>(p: *mut f32, t0: usize, n: usize) -> &'a mut [f32] {
953        unsafe { std::slice::from_raw_parts_mut(p.add(t0), n) }
954    }
955    let main_out = main_out_ch.min(out_ch);
956    match out_ch {
957        0 => {
958            let mut outs: [&mut [f32]; 0] = [];
959            let mut buffer = unsafe {
960                AudioBuffer::from_slices_with_buses_unchecked(
961                    in_refs,
962                    &mut outs,
963                    chunk_len,
964                    main_in_ch,
965                    sidechain_in_ch,
966                    0,
967                )
968            };
969            L::process(state, params, &mut buffer, ctx)
970        }
971        1 => {
972            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
973            let mut outs = [&mut s0 as &mut [f32]];
974            let mut buffer = unsafe {
975                AudioBuffer::from_slices_with_buses_unchecked(
976                    in_refs,
977                    &mut outs,
978                    chunk_len,
979                    main_in_ch,
980                    sidechain_in_ch,
981                    main_out,
982                )
983            };
984            L::process(state, params, &mut buffer, ctx)
985        }
986        2 => {
987            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
988            let mut s1 = unsafe { slice_out(out_ptrs[1], t0, chunk_len) };
989            let mut outs = [&mut s0 as &mut [f32], &mut s1];
990            let mut buffer = unsafe {
991                AudioBuffer::from_slices_with_buses_unchecked(
992                    in_refs,
993                    &mut outs,
994                    chunk_len,
995                    main_in_ch,
996                    sidechain_in_ch,
997                    main_out,
998                )
999            };
1000            L::process(state, params, &mut buffer, ctx)
1001        }
1002        3 => {
1003            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
1004            let mut s1 = unsafe { slice_out(out_ptrs[1], t0, chunk_len) };
1005            let mut s2 = unsafe { slice_out(out_ptrs[2], t0, chunk_len) };
1006            let mut outs = [&mut s0 as &mut [f32], &mut s1, &mut s2];
1007            let mut buffer = unsafe {
1008                AudioBuffer::from_slices_with_buses_unchecked(
1009                    in_refs,
1010                    &mut outs,
1011                    chunk_len,
1012                    main_in_ch,
1013                    sidechain_in_ch,
1014                    main_out,
1015                )
1016            };
1017            L::process(state, params, &mut buffer, ctx)
1018        }
1019        4 => {
1020            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
1021            let mut s1 = unsafe { slice_out(out_ptrs[1], t0, chunk_len) };
1022            let mut s2 = unsafe { slice_out(out_ptrs[2], t0, chunk_len) };
1023            let mut s3 = unsafe { slice_out(out_ptrs[3], t0, chunk_len) };
1024            let mut outs = [&mut s0 as &mut [f32], &mut s1, &mut s2, &mut s3];
1025            let mut buffer = unsafe {
1026                AudioBuffer::from_slices_with_buses_unchecked(
1027                    in_refs,
1028                    &mut outs,
1029                    chunk_len,
1030                    main_in_ch,
1031                    sidechain_in_ch,
1032                    main_out,
1033                )
1034            };
1035            L::process(state, params, &mut buffer, ctx)
1036        }
1037        _ => ProcessStatus::Error,
1038    }
1039}
1040
1041/// Collect timed param / MIDI / note / tuning events from the host input list.
1042#[allow(clippy::too_many_lines)]
1043unsafe fn collect_input_events(
1044    in_events: *const clap_input_events,
1045    timed: &mut Vec<TimedParamEvent>,
1046    tuning_events: &mut Vec<aura_core::TuningEvent>,
1047    tuning_space_id: u16,
1048    midi: &mut MidiBuffer,
1049    notes: &mut NoteBuffer,
1050    ump: &mut UmpBuffer,
1051) {
1052    midi.clear();
1053    notes.clear();
1054    ump.clear();
1055    timed.clear();
1056    tuning_events.clear();
1057    let ev = unsafe { &*in_events };
1058    let Some(size_fn) = ev.size else {
1059        return;
1060    };
1061    let Some(get_fn) = ev.get else {
1062        return;
1063    };
1064    let n = unsafe { size_fn(ev) };
1065    for i in 0..n {
1066        let hdr = unsafe { get_fn(ev, i) };
1067        if hdr.is_null() {
1068            continue;
1069        }
1070        let header = unsafe { &*hdr };
1071        if tuning_space_id != 0 && header.space_id == tuning_space_id {
1072            if let Some(ev) = unsafe { tuning::parse_tuning_event(header, hdr) } {
1073                tuning_events.push(ev);
1074            }
1075            continue;
1076        }
1077        if header.space_id != CLAP_CORE_EVENT_SPACE_ID {
1078            continue;
1079        }
1080        match header.type_ {
1081            CLAP_EVENT_PARAM_VALUE => {
1082                let pev = unsafe { &*(hdr as *const clap_event_param_value) };
1083                if pev.note_id >= 0 && !accept_note_event(notes.len(), false) {
1084                    continue;
1085                }
1086                route_param_value(
1087                    timed,
1088                    notes,
1089                    header.time,
1090                    pev.param_id,
1091                    pev.value,
1092                    NoteTarget {
1093                        note_id: pev.note_id,
1094                        port_index: pev.port_index,
1095                        channel: pev.channel,
1096                        key: pev.key,
1097                    },
1098                );
1099            }
1100            CLAP_EVENT_PARAM_MOD => {
1101                let pev = unsafe { &*(hdr as *const clap_event_param_mod) };
1102                if pev.note_id >= 0 && !accept_note_event(notes.len(), false) {
1103                    continue;
1104                }
1105                route_param_mod(
1106                    timed,
1107                    notes,
1108                    header.time,
1109                    pev.param_id,
1110                    pev.amount,
1111                    NoteTarget {
1112                        note_id: pev.note_id,
1113                        port_index: pev.port_index,
1114                        channel: pev.channel,
1115                        key: pev.key,
1116                    },
1117                );
1118            }
1119            CLAP_EVENT_NOTE_ON
1120            | CLAP_EVENT_NOTE_OFF
1121            | CLAP_EVENT_NOTE_CHOKE
1122            | CLAP_EVENT_NOTE_END => {
1123                if !accept_note_event(notes.len(), true) {
1124                    continue;
1125                }
1126                let n = unsafe { &*(hdr as *const clap_event_note) };
1127                notes.push(NoteEvent {
1128                    sample_offset: header.time,
1129                    note_id: n.note_id,
1130                    port_index: n.port_index,
1131                    channel: n.channel,
1132                    key: n.key,
1133                    kind: match header.type_ {
1134                        CLAP_EVENT_NOTE_ON => NoteEventKind::On {
1135                            velocity: n.velocity,
1136                        },
1137                        CLAP_EVENT_NOTE_CHOKE => NoteEventKind::Choke,
1138                        CLAP_EVENT_NOTE_END => NoteEventKind::End,
1139                        _ => NoteEventKind::Off {
1140                            velocity: n.velocity,
1141                        },
1142                    },
1143                });
1144                if let Some(msg) = clap_note_to_midi(header.type_, hdr) {
1145                    midi.push(header.time, msg);
1146                }
1147            }
1148            CLAP_EVENT_NOTE_EXPRESSION => {
1149                if !accept_note_event(notes.len(), false) {
1150                    continue;
1151                }
1152                let e = unsafe { &*(hdr as *const clap_event_note_expression) };
1153                notes.push(NoteEvent {
1154                    sample_offset: header.time,
1155                    note_id: e.note_id,
1156                    port_index: e.port_index,
1157                    channel: e.channel,
1158                    key: e.key,
1159                    kind: NoteEventKind::Expression {
1160                        id: NoteExpression::from_clap(e.expression_id),
1161                        value: e.value,
1162                    },
1163                });
1164            }
1165            CLAP_EVENT_MIDI => {
1166                let m = unsafe { &*(hdr as *const clap_event_midi) };
1167                let msg = MidiMessage::raw(m.data[0], m.data[1], m.data[2]);
1168                midi.push(header.time, msg);
1169                if accept_note_event(ump.len(), msg.is_note_on() || msg.is_note_off()) {
1170                    ump.push(header.time, Ump::from_midi1(msg));
1171                }
1172            }
1173            CLAP_EVENT_MIDI2 => {
1174                let m = unsafe { &*(hdr as *const clap_event_midi2) };
1175                let packet = Ump::from_words(m.data);
1176                let essential = packet.is_note_on() || packet.is_note_off();
1177                if accept_note_event(ump.len(), essential) {
1178                    ump.push(header.time, packet);
1179                }
1180                if let Some(msg) = packet.to_midi1() {
1181                    midi.push(header.time, msg);
1182                }
1183            }
1184            _ => {}
1185        }
1186    }
1187}
1188
1189/// Apply all param events immediately (flush / no-audio path).
1190unsafe fn apply_input_events(
1191    params: &dyn Params,
1192    in_events: *const clap_input_events,
1193    midi: &mut MidiBuffer,
1194) {
1195    let mut timed = Vec::new();
1196    let mut tuning_events = Vec::new();
1197    let mut notes = NoteBuffer::new();
1198    let mut ump = UmpBuffer::new();
1199    unsafe {
1200        collect_input_events(
1201            in_events,
1202            &mut timed,
1203            &mut tuning_events,
1204            0,
1205            midi,
1206            &mut notes,
1207            &mut ump,
1208        );
1209    }
1210    let _ = (tuning_events, notes, ump); // ponytail: flush has no process() to consume these
1211    for ev in timed {
1212        aura_core::apply_event(params, ev);
1213    }
1214}
1215
1216/// Map CLAP note events into channel MIDI (velocity 0..=127).
1217fn clap_note_to_midi(type_: clap_event_type, hdr: *const clap_event_header) -> Option<MidiMessage> {
1218    let n = unsafe { &*(hdr as *const clap_event_note) };
1219    if n.key < 0 || n.key > 127 {
1220        return None;
1221    }
1222    let channel = if n.channel < 0 {
1223        0
1224    } else {
1225        (n.channel as u8) & 0x0F
1226    };
1227    let key = n.key as u8;
1228    let velocity = (n.velocity * 127.0).round().clamp(0.0, 127.0) as u8;
1229    match type_ {
1230        CLAP_EVENT_NOTE_ON => Some(MidiMessage::note_on(channel, key, velocity.max(1))),
1231        CLAP_EVENT_NOTE_OFF | CLAP_EVENT_NOTE_CHOKE => {
1232            Some(MidiMessage::note_off(channel, key, velocity))
1233        }
1234        _ => None,
1235    }
1236}
1237
1238fn event_header(type_: clap_event_type, size: u32) -> clap_event_header {
1239    clap_event_header {
1240        size,
1241        time: 0,
1242        space_id: CLAP_CORE_EVENT_SPACE_ID,
1243        type_,
1244        flags: CLAP_EVENT_IS_LIVE,
1245    }
1246}
1247
1248/// Push queued GUI param events to the host's `out_events` (process/flush).
1249unsafe fn emit_param_events(queue: &ParamEventQueue, out: *const clap_output_events) {
1250    if out.is_null() {
1251        return;
1252    }
1253    let Some(try_push) = (unsafe { &*out }).try_push else {
1254        return;
1255    };
1256    for ev in queue.drain() {
1257        match ev {
1258            ParamEvent::GestureBegin(param_id) | ParamEvent::GestureEnd(param_id) => {
1259                let type_ = if matches!(ev, ParamEvent::GestureBegin(_)) {
1260                    CLAP_EVENT_PARAM_GESTURE_BEGIN
1261                } else {
1262                    CLAP_EVENT_PARAM_GESTURE_END
1263                };
1264                let e = clap_event_param_gesture {
1265                    header: event_header(type_, size_of::<clap_event_param_gesture>() as u32),
1266                    param_id,
1267                };
1268                unsafe { try_push(out, &e as *const _ as *const clap_event_header) };
1269            }
1270            ParamEvent::Value { id, plain } => {
1271                let e = clap_event_param_value {
1272                    header: event_header(
1273                        CLAP_EVENT_PARAM_VALUE,
1274                        size_of::<clap_event_param_value>() as u32,
1275                    ),
1276                    param_id: id,
1277                    cookie: ptr::null_mut(),
1278                    note_id: -1,
1279                    port_index: -1,
1280                    channel: -1,
1281                    key: -1,
1282                    value: plain,
1283                };
1284                unsafe { try_push(out, &e as *const _ as *const clap_event_header) };
1285            }
1286        }
1287    }
1288}
1289
1290/// Push plugin-generated CLAP notes from [`ProcessContext::notes_out`].
1291unsafe fn emit_note_events_at(out: *const clap_output_events, notes: &NoteBuffer, base: u32) {
1292    if out.is_null() || notes.is_empty() {
1293        return;
1294    }
1295    let Some(try_push) = (unsafe { &*out }).try_push else {
1296        return;
1297    };
1298    for ev in notes.iter() {
1299        let time = ev.sample_offset.saturating_add(base);
1300        match ev.kind {
1301            NoteEventKind::On { .. }
1302            | NoteEventKind::Off { .. }
1303            | NoteEventKind::Choke
1304            | NoteEventKind::End => {
1305                let type_ = match ev.kind {
1306                    NoteEventKind::On { .. } => CLAP_EVENT_NOTE_ON,
1307                    NoteEventKind::Off { .. } => CLAP_EVENT_NOTE_OFF,
1308                    NoteEventKind::Choke => CLAP_EVENT_NOTE_CHOKE,
1309                    _ => CLAP_EVENT_NOTE_END,
1310                };
1311                let velocity = match ev.kind {
1312                    NoteEventKind::On { velocity } | NoteEventKind::Off { velocity } => velocity,
1313                    _ => 0.0,
1314                };
1315                let mut e = clap_event_note {
1316                    header: event_header(type_, size_of::<clap_event_note>() as u32),
1317                    note_id: ev.note_id,
1318                    port_index: -1,
1319                    channel: ev.channel,
1320                    key: ev.key,
1321                    velocity,
1322                };
1323                e.header.time = time;
1324                unsafe { try_push(out, &e as *const _ as *const clap_event_header) };
1325            }
1326            NoteEventKind::Expression { id, value } => {
1327                let mut e = clap_event_note_expression {
1328                    header: event_header(
1329                        CLAP_EVENT_NOTE_EXPRESSION,
1330                        size_of::<clap_event_note_expression>() as u32,
1331                    ),
1332                    expression_id: id.to_clap(),
1333                    note_id: ev.note_id,
1334                    port_index: ev.port_index,
1335                    channel: ev.channel,
1336                    key: ev.key,
1337                    value,
1338                };
1339                e.header.time = time;
1340                unsafe { try_push(out, &e as *const _ as *const clap_event_header) };
1341            }
1342            NoteEventKind::ParamMod { .. } | NoteEventKind::ParamValue { .. } => {}
1343        }
1344    }
1345}
1346
1347/// Push plugin-generated UMP from [`ProcessContext::ump_out`] as `CLAP_EVENT_MIDI2`.
1348unsafe fn emit_ump_events_at(out: *const clap_output_events, ump: &UmpBuffer, base: u32) {
1349    if out.is_null() || ump.is_empty() {
1350        return;
1351    }
1352    let Some(try_push) = (unsafe { &*out }).try_push else {
1353        return;
1354    };
1355    for ev in ump.iter() {
1356        let mut e = clap_event_midi2 {
1357            header: event_header(CLAP_EVENT_MIDI2, size_of::<clap_event_midi2>() as u32),
1358            port_index: 0,
1359            data: ev.packet.words(),
1360        };
1361        e.header.time = ev.sample_offset.saturating_add(base);
1362        unsafe { try_push(out, &e as *const _ as *const clap_event_header) };
1363    }
1364}
1365
1366/// Push plugin-generated MIDI events from [`ProcessContext::midi_out`] to the host.
1367/// `base` is added to each sample offset (0 for a full-block chunk).
1368unsafe fn emit_midi_events_at(out: *const clap_output_events, midi: &MidiBuffer, base: u32) {
1369    if out.is_null() || midi.is_empty() {
1370        return;
1371    }
1372    let Some(try_push) = (unsafe { &*out }).try_push else {
1373        return;
1374    };
1375    for ev in midi.iter() {
1376        let time = ev.sample_offset.saturating_add(base);
1377        // Always raw `CLAP_EVENT_MIDI`. Note FX chains (Bitwig) forward MIDI
1378        // dialect; converting On/Off to `CLAP_EVENT_NOTE_*` here dropped them.
1379        let mut e = clap_event_midi {
1380            header: event_header(CLAP_EVENT_MIDI, size_of::<clap_event_midi>() as u32),
1381            port_index: 0,
1382            data: [ev.message.status_byte(), ev.message.data1, ev.message.data2],
1383        };
1384        e.header.time = time;
1385        unsafe { try_push(out, &e as *const _ as *const clap_event_header) };
1386    }
1387}
1388
1389fn map_transport(t: &clap_event_transport) -> Transport {
1390    use clap_sys::fixedpoint::{CLAP_BEATTIME_FACTOR, CLAP_SECTIME_FACTOR};
1391    // CLAP beat/sec times are i64 fixed point (factor 2^31).
1392    #[allow(clippy::cast_precision_loss)]
1393    let beat = |v: i64| v as f64 / CLAP_BEATTIME_FACTOR as f64;
1394    #[allow(clippy::cast_precision_loss)]
1395    let sec = |v: i64| v as f64 / CLAP_SECTIME_FACTOR as f64;
1396    let f = t.flags;
1397    let beats = f & CLAP_TRANSPORT_HAS_BEATS_TIMELINE != 0;
1398    Transport {
1399        playing: f & CLAP_TRANSPORT_IS_PLAYING != 0,
1400        recording: f & CLAP_TRANSPORT_IS_RECORDING != 0,
1401        loop_active: f & CLAP_TRANSPORT_IS_LOOP_ACTIVE != 0,
1402        tempo: (f & CLAP_TRANSPORT_HAS_TEMPO != 0).then_some(t.tempo),
1403        position_beats: beats.then_some(beat(t.song_pos_beats)),
1404        position_seconds: (f & CLAP_TRANSPORT_HAS_SECONDS_TIMELINE != 0)
1405            .then_some(sec(t.song_pos_seconds)),
1406        loop_beats: beats.then_some((beat(t.loop_start_beats), beat(t.loop_end_beats))),
1407        time_signature: (f & CLAP_TRANSPORT_HAS_TIME_SIGNATURE != 0)
1408            .then_some((t.tsig_num, t.tsig_denom)),
1409        bar_number: beats.then_some(t.bar_number),
1410    }
1411}
1412
1413unsafe extern "C" fn plugin_get_extension<L: PluginLogic>(
1414    plugin: *const clap_plugin,
1415    id: *const c_char,
1416) -> *const c_void {
1417    if id.is_null() {
1418        return ptr::null();
1419    }
1420    let id = unsafe { CStr::from_ptr(id) };
1421    if id == CLAP_EXT_AUDIO_PORTS {
1422        return audio_ports_ext::<L>() as *const _ as *const c_void;
1423    }
1424    if id == CLAP_EXT_AUDIO_PORTS_CONFIG && L::bus_layouts().len() > 1 {
1425        return audio_ports_config_ext::<L>() as *const _ as *const c_void;
1426    }
1427    if id == CLAP_EXT_PARAMS {
1428        return params_ext::<L>() as *const _ as *const c_void;
1429    }
1430    if id == CLAP_EXT_REMOTE_CONTROLS || id == CLAP_EXT_REMOTE_CONTROLS_COMPAT {
1431        return remote_controls_ext::<L>() as *const _ as *const c_void;
1432    }
1433    if id == CLAP_EXT_LATENCY {
1434        return latency_ext::<L>() as *const _ as *const c_void;
1435    }
1436    if id == CLAP_EXT_TAIL {
1437        return tail_ext::<L>() as *const _ as *const c_void;
1438    }
1439    if id == CLAP_EXT_RENDER {
1440        return render_ext::<L>() as *const _ as *const c_void;
1441    }
1442    if id == CLAP_EXT_NOTE_PORTS {
1443        let info = L::info();
1444        if info.accepts_midi_in || info.emits_midi {
1445            return note_ports_ext::<L>() as *const _ as *const c_void;
1446        }
1447        return ptr::null();
1448    }
1449    if id == CLAP_EXT_VOICE_INFO && L::info().voice_count > 0 {
1450        return voice_info_ext::<L>() as *const _ as *const c_void;
1451    }
1452    if id == CLAP_EXT_STATE {
1453        return state_ext::<L>() as *const _ as *const c_void;
1454    }
1455    if preset_load::is_preset_load_ext(id) {
1456        return preset_load::preset_load_ext::<L>() as *const _ as *const c_void;
1457    }
1458    if id == CLAP_EXT_GUI {
1459        // No GUI extension when the plugin has no editor.
1460        let has_editor =
1461            unsafe { Instance::<L>::from_plugin(plugin) }.is_some_and(|inst| inst.editor.is_some());
1462        if has_editor {
1463            return gui_ext::<L>() as *const _ as *const c_void;
1464        }
1465        return ptr::null();
1466    }
1467    if id == CLAP_EXT_TUNING && L::info().supports_tuning {
1468        return tuning::tuning_ext::<L>() as *const _ as *const c_void;
1469    }
1470    if id == CLAP_EXT_NOTE_NAME && !L::note_names().is_empty() {
1471        return note_name_ext::<L>() as *const _ as *const c_void;
1472    }
1473    if id == CLAP_EXT_PARAM_INDICATION || id == CLAP_EXT_PARAM_INDICATION_COMPAT {
1474        return param_indication_ext::<L>() as *const _ as *const c_void;
1475    }
1476    ptr::null()
1477}
1478
1479unsafe extern "C" fn plugin_on_main_thread<L: PluginLogic>(plugin: *const clap_plugin) {
1480    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1481        return;
1482    };
1483    if !inst.latency_dirty.swap(false, Ordering::Relaxed) {
1484        return;
1485    }
1486    // Mid-run latency change: notify + restart so the host re-activates
1487    // and re-reads get() for PDC (free-audio: change only during activate,
1488    // otherwise request_restart).
1489    host_latency_changed(inst.host);
1490    host_request_restart(inst.host);
1491}
1492
1493// ---------------------------------------------------------------------------
1494// latency (PDC)
1495// ---------------------------------------------------------------------------
1496
1497fn latency_ext<L: PluginLogic>() -> &'static clap_plugin_latency {
1498    static CELL: OnceLock<clap_plugin_latency> = OnceLock::new();
1499    CELL.get_or_init(|| clap_plugin_latency {
1500        get: Some(latency_get::<L>),
1501    })
1502}
1503
1504unsafe extern "C" fn latency_get<L: PluginLogic>(plugin: *const clap_plugin) -> u32 {
1505    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1506        return 0;
1507    };
1508    inst.latency_cache.load(Ordering::Relaxed)
1509}
1510
1511// ---------------------------------------------------------------------------
1512// tail
1513// ---------------------------------------------------------------------------
1514
1515fn tail_ext<L: PluginLogic>() -> &'static clap_plugin_tail {
1516    static CELL: OnceLock<clap_plugin_tail> = OnceLock::new();
1517    CELL.get_or_init(|| clap_plugin_tail {
1518        get: Some(tail_get::<L>),
1519    })
1520}
1521
1522unsafe extern "C" fn tail_get<L: PluginLogic>(plugin: *const clap_plugin) -> u32 {
1523    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1524        return 0;
1525    };
1526    inst.tail_cache.load(Ordering::Relaxed)
1527}
1528
1529// ---------------------------------------------------------------------------
1530// render (realtime vs offline)
1531// ---------------------------------------------------------------------------
1532
1533fn render_ext<L: PluginLogic>() -> &'static clap_plugin_render {
1534    static CELL: OnceLock<clap_plugin_render> = OnceLock::new();
1535    CELL.get_or_init(|| clap_plugin_render {
1536        has_hard_realtime_requirement: Some(render_hard_rt),
1537        set: Some(render_set::<L>),
1538    })
1539}
1540
1541unsafe extern "C" fn render_hard_rt(_plugin: *const clap_plugin) -> bool {
1542    // Authors can oversample offline; we never *require* hard realtime exclusivity.
1543    false
1544}
1545
1546unsafe extern "C" fn render_set<L: PluginLogic>(
1547    plugin: *const clap_plugin,
1548    mode: clap_plugin_render_mode,
1549) -> bool {
1550    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1551        return false;
1552    };
1553    inst.process_mode = match mode {
1554        CLAP_RENDER_OFFLINE => ProcessMode::Offline,
1555        _ => ProcessMode::Realtime, // CLAP_RENDER_REALTIME and unknown
1556    };
1557    let _ = CLAP_RENDER_REALTIME; // silence unused when matched via `_`
1558    true
1559}
1560
1561// ---------------------------------------------------------------------------
1562// note-ports (MIDI / note input + output)
1563// ---------------------------------------------------------------------------
1564
1565fn note_ports_ext<L: PluginLogic>() -> &'static clap_plugin_note_ports {
1566    static CELL: OnceLock<clap_plugin_note_ports> = OnceLock::new();
1567    CELL.get_or_init(|| clap_plugin_note_ports {
1568        count: Some(note_ports_count::<L>),
1569        get: Some(note_ports_get::<L>),
1570    })
1571}
1572
1573unsafe extern "C" fn note_ports_count<L: PluginLogic>(
1574    _plugin: *const clap_plugin,
1575    is_input: bool,
1576) -> u32 {
1577    let info = L::info();
1578    if is_input {
1579        u32::from(info.accepts_midi_in)
1580    } else {
1581        u32::from(info.emits_midi)
1582    }
1583}
1584
1585unsafe extern "C" fn note_ports_get<L: PluginLogic>(
1586    _plugin: *const clap_plugin,
1587    index: u32,
1588    is_input: bool,
1589    info: *mut clap_note_port_info,
1590) -> bool {
1591    if index != 0 || info.is_null() {
1592        return false;
1593    }
1594    let meta = L::info();
1595    let dialect = if is_input {
1596        meta.midi_input_dialect
1597    } else {
1598        meta.midi_output_dialect
1599    };
1600    let dialects = match dialect {
1601        aura_core::info::MidiDialect::Clap | aura_core::info::MidiDialect::Midi2 => {
1602            CLAP_NOTE_DIALECT_CLAP | CLAP_NOTE_DIALECT_MIDI | CLAP_NOTE_DIALECT_MIDI2
1603        }
1604        aura_core::info::MidiDialect::Midi1 => CLAP_NOTE_DIALECT_CLAP | CLAP_NOTE_DIALECT_MIDI,
1605    };
1606    let out = unsafe { &mut *info };
1607    // Same id in both directions so output events with port_index 0 match.
1608    // Distinct ids (out=1) made Bitwig Note-FX drop our emits.
1609    out.id = 0;
1610    out.supported_dialects = dialects;
1611    out.preferred_dialect = match dialect {
1612        aura_core::info::MidiDialect::Clap => CLAP_NOTE_DIALECT_CLAP,
1613        aura_core::info::MidiDialect::Midi2 => CLAP_NOTE_DIALECT_MIDI2,
1614        aura_core::info::MidiDialect::Midi1 => CLAP_NOTE_DIALECT_MIDI,
1615    };
1616    write_name(&mut out.name, if is_input { "Note In" } else { "Note Out" });
1617    true
1618}
1619
1620// ---------------------------------------------------------------------------
1621// voice-info (Bitwig Voice Stack / poly-mod needs a voice pool > 1)
1622// ---------------------------------------------------------------------------
1623
1624fn note_name_ext<L: PluginLogic>() -> &'static clap_plugin_note_name {
1625    static CELL: OnceLock<clap_plugin_note_name> = OnceLock::new();
1626    CELL.get_or_init(|| clap_plugin_note_name {
1627        count: Some(note_name_count::<L>),
1628        get: Some(note_name_get::<L>),
1629    })
1630}
1631
1632unsafe extern "C" fn note_name_count<L: PluginLogic>(_plugin: *const clap_plugin) -> u32 {
1633    L::note_names().len() as u32
1634}
1635
1636unsafe extern "C" fn note_name_get<L: PluginLogic>(
1637    _plugin: *const clap_plugin,
1638    index: u32,
1639    out: *mut clap_sys::ext::note_name::clap_note_name,
1640) -> bool {
1641    let names = L::note_names();
1642    let Some(entry) = names.get(index as usize) else {
1643        return false;
1644    };
1645    if out.is_null() {
1646        return false;
1647    }
1648    let out = unsafe { &mut *out };
1649    out.port = entry.port;
1650    out.channel = entry.channel;
1651    out.key = entry.key;
1652    let bytes = entry.name.as_bytes();
1653    let len = bytes.len().min(clap_sys::string_sizes::CLAP_NAME_SIZE - 1);
1654    for (i, &b) in bytes.iter().take(len).enumerate() {
1655        out.name[i] = b as std::ffi::c_char;
1656    }
1657    out.name[len] = 0;
1658    true
1659}
1660
1661fn param_indication_ext<L: PluginLogic>() -> &'static clap_plugin_param_indication {
1662    static CELL: OnceLock<clap_plugin_param_indication> = OnceLock::new();
1663    CELL.get_or_init(|| clap_plugin_param_indication {
1664        set_mapping: Some(param_indication_set_mapping::<L>),
1665        set_automation: Some(param_indication_set_automation::<L>),
1666    })
1667}
1668
1669unsafe extern "C" fn param_indication_set_mapping<L: PluginLogic>(
1670    plugin: *const clap_plugin,
1671    param_id: clap_id,
1672    has_mapping: bool,
1673    _color: *const clap_sys::color::clap_color,
1674    _label: *const std::ffi::c_char,
1675    _description: *const std::ffi::c_char,
1676) {
1677    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1678        return;
1679    };
1680    L::on_param_mapping(&inst.params, param_id, has_mapping);
1681}
1682
1683unsafe extern "C" fn param_indication_set_automation<L: PluginLogic>(
1684    plugin: *const clap_plugin,
1685    param_id: clap_id,
1686    automation_state: u32,
1687    _color: *const clap_sys::color::clap_color,
1688) {
1689    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1690        return;
1691    };
1692    L::on_param_automation(&inst.params, param_id, automation_state);
1693}
1694
1695fn voice_info_ext<L: PluginLogic>() -> &'static clap_plugin_voice_info {
1696    static CELL: OnceLock<clap_plugin_voice_info> = OnceLock::new();
1697    CELL.get_or_init(|| clap_plugin_voice_info {
1698        get: Some(voice_info_get::<L>),
1699    })
1700}
1701
1702unsafe extern "C" fn voice_info_get<L: PluginLogic>(
1703    _plugin: *const clap_plugin,
1704    info: *mut clap_voice_info,
1705) -> bool {
1706    if info.is_null() {
1707        return false;
1708    }
1709    let meta = L::info();
1710    if meta.voice_count == 0 {
1711        return false;
1712    }
1713    let cap = meta.voice_capacity.max(meta.voice_count);
1714    let out = unsafe { &mut *info };
1715    out.voice_count = meta.voice_count.min(cap);
1716    out.voice_capacity = cap;
1717    out.flags = CLAP_VOICE_INFO_SUPPORTS_OVERLAPPING_NOTES;
1718    true
1719}
1720
1721// ---------------------------------------------------------------------------
1722// audio-ports (main in/out from selected BusLayout)
1723// ---------------------------------------------------------------------------
1724
1725fn clap_port_type(channels: ChannelConfig) -> *const c_char {
1726    match channels {
1727        ChannelConfig::Mono => CLAP_PORT_MONO.as_ptr(),
1728        ChannelConfig::Stereo => CLAP_PORT_STEREO.as_ptr(),
1729    }
1730}
1731
1732fn audio_ports_ext<L: PluginLogic>() -> &'static clap_plugin_audio_ports {
1733    static CELL: OnceLock<clap_plugin_audio_ports> = OnceLock::new();
1734    CELL.get_or_init(|| clap_plugin_audio_ports {
1735        count: Some(audio_ports_count::<L>),
1736        get: Some(audio_ports_get::<L>),
1737    })
1738}
1739
1740unsafe extern "C" fn audio_ports_count<L: PluginLogic>(
1741    plugin: *const clap_plugin,
1742    is_input: bool,
1743) -> u32 {
1744    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1745        return 0;
1746    };
1747    let layout = inst.selected_layout();
1748    if is_input {
1749        layout.input_port_count()
1750    } else {
1751        layout.output_port_count()
1752    }
1753}
1754
1755unsafe extern "C" fn audio_ports_get<L: PluginLogic>(
1756    plugin: *const clap_plugin,
1757    index: u32,
1758    is_input: bool,
1759    info: *mut clap_audio_port_info,
1760) -> bool {
1761    if info.is_null() {
1762        return false;
1763    }
1764    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1765        return false;
1766    };
1767    let layout = inst.selected_layout();
1768    let (channels, name, is_main, id) = if is_input {
1769        let main_count = u32::from(layout.main_in.is_some());
1770        if index == 0 && main_count == 1 {
1771            let Some(ch) = layout.main_in else {
1772                return false;
1773            };
1774            (ch, "Input", true, 0)
1775        } else if index < layout.input_port_count() {
1776            let Some(ch) = layout.sidechain_in else {
1777                return false;
1778            };
1779            (ch, "Sidechain", false, 1)
1780        } else {
1781            return false;
1782        }
1783    } else if index == 0 {
1784        (layout.main_out, "Output", true, 0)
1785    } else if index == 1 {
1786        let Some(ch) = layout.aux_out else {
1787            return false;
1788        };
1789        (ch, "Aux", false, 1)
1790    } else {
1791        return false;
1792    };
1793    let info = unsafe { &mut *info };
1794    info.id = id;
1795    write_name(&mut info.name, name);
1796    info.flags = if is_main { CLAP_AUDIO_PORT_IS_MAIN } else { 0 };
1797    info.channel_count = channels.channel_count();
1798    info.port_type = clap_port_type(channels);
1799    info.in_place_pair = CLAP_INVALID_ID;
1800    true
1801}
1802
1803// ---------------------------------------------------------------------------
1804// audio-ports-config (when bus_layouts().len() > 1)
1805// ---------------------------------------------------------------------------
1806
1807fn audio_ports_config_ext<L: PluginLogic>() -> &'static clap_plugin_audio_ports_config {
1808    static CELL: OnceLock<clap_plugin_audio_ports_config> = OnceLock::new();
1809    CELL.get_or_init(|| clap_plugin_audio_ports_config {
1810        count: Some(audio_ports_config_count::<L>),
1811        get: Some(audio_ports_config_get::<L>),
1812        select: Some(audio_ports_config_select::<L>),
1813    })
1814}
1815
1816unsafe extern "C" fn audio_ports_config_count<L: PluginLogic>(_plugin: *const clap_plugin) -> u32 {
1817    L::bus_layouts().len() as u32
1818}
1819
1820unsafe extern "C" fn audio_ports_config_get<L: PluginLogic>(
1821    _plugin: *const clap_plugin,
1822    index: u32,
1823    config: *mut clap_audio_ports_config,
1824) -> bool {
1825    if config.is_null() {
1826        return false;
1827    }
1828    let layouts = L::bus_layouts();
1829    let Some(layout) = layouts.get(index as usize).copied() else {
1830        return false;
1831    };
1832    let out = unsafe { &mut *config };
1833    out.id = index;
1834    write_name(&mut out.name, &layout.config_name());
1835    out.input_port_count = layout.input_port_count();
1836    out.output_port_count = layout.output_port_count();
1837    out.has_main_input = layout.main_in.is_some();
1838    out.main_input_channel_count = layout.main_input_channels();
1839    out.main_input_port_type = layout.main_in.map_or(ptr::null(), clap_port_type);
1840    out.has_main_output = true;
1841    out.main_output_channel_count = layout.main_output_channels();
1842    out.main_output_port_type = clap_port_type(layout.main_out);
1843    true
1844}
1845
1846unsafe extern "C" fn audio_ports_config_select<L: PluginLogic>(
1847    plugin: *const clap_plugin,
1848    config_id: clap_id,
1849) -> bool {
1850    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1851        return false;
1852    };
1853    if inst.active {
1854        // Spec: select only while deactivated.
1855        return false;
1856    }
1857    let n = L::bus_layouts().len();
1858    if (config_id as usize) >= n {
1859        return false;
1860    }
1861    inst.layout_index = config_id as usize;
1862    true
1863}
1864
1865// ---------------------------------------------------------------------------
1866// remote-controls (device pages from ParamInfo.group)
1867// ---------------------------------------------------------------------------
1868//
1869// free-audio: clap.remote-controls/2 — up to 8 param slots per page, sections
1870// cycle through pages. We map `ParamInfo.group` to pages:
1871// - empty group → no remote page (host generic param list still has the param)
1872// - `"Section/Page"` → section + page names (first `/` only)
1873// - `"Section"` alone → section and page share the same name
1874// - >8 params in one group → multiple pages (chunk index in stable page_id)
1875// - HIDDEN / READONLY never consume a scarce hardware slot
1876
1877/// Split `group` on the first `/` into `(section_name, page_name)`.
1878fn split_group(group: &str) -> (&str, &str) {
1879    match group.split_once('/') {
1880        Some((section, page)) => (section, page),
1881        None => (group, group),
1882    }
1883}
1884
1885/// Chunk params into remote-control pages (≤8 ids each), one run per
1886/// distinct non-empty `ParamInfo.group` (declaration order).
1887fn remote_control_pages(infos: &[ParamInfo]) -> Vec<(&str, Vec<u32>)> {
1888    let mut pages: Vec<(&str, Vec<u32>)> = Vec::new();
1889    for info in infos {
1890        if info.group.is_empty()
1891            || info
1892                .flags
1893                .intersects(ParamFlags::HIDDEN | ParamFlags::READONLY)
1894        {
1895            continue;
1896        }
1897        let existing = pages
1898            .iter()
1899            .rposition(|page| page.0 == info.group && page.1.len() < CLAP_REMOTE_CONTROLS_COUNT);
1900        match existing {
1901            Some(idx) => pages[idx].1.push(info.id),
1902            None => pages.push((info.group, vec![info.id])),
1903        }
1904    }
1905    pages
1906}
1907
1908/// Stable FNV-1a page id from group name + chunk index (host may persist
1909/// the user's last page; must not depend on process-local hashers).
1910fn remote_controls_page_id(group: &str, chunk_index: usize) -> clap_id {
1911    let mut hash: u32 = 0x811c_9dc5;
1912    for &b in group.as_bytes() {
1913        hash ^= u32::from(b);
1914        hash = hash.wrapping_mul(0x0100_0193);
1915    }
1916    for &b in &chunk_index.to_le_bytes() {
1917        hash ^= u32::from(b);
1918        hash = hash.wrapping_mul(0x0100_0193);
1919    }
1920    hash
1921}
1922
1923fn remote_controls_ext<L: PluginLogic>() -> &'static clap_plugin_remote_controls {
1924    static CELL: OnceLock<clap_plugin_remote_controls> = OnceLock::new();
1925    CELL.get_or_init(|| clap_plugin_remote_controls {
1926        count: Some(remote_controls_count::<L>),
1927        get: Some(remote_controls_get::<L>),
1928    })
1929}
1930
1931unsafe extern "C" fn remote_controls_count<L: PluginLogic>(plugin: *const clap_plugin) -> u32 {
1932    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1933        return 0;
1934    };
1935    let infos = inst.params.param_infos();
1936    remote_control_pages(&infos).len() as u32
1937}
1938
1939unsafe extern "C" fn remote_controls_get<L: PluginLogic>(
1940    plugin: *const clap_plugin,
1941    page_index: u32,
1942    out: *mut clap_remote_controls_page,
1943) -> bool {
1944    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1945        return false;
1946    };
1947    if out.is_null() {
1948        return false;
1949    }
1950    let infos = inst.params.param_infos();
1951    let pages = remote_control_pages(&infos);
1952    let page_index = page_index as usize;
1953    if page_index >= pages.len() {
1954        return false;
1955    }
1956    let group = pages[page_index].0;
1957    let ids = &pages[page_index].1;
1958    let chunk_index = pages[..page_index]
1959        .iter()
1960        .filter(|page| page.0 == group)
1961        .count();
1962    let (section_name, page_name) = split_group(group);
1963
1964    let out = unsafe { &mut *out };
1965    write_name(&mut out.section_name, section_name);
1966    out.page_id = remote_controls_page_id(group, chunk_index);
1967    write_name(&mut out.page_name, page_name);
1968    out.param_ids = [CLAP_INVALID_ID; CLAP_REMOTE_CONTROLS_COUNT];
1969    for (slot, &id) in out.param_ids.iter_mut().zip(ids.iter()) {
1970        *slot = id;
1971    }
1972    out.is_for_preset = false;
1973    true
1974}
1975
1976// ---------------------------------------------------------------------------
1977// params
1978// ---------------------------------------------------------------------------
1979
1980fn params_ext<L: PluginLogic>() -> &'static clap_plugin_params {
1981    static CELL: OnceLock<clap_plugin_params> = OnceLock::new();
1982    CELL.get_or_init(|| clap_plugin_params {
1983        count: Some(params_count::<L>),
1984        get_info: Some(params_get_info::<L>),
1985        get_value: Some(params_get_value::<L>),
1986        value_to_text: Some(params_value_to_text::<L>),
1987        text_to_value: Some(params_text_to_value::<L>),
1988        flush: Some(params_flush::<L>),
1989    })
1990}
1991
1992unsafe extern "C" fn params_count<L: PluginLogic>(plugin: *const clap_plugin) -> u32 {
1993    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
1994        return 0;
1995    };
1996    inst.params.count() as u32
1997}
1998
1999unsafe extern "C" fn params_get_info<L: PluginLogic>(
2000    plugin: *const clap_plugin,
2001    param_index: u32,
2002    param_info: *mut clap_param_info,
2003) -> bool {
2004    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2005        return false;
2006    };
2007    if param_info.is_null() {
2008        return false;
2009    }
2010    let infos = inst.params.param_infos();
2011    let Some(meta) = infos.get(param_index as usize) else {
2012        return false;
2013    };
2014    let out = unsafe { &mut *param_info };
2015    out.id = meta.id;
2016    out.flags = map_param_flags(meta.flags, &meta.range);
2017    out.cookie = ptr::null_mut();
2018    write_name(&mut out.name, meta.name);
2019    write_path(&mut out.module, meta.group);
2020    out.min_value = meta.range.min();
2021    out.max_value = meta.range.max();
2022    out.default_value = meta.default_plain;
2023    true
2024}
2025
2026unsafe extern "C" fn params_get_value<L: PluginLogic>(
2027    plugin: *const clap_plugin,
2028    param_id: u32,
2029    out_value: *mut f64,
2030) -> bool {
2031    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2032        return false;
2033    };
2034    if out_value.is_null() {
2035        return false;
2036    }
2037    match inst.params.get_plain(param_id) {
2038        Some(v) => {
2039            unsafe { *out_value = v };
2040            true
2041        }
2042        None => false,
2043    }
2044}
2045
2046unsafe extern "C" fn params_value_to_text<L: PluginLogic>(
2047    plugin: *const clap_plugin,
2048    param_id: u32,
2049    value: f64,
2050    out_buffer: *mut c_char,
2051    out_buffer_capacity: u32,
2052) -> bool {
2053    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2054        return false;
2055    };
2056    if out_buffer.is_null() || out_buffer_capacity == 0 {
2057        return false;
2058    }
2059    let text = inst
2060        .params
2061        .format_value(param_id, value)
2062        .unwrap_or_else(|| format!("{value:.2}"));
2063    write_c_buf(out_buffer, out_buffer_capacity as usize, &text)
2064}
2065
2066unsafe extern "C" fn params_text_to_value<L: PluginLogic>(
2067    plugin: *const clap_plugin,
2068    param_id: u32,
2069    param_value_text: *const c_char,
2070    out_value: *mut f64,
2071) -> bool {
2072    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2073        return false;
2074    };
2075    if param_value_text.is_null() || out_value.is_null() {
2076        return false;
2077    }
2078    let text = unsafe { CStr::from_ptr(param_value_text) }.to_string_lossy();
2079    match inst.params.parse_value(param_id, &text) {
2080        Some(v) => {
2081            unsafe { *out_value = v };
2082            true
2083        }
2084        None => false,
2085    }
2086}
2087
2088unsafe extern "C" fn params_flush<L: PluginLogic>(
2089    plugin: *const clap_plugin,
2090    in_: *const clap_input_events,
2091    out: *const clap_output_events,
2092) {
2093    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2094        return;
2095    };
2096    if !in_.is_null() {
2097        // Flush is param-only; MIDI discarded (no process block).
2098        let mut midi = MidiBuffer::new();
2099        unsafe { apply_input_events(&*inst.params, in_, &mut midi) };
2100    }
2101    unsafe { emit_param_events(&inst.param_events, out) };
2102}
2103
2104// ---------------------------------------------------------------------------
2105// gui
2106// ---------------------------------------------------------------------------
2107
2108/// Host bridge for the editor: param store + `clap_host_gui.request_resize`.
2109///
2110/// Param edits land in the store immediately (audio reads them next block)
2111/// and are queued as CLAP gesture/value events for the host's automation.
2112struct ClapBridge {
2113    params: Arc<dyn Params>,
2114    events: Arc<ParamEventQueue>,
2115    host: *const clap_host,
2116    /// Same cell as [`Instance::host_scale`] — logical→physical for resize.
2117    host_scale: Arc<AtomicU64>,
2118}
2119
2120// SAFETY: used from the GUI thread only; `host` is valid for the plugin
2121// lifetime and `clap_host_gui` calls are main-thread per CLAP spec.
2122unsafe impl Send for ClapBridge {}
2123unsafe impl Sync for ClapBridge {}
2124
2125impl ClapBridge {
2126    fn host_gui(&self) -> Option<&clap_host_gui> {
2127        if self.host.is_null() {
2128            return None;
2129        }
2130        let get = unsafe { (*self.host).get_extension? };
2131        let ext = unsafe { get(self.host, CLAP_EXT_GUI.as_ptr()) };
2132        if ext.is_null() {
2133            None
2134        } else {
2135            Some(unsafe { &*(ext as *const clap_host_gui) })
2136        }
2137    }
2138
2139    fn host_scale(&self) -> f64 {
2140        f64::from_bits(self.host_scale.load(Ordering::Relaxed))
2141    }
2142}
2143
2144impl EditorBridge for ClapBridge {
2145    fn begin_edit(&self, id: u32) {
2146        self.events.push(ParamEvent::GestureBegin(id));
2147    }
2148
2149    fn set_param(&self, id: u32, normalized: f64) {
2150        self.params.set_normalized(id, normalized);
2151        if let Some(plain) = self.params.get_plain(id) {
2152            self.events.push(ParamEvent::Value { id, plain });
2153        }
2154    }
2155
2156    fn end_edit(&self, id: u32) {
2157        self.events.push(ParamEvent::GestureEnd(id));
2158    }
2159
2160    fn get_param(&self, id: u32) -> f64 {
2161        self.params.get_normalized(id).unwrap_or(0.0)
2162    }
2163
2164    fn get_param_plain(&self, id: u32) -> f64 {
2165        self.params.get_plain(id).unwrap_or(0.0)
2166    }
2167
2168    fn request_resize(&self, w: u32, h: u32) -> bool {
2169        let Some(rr) = self.host_gui().and_then(|gui| gui.request_resize) else {
2170            return false;
2171        };
2172        // Editor API is logical; CLAP host on Win/Linux expects physical
2173        // pixels (same units as `gui_get_size`). macOS stays logical.
2174        let (pw, ph) = gui_logical_to_host_px(w, h, self.host_scale());
2175        unsafe { rr(self.host, pw, ph) }
2176    }
2177
2178    fn set_scale_hint(&self, scale: f64) {
2179        // Writes the same cell `gui_get_size` / `request_resize` read, so a
2180        // Windows host that never called `gui.set_scale` (Bitwig) still gets a
2181        // frame size = logical × real OS DPI, matching the rendered child.
2182        if scale.is_finite() && scale > 0.0 {
2183            self.host_scale.store(scale.to_bits(), Ordering::Relaxed);
2184        }
2185    }
2186}
2187
2188/// Logical editor size → host GUI pixels (Win/Linux × `host_scale`; macOS identity).
2189fn gui_logical_to_host_px(lw: u32, lh: u32, host_scale: f64) -> (u32, u32) {
2190    #[cfg(target_os = "macos")]
2191    {
2192        let _ = host_scale;
2193        (lw.max(1), lh.max(1))
2194    }
2195    #[cfg(not(target_os = "macos"))]
2196    {
2197        scale_logical_to_physical(lw, lh, host_scale)
2198    }
2199}
2200
2201/// Host GUI pixels → logical editor size (inverse of [`gui_logical_to_host_px`]).
2202fn gui_host_px_to_logical(pw: u32, ph: u32, host_scale: f64) -> (u32, u32) {
2203    #[cfg(target_os = "macos")]
2204    {
2205        let _ = host_scale;
2206        (pw.max(1), ph.max(1))
2207    }
2208    #[cfg(not(target_os = "macos"))]
2209    {
2210        scale_physical_to_logical(pw, ph, host_scale)
2211    }
2212}
2213
2214fn scale_logical_to_physical(lw: u32, lh: u32, host_scale: f64) -> (u32, u32) {
2215    if !host_scale.is_finite() || host_scale <= 0.0 || (host_scale - 1.0).abs() < f64::EPSILON {
2216        return (lw.max(1), lh.max(1));
2217    }
2218    let pw = (f64::from(lw.max(1)) * host_scale).round().max(1.0) as u32;
2219    let ph = (f64::from(lh.max(1)) * host_scale).round().max(1.0) as u32;
2220    (pw, ph)
2221}
2222
2223fn scale_physical_to_logical(pw: u32, ph: u32, host_scale: f64) -> (u32, u32) {
2224    if !host_scale.is_finite() || host_scale <= 0.0 || (host_scale - 1.0).abs() < f64::EPSILON {
2225        return (pw.max(1), ph.max(1));
2226    }
2227    let lw = (f64::from(pw.max(1)) / host_scale).round().max(1.0) as u32;
2228    let lh = (f64::from(ph.max(1)) / host_scale).round().max(1.0) as u32;
2229    (lw, lh)
2230}
2231
2232fn platform_window_api() -> &'static CStr {
2233    if cfg!(target_os = "windows") {
2234        CLAP_WINDOW_API_WIN32
2235    } else if cfg!(target_os = "macos") {
2236        CLAP_WINDOW_API_COCOA
2237    } else {
2238        CLAP_WINDOW_API_X11
2239    }
2240}
2241
2242fn gui_ext<L: PluginLogic>() -> &'static clap_plugin_gui {
2243    static CELL: OnceLock<clap_plugin_gui> = OnceLock::new();
2244    CELL.get_or_init(|| clap_plugin_gui {
2245        is_api_supported: Some(gui_is_api_supported::<L>),
2246        get_preferred_api: Some(gui_get_preferred_api::<L>),
2247        create: Some(gui_create::<L>),
2248        destroy: Some(gui_destroy::<L>),
2249        set_scale: Some(gui_set_scale::<L>),
2250        get_size: Some(gui_get_size::<L>),
2251        can_resize: Some(gui_can_resize::<L>),
2252        get_resize_hints: Some(gui_get_resize_hints),
2253        adjust_size: Some(gui_adjust_size::<L>),
2254        set_size: Some(gui_set_size::<L>),
2255        set_parent: Some(gui_set_parent::<L>),
2256        set_transient: Some(gui_set_transient),
2257        suggest_title: Some(gui_suggest_title::<L>),
2258        show: Some(gui_show::<L>),
2259        hide: Some(gui_hide::<L>),
2260    })
2261}
2262
2263unsafe extern "C" fn gui_is_api_supported<L: PluginLogic>(
2264    plugin: *const clap_plugin,
2265    api: *const c_char,
2266    is_floating: bool,
2267) -> bool {
2268    if is_floating || api.is_null() {
2269        return false;
2270    }
2271    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2272        return false;
2273    };
2274    inst.editor.is_some() && unsafe { CStr::from_ptr(api) } == platform_window_api()
2275}
2276
2277unsafe extern "C" fn gui_get_preferred_api<L: PluginLogic>(
2278    plugin: *const clap_plugin,
2279    api: *mut *const c_char,
2280    is_floating: *mut bool,
2281) -> bool {
2282    let supported =
2283        unsafe { gui_is_api_supported::<L>(plugin, platform_window_api().as_ptr(), false) };
2284    if !supported || api.is_null() || is_floating.is_null() {
2285        return false;
2286    }
2287    unsafe {
2288        *api = platform_window_api().as_ptr();
2289        *is_floating = false;
2290    }
2291    true
2292}
2293
2294unsafe extern "C" fn gui_create<L: PluginLogic>(
2295    plugin: *const clap_plugin,
2296    api: *const c_char,
2297    is_floating: bool,
2298) -> bool {
2299    unsafe { gui_is_api_supported::<L>(plugin, api, is_floating) }
2300}
2301
2302unsafe extern "C" fn gui_destroy<L: PluginLogic>(plugin: *const clap_plugin) {
2303    // Catch panics *outside* wnd_proc. A panic *inside* WM_DESTROY still
2304    // aborts at the `extern "system"` boundary — that path is handled by
2305    // `SlintGlContext::ensure_current` swallowing a dead WGL DC.
2306    host_callback("CLAP", "gui_destroy", || {
2307        if let Some(inst) = unsafe { Instance::<L>::from_plugin(plugin) }
2308            && let Some(editor) = inst.editor.as_mut()
2309        {
2310            editor.close();
2311        }
2312    });
2313}
2314
2315unsafe extern "C" fn gui_set_scale<L: PluginLogic>(plugin: *const clap_plugin, scale: f64) -> bool {
2316    if !scale.is_finite() || scale <= 0.0 {
2317        return false;
2318    }
2319    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2320        return false;
2321    };
2322    // Remember for get_size / request_resize even if editor is not open yet.
2323    inst.set_host_scale(scale);
2324    if let Some(editor) = inst.editor.as_mut() {
2325        editor.set_scale(scale);
2326    }
2327    true
2328}
2329
2330unsafe extern "C" fn gui_get_size<L: PluginLogic>(
2331    plugin: *const clap_plugin,
2332    width: *mut u32,
2333    height: *mut u32,
2334) -> bool {
2335    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2336        return false;
2337    };
2338    let Some(editor) = inst.editor.as_mut() else {
2339        return false;
2340    };
2341    if width.is_null() || height.is_null() {
2342        return false;
2343    }
2344    let (w, h) = editor.size();
2345    // Editor size is logical layout points. CLAP hosts on Win/Linux size the
2346    // embed frame in physical pixels = logical × set_scale (default 1.0).
2347    // macOS AppKit applies backing scale itself — report logical there.
2348    // Without the Win/Linux multiply, HiDPI / multi-monitor clips the child
2349    // (child HWND is design × host_scale, host frame was only design).
2350    let (pw, ph) = gui_logical_to_host_px(w, h, inst.host_scale());
2351    unsafe {
2352        *width = pw;
2353        *height = ph;
2354    }
2355    true
2356}
2357
2358unsafe extern "C" fn gui_can_resize<L: PluginLogic>(plugin: *const clap_plugin) -> bool {
2359    unsafe { Instance::<L>::from_plugin(plugin) }
2360        .and_then(|inst| inst.editor.as_ref())
2361        .is_some_and(|editor| editor.can_resize())
2362}
2363
2364unsafe extern "C" fn gui_get_resize_hints(
2365    _plugin: *const clap_plugin,
2366    _hints: *mut clap_sys::ext::gui::clap_gui_resize_hints,
2367) -> bool {
2368    false
2369}
2370
2371unsafe extern "C" fn gui_adjust_size<L: PluginLogic>(
2372    plugin: *const clap_plugin,
2373    width: *mut u32,
2374    height: *mut u32,
2375) -> bool {
2376    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2377        return false;
2378    };
2379    if width.is_null() || height.is_null() {
2380        return false;
2381    }
2382    let scale = inst.host_scale();
2383    let Some(editor) = inst.editor.as_mut() else {
2384        return false;
2385    };
2386    let (min_w, min_h) = editor.min_size();
2387    let (max_w, max_h) = editor.max_size();
2388    // Host passes physical pixels; clamp in logical space then convert back.
2389    let (req_w, req_h) = unsafe { (*width, *height) };
2390    let (lw, lh) = gui_host_px_to_logical(req_w, req_h, scale);
2391    let lw = lw.clamp(min_w.max(1), max_w);
2392    let lh = lh.clamp(min_h.max(1), max_h);
2393    let (pw, ph) = gui_logical_to_host_px(lw, lh, scale);
2394    unsafe {
2395        *width = pw;
2396        *height = ph;
2397    }
2398    true
2399}
2400
2401unsafe extern "C" fn gui_set_size<L: PluginLogic>(
2402    plugin: *const clap_plugin,
2403    width: u32,
2404    height: u32,
2405) -> bool {
2406    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2407        return false;
2408    };
2409    // Host → physical; Editor::set_size is logical (same as size()).
2410    let (lw, lh) = gui_host_px_to_logical(width, height, inst.host_scale());
2411    let Some(editor) = inst.editor.as_mut() else {
2412        return false;
2413    };
2414    editor.set_size(lw, lh)
2415}
2416
2417unsafe extern "C" fn gui_set_parent<L: PluginLogic>(
2418    plugin: *const clap_plugin,
2419    window: *const clap_window,
2420) -> bool {
2421    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2422        return false;
2423    };
2424    let Some(editor) = inst.editor.as_mut() else {
2425        return false;
2426    };
2427    if window.is_null() || unsafe { &*window }.api.is_null() {
2428        return false;
2429    }
2430    let window = unsafe { &*window };
2431    let api = unsafe { CStr::from_ptr(window.api) };
2432    let parent = if api == CLAP_WINDOW_API_WIN32 {
2433        RawWindowHandle::Win32(unsafe { window.specific.win32 })
2434    } else if api == CLAP_WINDOW_API_COCOA {
2435        RawWindowHandle::AppKit(unsafe { window.specific.cocoa })
2436    } else if api == CLAP_WINDOW_API_X11 {
2437        // `clap_xwnd` is `c_ulong`: 32-bit on Windows (LLP64), 64-bit elsewhere (LP64).
2438        // Widen losslessly to `u64`; skip the no-op conversion on Unix to avoid
2439        // clippy::useless_conversion.
2440        let xid = unsafe { window.specific.x11 };
2441        #[cfg(target_os = "windows")]
2442        let xid = u64::from(xid);
2443        RawWindowHandle::X11(xid)
2444    } else {
2445        return false;
2446    };
2447
2448    let params: Arc<dyn Params> = inst.params.clone();
2449    let ctx = PluginContext::new(params.clone())
2450        .with_bridge(Arc::new(ClapBridge {
2451            params,
2452            events: Arc::clone(&inst.param_events),
2453            host: inst.host,
2454            host_scale: Arc::clone(&inst.host_scale),
2455        }))
2456        .with_sample_rate(inst.sample_rate);
2457    editor.open(parent, ctx);
2458    true
2459}
2460
2461unsafe extern "C" fn gui_set_transient(
2462    _plugin: *const clap_plugin,
2463    _window: *const clap_window,
2464) -> bool {
2465    false
2466}
2467
2468unsafe extern "C" fn gui_suggest_title<L: PluginLogic>(
2469    _plugin: *const clap_plugin,
2470    _title: *const c_char,
2471) {
2472}
2473
2474unsafe extern "C" fn gui_show<L: PluginLogic>(plugin: *const clap_plugin) -> bool {
2475    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2476        return false;
2477    };
2478    let Some(editor) = inst.editor.as_mut() else {
2479        return false;
2480    };
2481    editor.show();
2482    true
2483}
2484
2485unsafe extern "C" fn gui_hide<L: PluginLogic>(plugin: *const clap_plugin) -> bool {
2486    let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2487        return false;
2488    };
2489    let Some(editor) = inst.editor.as_mut() else {
2490        return false;
2491    };
2492    editor.hide();
2493    true
2494}
2495
2496// ---------------------------------------------------------------------------
2497// state
2498// ---------------------------------------------------------------------------
2499
2500/// v1 blob codec lives in `aura_core::state` (shared with the VST3/LV2
2501/// wrappers); here we only pump bytes through the CLAP streams.
2502fn state_ext<L: PluginLogic>() -> &'static clap_plugin_state {
2503    static CELL: OnceLock<clap_plugin_state> = OnceLock::new();
2504    CELL.get_or_init(|| clap_plugin_state {
2505        save: Some(state_save::<L>),
2506        load: Some(state_load::<L>),
2507    })
2508}
2509
2510unsafe extern "C" fn state_save<L: PluginLogic>(
2511    plugin: *const clap_plugin,
2512    stream: *const clap_ostream,
2513) -> bool {
2514    host_callback_with("CLAP", "state_save", false, || {
2515        let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2516            return false;
2517        };
2518        if stream.is_null() {
2519            return false;
2520        }
2521        let Some(write) = (unsafe { &*stream }).write else {
2522            return false;
2523        };
2524
2525        let blob = aura_core::encode_state(&*inst.params);
2526
2527        let mut written = 0usize;
2528        while written < blob.len() {
2529            let n = unsafe {
2530                write(
2531                    stream,
2532                    blob.as_ptr().add(written) as *const c_void,
2533                    (blob.len() - written) as u64,
2534                )
2535            };
2536            if n <= 0 {
2537                return false;
2538            }
2539            written += n as usize;
2540        }
2541        true
2542    })
2543}
2544
2545unsafe extern "C" fn state_load<L: PluginLogic>(
2546    plugin: *const clap_plugin,
2547    stream: *const clap_istream,
2548) -> bool {
2549    host_callback_with("CLAP", "state_load", false, || {
2550        let Some(inst) = (unsafe { Instance::<L>::from_plugin(plugin) }) else {
2551            return false;
2552        };
2553        if stream.is_null() {
2554            return false;
2555        }
2556        let Some(read) = (unsafe { &*stream }).read else {
2557            return false;
2558        };
2559
2560        let mut blob = Vec::new();
2561        let mut chunk = [0u8; 4096];
2562        loop {
2563            let n = unsafe {
2564                read(
2565                    stream,
2566                    chunk.as_mut_ptr() as *mut c_void,
2567                    chunk.len() as u64,
2568                )
2569            };
2570            if n < 0 {
2571                return false;
2572            }
2573            if n == 0 {
2574                break;
2575            }
2576            blob.extend_from_slice(&chunk[..n as usize]);
2577        }
2578
2579        let ok = aura_core::decode_state(&*inst.params, &blob);
2580        if ok {
2581            // Values changed behind the host's back: per CLAP spec the plugin
2582            // must ask for a value rescan after a state load, or the host (and
2583            // clap-validator's state-reproducibility tests) sees stale values.
2584            unsafe { request_param_rescan(inst.host) };
2585        }
2586        ok
2587    })
2588}
2589
2590/// Ask the host to rescan param values (`clap_host_params.rescan`) after a
2591/// state load. No-op when the host is null or lacks the params extension.
2592pub(crate) unsafe fn request_param_rescan(host: *const clap_host) {
2593    if host.is_null() {
2594        return;
2595    }
2596    let Some(get) = (unsafe { &*host }).get_extension else {
2597        return;
2598    };
2599    let ext = unsafe { get(host, CLAP_EXT_PARAMS.as_ptr()) };
2600    if ext.is_null() {
2601        return;
2602    }
2603    let host_params = unsafe { &*(ext as *const clap_host_params) };
2604    if let Some(rescan) = host_params.rescan {
2605        unsafe { rescan(host, CLAP_PARAM_RESCAN_VALUES) };
2606    }
2607}
2608
2609// ---------------------------------------------------------------------------
2610// helpers
2611// ---------------------------------------------------------------------------
2612
2613fn map_param_flags(flags: ParamFlags, range: &ParamRange) -> u32 {
2614    let mut f = 0u32;
2615    if flags.contains(ParamFlags::AUTOMATABLE) {
2616        f |= CLAP_PARAM_IS_AUTOMATABLE;
2617        if flags.contains(ParamFlags::MODULATABLE_PER_NOTE) {
2618            // Bitwig Voice Stack binds only when per-note *and* per-key
2619            // automation are advertised (clap-saw-demo / Surge set).
2620            f |= CLAP_PARAM_IS_AUTOMATABLE_PER_NOTE_ID
2621                | CLAP_PARAM_IS_AUTOMATABLE_PER_KEY
2622                | CLAP_PARAM_IS_AUTOMATABLE_PER_CHANNEL;
2623        }
2624    }
2625    if flags.contains(ParamFlags::HIDDEN) {
2626        f |= CLAP_PARAM_IS_HIDDEN;
2627    }
2628    if flags.contains(ParamFlags::READONLY) {
2629        f |= CLAP_PARAM_IS_READONLY;
2630    }
2631    if flags.contains(ParamFlags::IS_BYPASS) {
2632        f |= CLAP_PARAM_IS_BYPASS;
2633    }
2634    if flags.contains(ParamFlags::MODULATABLE_PER_NOTE) {
2635        f |= CLAP_PARAM_IS_MODULATABLE
2636            | CLAP_PARAM_IS_MODULATABLE_PER_NOTE_ID
2637            | CLAP_PARAM_IS_MODULATABLE_PER_KEY
2638            | CLAP_PARAM_IS_MODULATABLE_PER_CHANNEL;
2639    } else if flags.contains(ParamFlags::MODULATABLE) {
2640        f |= CLAP_PARAM_IS_MODULATABLE;
2641    }
2642    if matches!(range, ParamRange::Discrete { .. } | ParamRange::Enum { .. }) {
2643        f |= CLAP_PARAM_IS_STEPPED;
2644    }
2645    f
2646}
2647
2648fn write_name(buf: &mut [c_char; CLAP_NAME_SIZE], s: &str) {
2649    write_fixed(buf, s);
2650}
2651
2652fn write_path(buf: &mut [c_char; CLAP_PATH_SIZE], s: &str) {
2653    write_fixed(buf, s);
2654}
2655
2656fn write_fixed<const N: usize>(buf: &mut [c_char; N], s: &str) {
2657    buf.fill(0);
2658    let bytes = s.as_bytes();
2659    let n = bytes.len().min(N - 1);
2660    for (i, b) in bytes.iter().take(n).enumerate() {
2661        buf[i] = *b as c_char;
2662    }
2663}
2664
2665fn write_c_buf(out: *mut c_char, cap: usize, s: &str) -> bool {
2666    if cap == 0 {
2667        return false;
2668    }
2669    let bytes = s.as_bytes();
2670    let n = bytes.len().min(cap - 1);
2671    unsafe {
2672        ptr::copy_nonoverlapping(bytes.as_ptr(), out as *mut u8, n);
2673        *out.add(n) = 0;
2674    }
2675    true
2676}
2677
2678#[cfg(test)]
2679mod remote_controls_tests {
2680    use super::{remote_control_pages, remote_controls_page_id, split_group};
2681    use aura_params::{ParamFlags, ParamInfo, ParamRange, ParamUnit, ParamValueKind};
2682
2683    fn info(id: u32, group: &'static str) -> ParamInfo {
2684        ParamInfo {
2685            id,
2686            name: "p",
2687            short_name: "p",
2688            group,
2689            range: ParamRange::Linear { min: 0.0, max: 1.0 },
2690            default_plain: 0.0,
2691            flags: ParamFlags::empty(),
2692            unit: ParamUnit::None,
2693            kind: ParamValueKind::Float,
2694            midi_map: None,
2695            midi_channel: None,
2696        }
2697    }
2698
2699    #[test]
2700    fn ungrouped_params_produce_no_page() {
2701        let infos = [info(0, ""), info(1, "")];
2702        assert_eq!(remote_control_pages(&infos).len(), 0);
2703    }
2704
2705    #[test]
2706    fn hidden_and_readonly_grouped_params_take_no_slot() {
2707        let mut hidden = info(0, "EQ");
2708        hidden.flags = ParamFlags::HIDDEN;
2709        let visible = info(1, "EQ");
2710        let mut readonly = info(2, "EQ");
2711        readonly.flags = ParamFlags::READONLY;
2712        let infos = [hidden, visible, readonly];
2713        let pages = remote_control_pages(&infos);
2714        assert_eq!(pages, vec![("EQ", vec![1])]);
2715    }
2716
2717    #[test]
2718    fn group_over_eight_params_splits_into_two_pages() {
2719        let infos: Vec<ParamInfo> = (0..10).map(|id| info(id, "EQ")).collect();
2720        let pages = remote_control_pages(&infos);
2721        assert_eq!(pages.len(), 2);
2722        assert_eq!(pages[0].1.len(), 8);
2723        assert_eq!(pages[1].1, vec![8, 9]);
2724    }
2725
2726    #[test]
2727    fn distinct_groups_get_distinct_pages() {
2728        let mut infos: Vec<ParamInfo> = (0..3).map(|id| info(id, "EQ")).collect();
2729        infos.extend((3..5).map(|id| info(id, "DYN")));
2730        let pages = remote_control_pages(&infos);
2731        assert_eq!(pages, vec![("EQ", vec![0, 1, 2]), ("DYN", vec![3, 4])]);
2732    }
2733
2734    #[test]
2735    fn section_page_split_on_first_slash() {
2736        assert_eq!(split_group("EQ/Lo Shelf"), ("EQ", "Lo Shelf"));
2737        assert_eq!(split_group("EQ/Lo Shelf/Extra"), ("EQ", "Lo Shelf/Extra"));
2738        assert_eq!(split_group("Compressor"), ("Compressor", "Compressor"));
2739    }
2740
2741    #[test]
2742    fn page_id_stable_and_distinct() {
2743        assert_eq!(
2744            remote_controls_page_id("EQ", 0),
2745            remote_controls_page_id("EQ", 0)
2746        );
2747        assert_ne!(
2748            remote_controls_page_id("EQ", 0),
2749            remote_controls_page_id("EQ", 1)
2750        );
2751        assert_ne!(
2752            remote_controls_page_id("EQ", 0),
2753            remote_controls_page_id("DYN", 0)
2754        );
2755    }
2756}
2757
2758#[cfg(test)]
2759mod bus_layout_clap_tests {
2760    use aura_core::{BusLayout, ChannelConfig};
2761
2762    #[test]
2763    fn default_layout_is_stereo() {
2764        // PluginLogic default is stereo; pure layout helpers used by ports.
2765        assert_eq!(BusLayout::stereo().main_out, ChannelConfig::Stereo);
2766        assert_eq!(BusLayout::mono().main_out, ChannelConfig::Mono);
2767        assert_eq!(BusLayout::stereo_and_mono().len(), 2);
2768    }
2769}
2770
2771#[cfg(test)]
2772mod latency_cache_tests {
2773    use std::sync::atomic::{AtomicU32, Ordering};
2774
2775    /// Mirrors the cache swap used by `Instance::update_latency_cache`.
2776    fn swap_latency(cache: &AtomicU32, new: u32) -> bool {
2777        let old = cache.swap(new, Ordering::Relaxed);
2778        old != new
2779    }
2780
2781    #[test]
2782    fn cache_detects_change_and_stability() {
2783        let cache = AtomicU32::new(0);
2784        assert!(swap_latency(&cache, 512));
2785        assert!(!swap_latency(&cache, 512));
2786        assert!(swap_latency(&cache, 1024));
2787        assert_eq!(cache.load(Ordering::Relaxed), 1024);
2788    }
2789}
2790
2791#[cfg(test)]
2792mod process_scratch_tests {
2793    use super::{MAX_NOTE_EVENTS, accept_note_event};
2794
2795    #[test]
2796    fn expression_flood_is_capped_note_on_is_not() {
2797        assert!(accept_note_event(MAX_NOTE_EVENTS - 1, false));
2798        assert!(!accept_note_event(MAX_NOTE_EVENTS, false));
2799        assert!(accept_note_event(MAX_NOTE_EVENTS, true));
2800        assert!(accept_note_event(MAX_NOTE_EVENTS + 50, true));
2801    }
2802
2803    #[test]
2804    fn notes_out_maps_end_to_clap_note_end() {
2805        use aura_core::NoteEventKind;
2806        use clap_sys::events::{
2807            CLAP_EVENT_NOTE_CHOKE, CLAP_EVENT_NOTE_END, CLAP_EVENT_NOTE_OFF, CLAP_EVENT_NOTE_ON,
2808        };
2809        let t = |k: NoteEventKind| -> u16 {
2810            match k {
2811                NoteEventKind::On { .. } => CLAP_EVENT_NOTE_ON,
2812                NoteEventKind::Off { .. } => CLAP_EVENT_NOTE_OFF,
2813                NoteEventKind::Choke => CLAP_EVENT_NOTE_CHOKE,
2814                NoteEventKind::End => CLAP_EVENT_NOTE_END,
2815                _ => 0xFFFF,
2816            }
2817        };
2818        assert_eq!(t(NoteEventKind::End), CLAP_EVENT_NOTE_END);
2819        assert_eq!(t(NoteEventKind::On { velocity: 1.0 }), CLAP_EVENT_NOTE_ON);
2820    }
2821
2822    #[test]
2823    fn ump_out_is_clap_midi2() {
2824        use std::mem::size_of;
2825
2826        use clap_sys::events::{
2827            CLAP_CORE_EVENT_SPACE_ID, CLAP_EVENT_MIDI2, clap_event_header, clap_event_midi2,
2828        };
2829
2830        let u = aura_core::Ump::midi2_per_note_pitch_bend(0, 0, 60, 0x8000_0000);
2831        assert!(u.is_per_note_pitch_bend());
2832        assert!(u.to_midi1().is_none());
2833        let e = clap_event_midi2 {
2834            header: clap_event_header {
2835                size: size_of::<clap_event_midi2>() as u32,
2836                time: 0,
2837                space_id: CLAP_CORE_EVENT_SPACE_ID,
2838                type_: CLAP_EVENT_MIDI2,
2839                flags: 0,
2840            },
2841            port_index: 0,
2842            data: u.words(),
2843        };
2844        assert_eq!(e.header.type_, CLAP_EVENT_MIDI2);
2845        assert_eq!(e.data, u.words());
2846    }
2847
2848    #[test]
2849    fn voice_info_overlapping_when_count_set() {
2850        use clap_sys::ext::voice_info::CLAP_VOICE_INFO_SUPPORTS_OVERLAPPING_NOTES;
2851        assert_ne!(CLAP_VOICE_INFO_SUPPORTS_OVERLAPPING_NOTES, 0);
2852    }
2853}
2854
2855#[cfg(test)]
2856mod gui_scale_tests {
2857    use super::{scale_logical_to_physical, scale_physical_to_logical};
2858
2859    #[test]
2860    fn scale_1_is_identity() {
2861        assert_eq!(scale_logical_to_physical(730, 395, 1.0), (730, 395));
2862        assert_eq!(scale_physical_to_logical(730, 395, 1.0), (730, 395));
2863    }
2864
2865    #[test]
2866    fn scale_15_round_trip() {
2867        let (pw, ph) = scale_logical_to_physical(730, 395, 1.5);
2868        assert_eq!((pw, ph), (1095, 593));
2869        assert_eq!(scale_physical_to_logical(pw, ph, 1.5), (730, 395));
2870    }
2871
2872    #[test]
2873    fn zoomed_frame_matches_child_physical() {
2874        // design 730×395, ui_zoom 100%, host 1.5 → host frame physical =
2875        // zoomed_logical × host_scale; child HWND = design × (host×zoom).
2876        let design = (730u32, 395u32);
2877        let ui_zoom = 1.0_f64;
2878        let host = 1.5_f64;
2879        let zoomed_w = ((f64::from(design.0) * ui_zoom).round() as u32).max(1);
2880        let zoomed_h = ((f64::from(design.1) * ui_zoom).round() as u32).max(1);
2881        let host_frame = scale_logical_to_physical(zoomed_w, zoomed_h, host);
2882        let child = scale_logical_to_physical(design.0, design.1, host * ui_zoom);
2883        assert_eq!(host_frame, child);
2884    }
2885}