Skip to main content

aura_vst3/
lib.rs

1//! Minimal VST3 wrapper for AURA.
2//!
3//! **Spec:** [steinbergmedia/vst3sdk](https://github.com/steinbergmedia/vst3sdk)
4//! is the source of truth. Bindings: [`vst3`](https://crates.io/crates/vst3)
5//! (generated from the C++ headers; module layout mirrors the namespaces).
6//!
7//! ```ignore
8//! aura_vst3::export_vst3!(MyPlugin);
9//! ```
10//!
11//! Covers: `GetPluginFactory` entry, single-component model (`IComponent` +
12//! `IAudioProcessor` + `IEditController` on one object), main FX bus
13//! (mono/stereo from [`PluginLogic::bus_layouts`]), f32 samples, params
14//! (1:1 `ParamID` map, no hash), flat state blob via
15//! [`aura_core::encode_state`] / [`aura_core::decode_state`], parented GUI
16//! via `IPlugView` + the same [`Editor`] trait as CLAP. MIDI note input
17//! (`PluginInfo::accepts_midi_in` declares the event input bus).
18
19#![allow(clippy::missing_safety_doc)]
20// ponytail: VST3 FFI glue — raw-pointer casts and C-int size conversions are
21// spec-shaped; the "safer" spellings add noise without changing semantics.
22// `unnecessary_cast`: the bindings alias enum types to `c_int`/`c_uint`
23// depending on platform, so casts that are redundant on Windows keep the
24// source portable. `non_snake_case`: trait method params mirror the C++ SDK.
25#![allow(non_snake_case)]
26#![allow(
27    clippy::ptr_as_ptr,
28    clippy::ref_as_ptr,
29    clippy::borrow_as_ptr,
30    clippy::cast_ptr_alignment,
31    clippy::cast_possible_truncation,
32    clippy::cast_sign_loss,
33    clippy::cast_possible_wrap,
34    clippy::cast_precision_loss,
35    clippy::unnecessary_cast
36)]
37
38mod gui;
39
40use std::ffi::{CStr, c_char, c_void};
41use std::marker::PhantomData;
42use std::ptr;
43use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
44
45use aura_core::info::PluginCategory;
46use aura_core::transport::Transport;
47use aura_core::{
48    AudioBuffer, AudioConfig, BusLayout, MidiBuffer, MidiMessage, MidiStatus, NoteBuffer,
49    PluginLogic, ProcessContext, ProcessMode, UmpBuffer, append_midi_as_ump, append_notes_as_midi,
50    append_ump_as_midi, decode_state, encode_state, host_callback_with, layout_at,
51};
52use aura_params::{ParamFlags, ParamInfo, ParamValueKind, Params};
53use gui::GuiState;
54use vst3::Steinberg::Vst::BusDirections_::{kInput, kOutput};
55use vst3::Steinberg::Vst::BusInfo_::BusFlags_::kDefaultActive;
56use vst3::Steinberg::Vst::BusTypes_::{kAux, kMain};
57use vst3::Steinberg::Vst::Event_::EventTypes_;
58use vst3::Steinberg::Vst::MediaTypes_::{kAudio, kEvent};
59use vst3::Steinberg::Vst::ParameterInfo_::ParameterFlags_::{
60    kCanAutomate, kIsBypass, kIsHidden, kIsList, kIsReadOnly,
61};
62use vst3::Steinberg::Vst::ProcessContext_::StatesAndFlags_::{
63    kBarPositionValid, kCycleActive, kCycleValid, kPlaying, kProjectTimeMusicValid, kRecording,
64    kTempoValid, kTimeSigValid,
65};
66use vst3::Steinberg::Vst::ProcessModes_::{kOffline, kPrefetch};
67use vst3::Steinberg::Vst::SymbolicSampleSizes_::kSample32;
68use vst3::Steinberg::Vst::{
69    BusDirection, BusInfo, BusType, Event, IAudioProcessor, IAudioProcessor_iid,
70    IAudioProcessorTrait, IComponent, IComponent_iid, IComponentHandler, IComponentTrait,
71    IEditController, IEditController_iid, IEditControllerTrait, IEventList, IEventListTrait,
72    IParamValueQueueTrait, IParameterChanges, IParameterChangesTrait, IoMode, MediaType,
73    NoteOffEvent, NoteOnEvent, ParamID, ParamValue, ParameterInfo, ProcessData, ProcessSetup,
74    RoutingInfo, SpeakerArrangement, String128, TChar, kRootUnitId,
75};
76// IPlugView / TBool live in Steinberg root, not Steinberg::Vst.
77use vst3::Steinberg::{
78    FIDString, FUnknown, IBStream, IBStreamTrait, IPlugView, IPluginBaseTrait, IPluginFactory,
79    IPluginFactory2, IPluginFactory2Trait, IPluginFactoryTrait, PClassInfo, PClassInfo2,
80    PFactoryInfo, TBool, TUID, char8, int32, kInternalError, kInvalidArgument, kNoInterface,
81    kNotImplemented, kResultFalse, kResultOk, tresult, uint32,
82};
83use vst3::{Class, ComPtr, ComRef, ComWrapper};
84
85// ---------------------------------------------------------------------------
86// Export macro
87// ---------------------------------------------------------------------------
88
89/// Hidden re-export so [`export_vst3!`] can name vst3 types without a
90/// direct plugin dependency on the `vst3` crate.
91#[doc(hidden)]
92pub use vst3 as __vst3;
93
94/// Export `$logic` ([`PluginLogic`]) as this cdylib's VST3 entry point.
95///
96/// Emits `GetPluginFactory` plus the platform module init/exit stubs hosts
97/// look for (`InitDll`/`ExitDll` on Windows, `BundleEntry`/`BundleExit` on
98/// macOS, `ModuleEntry`/`ModuleExit` on Linux).
99#[macro_export]
100macro_rules! export_vst3 {
101    ($logic:ty) => {
102        /// VST3 module entry point called by the host after loading the bundle.
103        #[allow(non_snake_case)]
104        #[unsafe(no_mangle)]
105        pub extern "system" fn GetPluginFactory() -> *mut $crate::__vst3::Steinberg::IPluginFactory
106        {
107            $crate::plugin_factory::<$logic>()
108        }
109
110        #[cfg(target_os = "windows")]
111        #[allow(non_snake_case)]
112        #[unsafe(no_mangle)]
113        pub extern "system" fn InitDll() -> bool {
114            true
115        }
116
117        #[cfg(target_os = "windows")]
118        #[allow(non_snake_case)]
119        #[unsafe(no_mangle)]
120        pub extern "system" fn ExitDll() -> bool {
121            true
122        }
123
124        #[cfg(target_os = "macos")]
125        #[allow(non_snake_case)]
126        #[unsafe(no_mangle)]
127        pub extern "system" fn BundleEntry(_bundle_ref: *mut core::ffi::c_void) -> bool {
128            true
129        }
130
131        #[cfg(target_os = "macos")]
132        #[allow(non_snake_case)]
133        #[unsafe(no_mangle)]
134        pub extern "system" fn BundleExit() -> bool {
135            true
136        }
137
138        #[cfg(target_os = "linux")]
139        #[allow(non_snake_case)]
140        #[unsafe(no_mangle)]
141        pub extern "system" fn ModuleEntry(_library_handle: *mut core::ffi::c_void) -> bool {
142            true
143        }
144
145        #[cfg(target_os = "linux")]
146        #[allow(non_snake_case)]
147        #[unsafe(no_mangle)]
148        pub extern "system" fn ModuleExit() -> bool {
149            true
150        }
151    };
152}
153
154/// Create a fresh plugin factory for `L`. Hosts call this once via
155/// `GetPluginFactory` and own the returned reference.
156#[must_use]
157pub fn plugin_factory<L: PluginLogic>() -> *mut IPluginFactory {
158    let wrapper = ComWrapper::new(Factory::<L>(PhantomData));
159    match wrapper.to_com_ptr::<IPluginFactory>() {
160        Some(ptr) => ComPtr::into_raw(ptr),
161        None => ptr::null_mut(),
162    }
163}
164
165// ---------------------------------------------------------------------------
166// Class ID (TUID)
167// ---------------------------------------------------------------------------
168
169const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
170const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
171
172/// FNV-1a 64-bit over `bytes` with a custom offset seed.
173const fn fnv1a(seed: u64, bytes: &[u8]) -> u64 {
174    let mut hash = seed;
175    let mut i = 0;
176    while i < bytes.len() {
177        hash ^= bytes[i] as u64;
178        hash = hash.wrapping_mul(FNV_PRIME);
179        i += 1;
180    }
181    hash
182}
183
184/// Deterministic 16-byte class ID derived from an ID string: two FNV-1a
185/// 64-bit passes with different offset seeds, little-endian packed.
186///
187/// **Changing the ID string breaks host compatibility** — saved sessions and
188/// automation resolve the plugin by this ID, so `PluginInfo::vst3_id` is
189/// forever once shipped.
190#[must_use]
191pub fn tuid_bytes(id: &str) -> [u8; 16] {
192    let a = fnv1a(FNV_OFFSET, id.as_bytes());
193    // Second pass: offset basis with rotated halves, so the two 64-bit
194    // lanes are independent functions of the input.
195    let b = fnv1a(
196        FNV_OFFSET.rotate_left(32) ^ 0x9e37_79b9_7f4a_7c15,
197        id.as_bytes(),
198    );
199    let mut out = [0u8; 16];
200    out[..8].copy_from_slice(&a.to_le_bytes());
201    out[8..].copy_from_slice(&b.to_le_bytes());
202    out
203}
204
205/// Class TUID for `L`, derived from `vst3_id` (fallback `clap_id`).
206/// Cached per monomorphization.
207fn class_id<L: PluginLogic>() -> TUID {
208    static CELL: OnceLock<TUID> = OnceLock::new();
209    *CELL.get_or_init(|| {
210        let info = L::info();
211        let id = if info.vst3_id.is_empty() {
212            info.clap_id
213        } else {
214            info.vst3_id
215        };
216        tuid_bytes(id).map(|b| b as c_char)
217    })
218}
219
220// ---------------------------------------------------------------------------
221// String helpers (char8 = ASCII-ish, String128 = UTF-16)
222// ---------------------------------------------------------------------------
223
224/// Copy `s` into a fixed `char8` field, NUL-padded, truncated to fit.
225fn write_char8(dst: &mut [char8], s: &str) {
226    dst.fill(0);
227    let n = s.len().min(dst.len().saturating_sub(1));
228    for (d, b) in dst.iter_mut().zip(s.as_bytes()).take(n) {
229        *d = *b as char8;
230    }
231}
232
233/// Copy `s` into a `String128` as UTF-16, NUL-padded, truncated to 127 units.
234fn write_string128(dst: &mut String128, s: &str) {
235    dst.fill(0);
236    for (d, u) in dst.iter_mut().zip(s.encode_utf16().take(127)) {
237        *d = u;
238    }
239}
240
241/// Read a NUL-terminated host UTF-16 string (bounded).
242unsafe fn read_tchar(ptr: *const TChar) -> String {
243    const MAX: usize = 4096;
244    let mut units = Vec::new();
245    for i in 0..MAX {
246        // SAFETY: caller guarantees a valid NUL-terminated string; the bound
247        // caps damage from a misbehaving host.
248        let u = unsafe { *ptr.add(i) };
249        if u == 0 {
250            break;
251        }
252        units.push(u);
253    }
254    String::from_utf16_lossy(&units)
255}
256
257// ---------------------------------------------------------------------------
258// Factory
259// ---------------------------------------------------------------------------
260
261struct Factory<L: PluginLogic>(PhantomData<fn() -> L>);
262
263impl<L: PluginLogic> Class for Factory<L> {
264    type Interfaces = (IPluginFactory, IPluginFactory2);
265}
266
267impl<L: PluginLogic> IPluginFactoryTrait for Factory<L> {
268    unsafe fn getFactoryInfo(&self, info: *mut PFactoryInfo) -> tresult {
269        if info.is_null() {
270            return kInvalidArgument;
271        }
272        let meta = L::info();
273        // SAFETY: non-null, host-owned out struct per spec.
274        let info = unsafe { &mut *info };
275        write_char8(&mut info.vendor, meta.vendor);
276        write_char8(&mut info.url, meta.url);
277        write_char8(&mut info.email, "");
278        info.flags = vst3::Steinberg::PFactoryInfo_::FactoryFlags_::kUnicode as int32;
279        kResultOk
280    }
281
282    unsafe fn countClasses(&self) -> int32 {
283        1
284    }
285
286    unsafe fn getClassInfo(&self, index: int32, info: *mut PClassInfo) -> tresult {
287        if index != 0 || info.is_null() {
288            return kInvalidArgument;
289        }
290        let meta = L::info();
291        // SAFETY: non-null, host-owned out struct per spec.
292        let info = unsafe { &mut *info };
293        info.cid = class_id::<L>();
294        info.cardinality = vst3::Steinberg::PClassInfo_::ClassCardinality_::kManyInstances as int32;
295        write_char8(&mut info.category, "Audio Module Class");
296        write_char8(&mut info.name, meta.name);
297        kResultOk
298    }
299
300    unsafe fn createInstance(
301        &self,
302        cid: FIDString,
303        iid: FIDString,
304        obj: *mut *mut c_void,
305    ) -> tresult {
306        if cid.is_null() || iid.is_null() || obj.is_null() {
307            return kInvalidArgument;
308        }
309        // SAFETY: non-null out pointer per spec.
310        unsafe { *obj = ptr::null_mut() };
311        // SAFETY: FIDString here carries a 16-byte TUID per spec.
312        let cid = unsafe { &*(cid as *const TUID) };
313        if *cid != class_id::<L>() {
314            return kInvalidArgument;
315        }
316        // SAFETY: same as above.
317        let iid = unsafe { &*(iid as *const TUID) };
318
319        // Single-component model: the same object serves IComponent and
320        // IEditController. Fresh instance per call.
321        let wrapper = ComWrapper::new(Component::<L>::new());
322        let ptr: *mut c_void = if *iid == IComponent_iid {
323            wrapper
324                .to_com_ptr::<IComponent>()
325                .map_or(ptr::null_mut(), |p| ComPtr::into_raw(p).cast())
326        } else if *iid == IEditController_iid {
327            wrapper
328                .to_com_ptr::<IEditController>()
329                .map_or(ptr::null_mut(), |p| ComPtr::into_raw(p).cast())
330        } else if *iid == IAudioProcessor_iid {
331            wrapper
332                .to_com_ptr::<IAudioProcessor>()
333                .map_or(ptr::null_mut(), |p| ComPtr::into_raw(p).cast())
334        } else {
335            return kNoInterface;
336        };
337        // SAFETY: non-null out pointer per spec.
338        unsafe { *obj = ptr };
339        kResultOk
340    }
341}
342
343impl<L: PluginLogic> IPluginFactory2Trait for Factory<L> {
344    unsafe fn getClassInfo2(&self, index: int32, info: *mut PClassInfo2) -> tresult {
345        if index != 0 || info.is_null() {
346            return kInvalidArgument;
347        }
348        let meta = L::info();
349        // SAFETY: non-null, host-owned out struct per spec.
350        let info = unsafe { &mut *info };
351        info.cid = class_id::<L>();
352        info.cardinality = vst3::Steinberg::PClassInfo_::ClassCardinality_::kManyInstances as int32;
353        write_char8(&mut info.category, "Audio Module Class");
354        write_char8(&mut info.name, meta.name);
355        info.classFlags = 0;
356        write_char8(
357            &mut info.subCategories,
358            match meta.category {
359                PluginCategory::Effect => "Fx",
360                PluginCategory::Analyzer => "Fx|Analyzer",
361                PluginCategory::Instrument => "Instrument",
362                PluginCategory::NoteEffect => "Fx|Note Expression",
363            },
364        );
365        write_char8(&mut info.vendor, meta.vendor);
366        write_char8(&mut info.version, meta.version);
367        write_char8(&mut info.sdkVersion, "VST 3.7");
368        kResultOk
369    }
370}
371
372// ---------------------------------------------------------------------------
373// Component (IComponent + IAudioProcessor + IEditController, single object)
374// ---------------------------------------------------------------------------
375
376/// Runtime state behind a mutex: every COM method takes `&self`, so shared
377/// mutable state needs interior mutability. Uncontended in practice (host
378/// serializes audio-thread vs main-thread calls per spec).
379struct Component<L: PluginLogic> {
380    params: Arc<L::Params>,
381    /// Shared with `IPlugView` (editor open/close, bridge, sample rate).
382    gui: Arc<GuiState>,
383    inner: Mutex<Inner<L>>,
384}
385
386struct Inner<L: PluginLogic> {
387    state: Option<L::DspState>,
388    sample_rate: f64,
389    max_samples: usize,
390    process_mode: ProcessMode,
391    active: bool,
392    processing: bool,
393    /// Index into `L::bus_layouts()` last accepted by `setBusArrangements`.
394    layout_index: usize,
395    scratch: ProcessScratch,
396}
397
398/// Audio-thread working set. Reserved in `setupProcessing` / `setActive`.
399struct ProcessScratch {
400    midi: MidiBuffer,
401    midi_out: MidiBuffer,
402    notes_out: NoteBuffer,
403    ump: UmpBuffer,
404    ump_out: UmpBuffer,
405    silence: Vec<f32>,
406}
407
408const MAX_AUDIO_CH: usize = 8;
409const MAX_MIDI_EVENTS: usize = 4096;
410
411impl ProcessScratch {
412    fn new() -> Self {
413        Self {
414            midi: MidiBuffer::new(),
415            midi_out: MidiBuffer::new(),
416            notes_out: NoteBuffer::new(),
417            ump: UmpBuffer::new(),
418            ump_out: UmpBuffer::new(),
419            silence: Vec::new(),
420        }
421    }
422
423    fn prepare(&mut self, max_frames: usize) {
424        self.midi.reserve(MAX_MIDI_EVENTS + 128);
425        self.midi_out.reserve(256);
426        self.notes_out.reserve(256);
427        self.ump.reserve(MAX_MIDI_EVENTS);
428        self.ump_out.reserve(256);
429        if self.silence.len() < max_frames {
430            self.silence.resize(max_frames, 0.0);
431        }
432    }
433}
434
435fn accept_midi_event(len: usize, essential: bool) -> bool {
436    essential || len < MAX_MIDI_EVENTS
437}
438
439impl<L: PluginLogic> Component<L> {
440    fn new() -> Self {
441        let params = Arc::new(L::Params::default());
442        let gui = GuiState::new(Arc::clone(&params) as Arc<dyn Params>);
443        Self {
444            params,
445            gui,
446            inner: Mutex::new(Inner {
447                state: None,
448                sample_rate: 44_100.0,
449                max_samples: 0,
450                process_mode: ProcessMode::Realtime,
451                active: false,
452                processing: false,
453                layout_index: 0,
454                scratch: ProcessScratch::new(),
455            }),
456        }
457    }
458
459    fn selected_layout(&self) -> BusLayout {
460        let layouts = L::bus_layouts();
461        let idx = self.lock().layout_index;
462        layout_at(&layouts, idx)
463    }
464
465    /// Max main-bus channel count across all declared layouts (`BusInfo` report).
466    fn max_main_channels(is_input: bool) -> i32 {
467        let layouts = L::bus_layouts();
468        let n = layouts
469            .iter()
470            .map(|l| {
471                if is_input {
472                    l.main_input_channels()
473                } else {
474                    l.main_output_channels()
475                }
476            })
477            .max()
478            .unwrap_or(2);
479        n as i32
480    }
481
482    /// Max sidechain-bus channel count across all declared layouts.
483    fn max_sidechain_channels() -> i32 {
484        let layouts = L::bus_layouts();
485        let n = layouts
486            .iter()
487            .map(|l| l.sidechain_input_channels())
488            .max()
489            .unwrap_or(0);
490        n as i32
491    }
492
493    /// Max aux-out bus channel count across all declared layouts.
494    fn max_aux_channels() -> i32 {
495        let layouts = L::bus_layouts();
496        let n = layouts
497            .iter()
498            .map(|l| l.aux_output_channels())
499            .max()
500            .unwrap_or(0);
501        n as i32
502    }
503
504    fn lock(&self) -> MutexGuard<'_, Inner<L>> {
505        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
506    }
507
508    fn find_info(&self, id: u32) -> Option<ParamInfo> {
509        self.params.param_infos().into_iter().find(|p| p.id == id)
510    }
511
512    unsafe fn apply_param_changes(&self, changes: *mut IParameterChanges) {
513        // SAFETY: host guarantees `changes` is valid for this process call.
514        let Some(changes) = (unsafe { ComRef::from_raw(changes) }) else {
515            return;
516        };
517        let count = unsafe { changes.getParameterCount() };
518        for i in 0..count {
519            let queue = unsafe { changes.getParameterData(i) };
520            // SAFETY: queue pointers from the host are valid for this call.
521            let Some(queue) = (unsafe { ComRef::from_raw(queue) }) else {
522                continue;
523            };
524            let id = unsafe { queue.getParameterId() };
525            let points = unsafe { queue.getPointCount() };
526            if points <= 0 {
527                continue;
528            }
529            let mut sample_offset: int32 = 0;
530            let mut value: ParamValue = 0.0;
531            // Block-accurate application: the last point in the queue wins.
532            let ok = unsafe { queue.getPoint(points - 1, &mut sample_offset, &mut value) };
533            if ok == kResultOk {
534                self.params.set_normalized(id, value);
535            }
536        }
537    }
538
539    // Host buffer glue + bus layout + MIDI — length is inherent to VST3 process.
540    #[allow(clippy::too_many_lines)]
541    unsafe fn process_audio(&self, data: *mut ProcessData) -> tresult {
542        // Author `process` must not unwind across the COM ABI.
543        host_callback_with("VST3", "process", kInternalError, || {
544            if data.is_null() {
545                return kInvalidArgument;
546            }
547            // SAFETY: non-null; valid for the duration of the process call.
548            let data = unsafe { &*data };
549            let frames = data.numSamples.max(0) as usize;
550
551            if !data.inputParameterChanges.is_null() {
552                unsafe { self.apply_param_changes(data.inputParameterChanges) };
553            }
554
555            let transport = if data.processContext.is_null() {
556                None
557            } else {
558                // SAFETY: non-null; valid for the duration of the process call.
559                Some(map_transport(unsafe { &*data.processContext }))
560            };
561
562            if frames == 0 {
563                return kResultOk;
564            }
565
566            let mut inner = self.lock();
567            if !inner.active || !inner.processing {
568                return kResultOk;
569            }
570            if data.symbolicSampleSize != kSample32 as int32 {
571                return kResultFalse;
572            }
573            let sample_rate = inner.sample_rate;
574            let process_mode = inner.process_mode;
575            let layout = layout_at(&L::bus_layouts(), inner.layout_index);
576            let main_in_ch = layout.main_input_channels() as usize;
577            let sidechain_in_ch = layout.sidechain_input_channels() as usize;
578            let main_out_ch = layout.main_output_channels() as usize;
579            let total_in_ch = main_in_ch + sidechain_in_ch;
580            let mut out_ch = layout.total_output_channels() as usize;
581            let max_samples = inner.max_samples;
582            if out_ch > MAX_AUDIO_CH || total_in_ch > MAX_AUDIO_CH {
583                return kResultOk;
584            }
585            if max_samples == 0 || frames > max_samples {
586                return kResultFalse;
587            }
588            if inner.scratch.silence.len() < frames {
589                return kResultFalse;
590            }
591            if inner.state.is_none() {
592                return kResultOk;
593            }
594            if data.numOutputs <= 0 || data.outputs.is_null() {
595                return kResultOk;
596            }
597
598            let mut in_ptrs = [ptr::null::<f32>(); MAX_AUDIO_CH];
599            let mut filled_in = 0usize;
600            if data.numInputs > 0 && !data.inputs.is_null() {
601                for bus_i in 0..data.numInputs as usize {
602                    if filled_in >= total_in_ch {
603                        break;
604                    }
605                    let bus = unsafe { &*data.inputs.add(bus_i) };
606                    let ptrs = unsafe { bus.__field0.channelBuffers32 };
607                    if ptrs.is_null() {
608                        continue;
609                    }
610                    for c in 0..bus.numChannels.max(0) as usize {
611                        if filled_in >= total_in_ch {
612                            break;
613                        }
614                        in_ptrs[filled_in] = unsafe { *ptrs.add(c) };
615                        filled_in += 1;
616                    }
617                }
618            }
619
620            let mut out_ptrs = [ptr::null_mut::<f32>(); MAX_AUDIO_CH];
621            let mut filled_out = 0usize;
622            for bus_i in 0..data.numOutputs as usize {
623                if filled_out >= out_ch {
624                    break;
625                }
626                let bus = unsafe { &*data.outputs.add(bus_i) };
627                let ptrs = unsafe { bus.__field0.channelBuffers32 };
628                if ptrs.is_null() {
629                    continue;
630                }
631                for c in 0..bus.numChannels.max(0) as usize {
632                    if filled_out >= out_ch {
633                        break;
634                    }
635                    out_ptrs[filled_out] = unsafe { *ptrs.add(c) };
636                    filled_out += 1;
637                }
638            }
639            if filled_out == 0 || out_ptrs[..filled_out].iter().any(|p| p.is_null()) {
640                return kResultOk;
641            }
642            out_ch = filled_out;
643            let main_out_for_buf = main_out_ch.min(out_ch);
644
645            inner.scratch.midi.clear();
646            inner.scratch.midi_out.clear();
647            inner.scratch.notes_out.clear();
648            inner.scratch.ump.clear();
649            inner.scratch.ump_out.clear();
650            if L::info().accepts_midi_in && !data.inputEvents.is_null() {
651                unsafe { collect_input_events(data.inputEvents, &mut inner.scratch.midi) };
652            }
653            {
654                let scratch = &mut inner.scratch;
655                append_midi_as_ump(&mut scratch.ump, &scratch.midi);
656            }
657            let midi = std::mem::take(&mut inner.scratch.midi);
658            let midi_out = std::mem::take(&mut inner.scratch.midi_out);
659            let notes_out = std::mem::take(&mut inner.scratch.notes_out);
660            let ump = std::mem::take(&mut inner.scratch.ump);
661            let ump_out = std::mem::take(&mut inner.scratch.ump_out);
662
663            let mut ctx = {
664                // Distinct fields; raw slice so we can also mut-borrow `state`.
665                let silence =
666                    unsafe { std::slice::from_raw_parts(inner.scratch.silence.as_ptr(), frames) };
667                let mut in_store = [&[] as &[f32]; MAX_AUDIO_CH];
668                for i in 0..total_in_ch {
669                    in_store[i] = if in_ptrs[i].is_null() {
670                        silence
671                    } else {
672                        unsafe { std::slice::from_raw_parts(in_ptrs[i], frames) }
673                    };
674                }
675                let in_refs = &in_store[..total_in_ch];
676                let state = inner.state.as_mut().expect("checked is_none above");
677                let mut ctx = ProcessContext::new(sample_rate, frames)
678                    .with_process_mode(process_mode)
679                    .with_midi(midi)
680                    .with_midi_out(midi_out)
681                    .with_notes_out(notes_out)
682                    .with_ump(ump)
683                    .with_ump_out(ump_out);
684                ctx.transport = transport;
685                let _ = unsafe {
686                    run_process_chunk::<L>(
687                        state,
688                        &self.params,
689                        in_refs,
690                        out_ptrs,
691                        out_ch,
692                        main_out_for_buf,
693                        0,
694                        frames,
695                        main_in_ch,
696                        sidechain_in_ch,
697                        &mut ctx,
698                    )
699                };
700                ctx
701            };
702            inner.scratch.midi = std::mem::take(&mut ctx.midi);
703            if L::info().emits_midi && !data.outputEvents.is_null() {
704                append_ump_as_midi(&mut ctx.midi_out, &ctx.ump_out);
705                append_notes_as_midi(&mut ctx.midi_out, &ctx.notes_out);
706                if !ctx.midi_out.is_empty() {
707                    unsafe { emit_output_events(data.outputEvents, &ctx.midi_out) };
708                }
709            }
710            inner.scratch.midi_out = std::mem::take(&mut ctx.midi_out);
711            inner.scratch.midi_out.clear();
712            inner.scratch.notes_out = std::mem::take(&mut ctx.notes_out);
713            inner.scratch.notes_out.clear();
714            inner.scratch.ump = std::mem::take(&mut ctx.ump);
715            inner.scratch.ump_out = std::mem::take(&mut ctx.ump_out);
716            inner.scratch.ump_out.clear();
717            kResultOk
718        })
719    }
720}
721
722impl<L: PluginLogic> Class for Component<L> {
723    type Interfaces = (IComponent, IAudioProcessor, IEditController);
724}
725
726impl<L: PluginLogic> IPluginBaseTrait for Component<L> {
727    unsafe fn initialize(&self, _context: *mut FUnknown) -> tresult {
728        // Main-thread GUI factory — same timing as CLAP `plugin_init`.
729        let editor = L::editor(Arc::clone(&self.params));
730        *self
731            .gui
732            .editor
733            .lock()
734            .unwrap_or_else(PoisonError::into_inner) = editor;
735        kResultOk
736    }
737
738    unsafe fn terminate(&self) -> tresult {
739        if let Some(editor) = self
740            .gui
741            .editor
742            .lock()
743            .unwrap_or_else(PoisonError::into_inner)
744            .as_mut()
745        {
746            editor.close();
747        }
748        *self
749            .gui
750            .editor
751            .lock()
752            .unwrap_or_else(PoisonError::into_inner) = None;
753        *self
754            .gui
755            .handler
756            .lock()
757            .unwrap_or_else(PoisonError::into_inner) = None;
758        *self
759            .gui
760            .frame
761            .lock()
762            .unwrap_or_else(PoisonError::into_inner) = None;
763        kResultOk
764    }
765}
766
767impl<L: PluginLogic> IComponentTrait for Component<L> {
768    unsafe fn getControllerClassId(&self, classId: *mut TUID) -> tresult {
769        if classId.is_null() {
770            return kInvalidArgument;
771        }
772        // Single component: controller CID == component CID.
773        // SAFETY: non-null, host provides 16 writable bytes per spec.
774        unsafe { *classId = class_id::<L>() };
775        kResultOk
776    }
777
778    unsafe fn setIoMode(&self, _mode: IoMode) -> tresult {
779        // kSimple / kAdvanced / kOfflineProcessing all accepted, no behavior change.
780        kResultOk
781    }
782
783    unsafe fn getBusCount(&self, r#type: MediaType, dir: BusDirection) -> int32 {
784        if r#type == kEvent as MediaType {
785            let info = L::info();
786            if dir == kInput as BusDirection {
787                return int32::from(info.accepts_midi_in);
788            }
789            return int32::from(info.emits_midi);
790        }
791        if r#type != kAudio as MediaType {
792            return 0;
793        }
794        // Port counts (not channels): main ± sidechain in / main ± aux out.
795        if dir == kInput as BusDirection {
796            let has_in = L::bus_layouts().iter().any(|l| l.main_in.is_some());
797            let has_sc = L::bus_layouts().iter().any(|l| l.sidechain_in.is_some());
798            i32::from(has_in) + i32::from(has_sc)
799        } else {
800            let has_aux = L::bus_layouts().iter().any(|l| l.aux_out.is_some());
801            1 + i32::from(has_aux)
802        }
803    }
804
805    unsafe fn getBusInfo(
806        &self,
807        r#type: MediaType,
808        dir: BusDirection,
809        index: int32,
810        bus: *mut BusInfo,
811    ) -> tresult {
812        if bus.is_null() {
813            return kInvalidArgument;
814        }
815        if r#type == kEvent as MediaType {
816            let info = L::info();
817            let valid = if dir == kInput as BusDirection {
818                info.accepts_midi_in
819            } else {
820                info.emits_midi
821            };
822            if !valid || index != 0 {
823                return kInvalidArgument;
824            }
825            // SAFETY: non-null, host-owned out struct per spec.
826            let bus = unsafe { &mut *bus };
827            bus.mediaType = kEvent as MediaType;
828            bus.direction = dir;
829            bus.channelCount = 1;
830            write_string128(
831                &mut bus.name,
832                if dir == kInput as BusDirection {
833                    "MIDI In"
834                } else {
835                    "MIDI Out"
836                },
837            );
838            bus.busType = kMain as BusType;
839            bus.flags = kDefaultActive as uint32;
840            return kResultOk;
841        }
842        if r#type != kAudio as MediaType
843            || (dir != kInput as BusDirection && dir != kOutput as BusDirection)
844        {
845            return kInvalidArgument;
846        }
847        if dir == kInput as BusDirection && index < 0 {
848            return kInvalidArgument;
849        }
850
851        let is_input = dir == kInput as BusDirection;
852        let (channels, name, bus_type) = if is_input {
853            match index {
854                0 if Self::max_main_channels(true) > 0 => {
855                    (Self::max_main_channels(true), "Input", kMain)
856                }
857                1 if Self::max_sidechain_channels() > 0 => {
858                    (Self::max_sidechain_channels(), "Sidechain", kAux)
859                }
860                _ => return kInvalidArgument,
861            }
862        } else {
863            match index {
864                0 => (Self::max_main_channels(false), "Output", kMain),
865                1 if Self::max_aux_channels() > 0 => (Self::max_aux_channels(), "Aux", kAux),
866                _ => return kInvalidArgument,
867            }
868        };
869
870        // SAFETY: non-null, host-owned out struct per spec.
871        let bus = unsafe { &mut *bus };
872        bus.mediaType = kAudio as MediaType;
873        bus.direction = dir;
874        bus.channelCount = channels as int32;
875        write_string128(&mut bus.name, name);
876        bus.busType = bus_type as BusType;
877        bus.flags = kDefaultActive as uint32;
878        kResultOk
879    }
880
881    unsafe fn getRoutingInfo(
882        &self,
883        _inInfo: *mut RoutingInfo,
884        _outInfo: *mut RoutingInfo,
885    ) -> tresult {
886        kNotImplemented
887    }
888
889    unsafe fn activateBus(
890        &self,
891        _type: MediaType,
892        _dir: BusDirection,
893        _index: int32,
894        _state: TBool,
895    ) -> tresult {
896        kResultOk
897    }
898
899    unsafe fn setActive(&self, state: TBool) -> tresult {
900        let mut inner = self.lock();
901        if state != 0 {
902            if inner.active {
903                return kResultOk;
904            }
905            let layout = layout_at(&L::bus_layouts(), inner.layout_index);
906            let config = AudioConfig::new(inner.sample_rate, inner.max_samples)
907                .with_process_mode(inner.process_mode)
908                .with_channels(layout.main_input_channels(), layout.main_output_channels())
909                .with_sidechain_channels(layout.sidechain_input_channels())
910                .with_aux_channels(layout.aux_output_channels());
911            let mut dsp = L::init(&self.params, inner.sample_rate);
912            self.params.set_sample_rate(inner.sample_rate);
913            L::reset(&mut dsp, &self.params, &config);
914            let scratch_frames = inner.max_samples.max(8192);
915            inner.scratch.prepare(scratch_frames);
916            inner.state = Some(dsp);
917            inner.active = true;
918        } else {
919            inner.active = false;
920            inner.processing = false;
921            inner.state = None;
922        }
923        kResultOk
924    }
925
926    unsafe fn setState(&self, state: *mut IBStream) -> tresult {
927        load_state(&*self.params, state)
928    }
929
930    unsafe fn getState(&self, state: *mut IBStream) -> tresult {
931        save_state(&*self.params, state)
932    }
933}
934
935impl<L: PluginLogic> IAudioProcessorTrait for Component<L> {
936    unsafe fn setBusArrangements(
937        &self,
938        inputs: *mut SpeakerArrangement,
939        numIns: int32,
940        outputs: *mut SpeakerArrangement,
941        numOuts: int32,
942    ) -> tresult {
943        if numOuts < 1 || outputs.is_null() {
944            return kResultFalse;
945        }
946        // SAFETY: host arrays sized by numIns/numOuts.
947        let out_ch = speaker_channel_count(unsafe { *outputs });
948        let aux_ch = if numOuts >= 2 {
949            speaker_channel_count(unsafe { *outputs.add(1) })
950        } else {
951            0
952        };
953        if numIns < 0 || inputs.is_null() && numIns > 0 {
954            return kResultFalse;
955        }
956        let in_ch = if numIns == 0 {
957            0
958        } else {
959            speaker_channel_count(unsafe { *inputs })
960        };
961        let sidechain_ch = if numIns >= 2 {
962            speaker_channel_count(unsafe { *inputs.add(1) })
963        } else {
964            0
965        };
966
967        let layouts = L::bus_layouts();
968        let Some(idx) = layouts.iter().position(|l| {
969            l.main_input_channels() == in_ch
970                && l.sidechain_input_channels() == sidechain_ch
971                && l.main_output_channels() == out_ch
972                && l.aux_output_channels() == aux_ch
973        }) else {
974            return kResultFalse;
975        };
976        self.lock().layout_index = idx;
977        kResultOk
978    }
979
980    unsafe fn getBusArrangement(
981        &self,
982        dir: BusDirection,
983        index: int32,
984        arr: *mut SpeakerArrangement,
985    ) -> tresult {
986        if arr.is_null() {
987            return kInvalidArgument;
988        }
989        let layout = self.selected_layout();
990        let is_input = dir == kInput as BusDirection;
991        let channels = if is_input {
992            match index {
993                0 => layout.main_input_channels(),
994                1 => layout.sidechain_input_channels(),
995                _ => return kInvalidArgument,
996            }
997        } else {
998            match index {
999                0 => layout.main_output_channels(),
1000                1 => layout.aux_output_channels(),
1001                _ => return kInvalidArgument,
1002            }
1003        };
1004        let Some(sa) = arrangement_for_channels(channels) else {
1005            return kInvalidArgument;
1006        };
1007        // SAFETY: non-null, host-owned out value per spec.
1008        unsafe { *arr = sa };
1009        kResultOk
1010    }
1011
1012    unsafe fn canProcessSampleSize(&self, symbolicSampleSize: int32) -> tresult {
1013        if symbolicSampleSize == kSample32 as int32 {
1014            kResultOk
1015        } else {
1016            kResultFalse
1017        }
1018    }
1019
1020    unsafe fn getLatencySamples(&self) -> uint32 {
1021        let inner = self.lock();
1022        inner.state.as_ref().map_or(0, |s| L::latency(s))
1023    }
1024
1025    unsafe fn setupProcessing(&self, setup: *mut ProcessSetup) -> tresult {
1026        if setup.is_null() {
1027            return kInvalidArgument;
1028        }
1029        // SAFETY: non-null, host-owned struct per spec.
1030        let setup = unsafe { &*setup };
1031        if setup.symbolicSampleSize != kSample32 as int32 {
1032            return kResultFalse;
1033        }
1034        {
1035            let mut inner = self.lock();
1036            inner.sample_rate = setup.sampleRate;
1037            inner.max_samples = setup.maxSamplesPerBlock.max(0) as usize;
1038            inner.process_mode = map_process_mode(setup.processMode);
1039            let scratch_frames = inner.max_samples.max(8192);
1040            inner.scratch.prepare(scratch_frames);
1041        }
1042        self.params.set_sample_rate(setup.sampleRate);
1043        self.gui.set_sample_rate(setup.sampleRate);
1044        kResultOk
1045    }
1046
1047    unsafe fn setProcessing(&self, state: TBool) -> tresult {
1048        self.lock().processing = state != 0;
1049        kResultOk
1050    }
1051
1052    unsafe fn process(&self, data: *mut ProcessData) -> tresult {
1053        unsafe { self.process_audio(data) }
1054    }
1055
1056    unsafe fn getTailSamples(&self) -> uint32 {
1057        let inner = self.lock();
1058        let Some(state) = inner.state.as_ref() else {
1059            return 0;
1060        };
1061        L::tail_length(state)
1062    }
1063}
1064
1065impl<L: PluginLogic> IEditControllerTrait for Component<L> {
1066    unsafe fn setComponentState(&self, state: *mut IBStream) -> tresult {
1067        // Single component: the component state IS the param state.
1068        load_state(&*self.params, state)
1069    }
1070
1071    unsafe fn setState(&self, _state: *mut IBStream) -> tresult {
1072        // No controller-only state beyond params.
1073        kResultOk
1074    }
1075
1076    unsafe fn getState(&self, _state: *mut IBStream) -> tresult {
1077        kResultOk
1078    }
1079
1080    unsafe fn getParameterCount(&self) -> int32 {
1081        self.params.count() as int32
1082    }
1083
1084    unsafe fn getParameterInfo(&self, paramIndex: int32, info: *mut ParameterInfo) -> tresult {
1085        if info.is_null() || paramIndex < 0 {
1086            return kInvalidArgument;
1087        }
1088        let infos = self.params.param_infos();
1089        let Some(meta) = infos.get(paramIndex as usize) else {
1090            return kInvalidArgument;
1091        };
1092        // SAFETY: non-null, host-owned out struct per spec.
1093        fill_parameter_info(meta, unsafe { &mut *info });
1094        kResultOk
1095    }
1096
1097    unsafe fn getParamStringByValue(
1098        &self,
1099        id: ParamID,
1100        valueNormalized: ParamValue,
1101        string: *mut String128,
1102    ) -> tresult {
1103        if string.is_null() {
1104            return kInvalidArgument;
1105        }
1106        let Some(meta) = self.find_info(id) else {
1107            return kInvalidArgument;
1108        };
1109        let plain = meta.range.denormalize(valueNormalized);
1110        let text = self
1111            .params
1112            .format_value(id, plain)
1113            .unwrap_or_else(|| format!("{plain:.2}"));
1114        // SAFETY: non-null, host-owned out buffer per spec.
1115        write_string128(unsafe { &mut *string }, &text);
1116        kResultOk
1117    }
1118
1119    unsafe fn getParamValueByString(
1120        &self,
1121        id: ParamID,
1122        string: *mut TChar,
1123        valueNormalized: *mut ParamValue,
1124    ) -> tresult {
1125        if string.is_null() || valueNormalized.is_null() {
1126            return kInvalidArgument;
1127        }
1128        let Some(meta) = self.find_info(id) else {
1129            return kInvalidArgument;
1130        };
1131        // SAFETY: non-null NUL-terminated host string per spec.
1132        let text = unsafe { read_tchar(string) };
1133        let Some(plain) = self.params.parse_value(id, &text) else {
1134            return kResultFalse;
1135        };
1136        // SAFETY: non-null, host-owned out value per spec.
1137        unsafe { *valueNormalized = meta.range.normalize(plain) };
1138        kResultOk
1139    }
1140
1141    unsafe fn normalizedParamToPlain(
1142        &self,
1143        id: ParamID,
1144        valueNormalized: ParamValue,
1145    ) -> ParamValue {
1146        self.find_info(id).map_or(valueNormalized, |meta| {
1147            meta.range.denormalize(valueNormalized)
1148        })
1149    }
1150
1151    unsafe fn plainParamToNormalized(&self, id: ParamID, plainValue: ParamValue) -> ParamValue {
1152        self.find_info(id)
1153            .map_or(plainValue, |meta| meta.range.normalize(plainValue))
1154    }
1155
1156    unsafe fn getParamNormalized(&self, id: ParamID) -> ParamValue {
1157        self.params.get_normalized(id).unwrap_or(0.0)
1158    }
1159
1160    unsafe fn setParamNormalized(&self, id: ParamID, value: ParamValue) -> tresult {
1161        self.params.set_normalized_returning_normalized(id, value);
1162        kResultOk
1163    }
1164
1165    unsafe fn setComponentHandler(&self, handler: *mut IComponentHandler) -> tresult {
1166        *self
1167            .gui
1168            .handler
1169            .lock()
1170            .unwrap_or_else(PoisonError::into_inner) = if handler.is_null() {
1171            None
1172        } else {
1173            Some(handler)
1174        };
1175        kResultOk
1176    }
1177
1178    unsafe fn createView(&self, name: FIDString) -> *mut IPlugView {
1179        // Spec: primary view is named "editor". Empty/null accepted as same.
1180        if !name.is_null() {
1181            // SAFETY: host C string for the view name.
1182            let name = unsafe { CStr::from_ptr(name) };
1183            if !name.to_bytes().is_empty() && name.to_bytes() != b"editor" {
1184                return ptr::null_mut();
1185            }
1186        }
1187        let has_editor = self
1188            .gui
1189            .editor
1190            .lock()
1191            .unwrap_or_else(PoisonError::into_inner)
1192            .is_some();
1193        if !has_editor {
1194            return ptr::null_mut();
1195        }
1196        gui::PlugView::create(Arc::clone(&self.gui))
1197    }
1198}
1199
1200// ---------------------------------------------------------------------------
1201// MIDI input helpers
1202// ---------------------------------------------------------------------------
1203
1204/// Write one block into host output pointers (main + optional aux, ≤4 ch).
1205#[allow(clippy::too_many_arguments)]
1206unsafe fn run_process_chunk<L: PluginLogic>(
1207    state: &mut L::DspState,
1208    params: &L::Params,
1209    in_refs: &[&[f32]],
1210    out_ptrs: [*mut f32; MAX_AUDIO_CH],
1211    out_ch: usize,
1212    main_out_ch: usize,
1213    t0: usize,
1214    chunk_len: usize,
1215    main_in_ch: usize,
1216    sidechain_in_ch: usize,
1217    ctx: &mut ProcessContext,
1218) -> aura_core::ProcessStatus {
1219    unsafe fn slice_out<'a>(p: *mut f32, t0: usize, n: usize) -> &'a mut [f32] {
1220        unsafe { std::slice::from_raw_parts_mut(p.add(t0), n) }
1221    }
1222    let main_out = main_out_ch.min(out_ch);
1223    match out_ch {
1224        1 => {
1225            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
1226            let mut outs = [&mut s0 as &mut [f32]];
1227            let mut buffer = unsafe {
1228                AudioBuffer::from_slices_with_buses_unchecked(
1229                    in_refs,
1230                    &mut outs,
1231                    chunk_len,
1232                    main_in_ch,
1233                    sidechain_in_ch,
1234                    main_out,
1235                )
1236            };
1237            L::process(state, params, &mut buffer, ctx)
1238        }
1239        2 => {
1240            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
1241            let mut s1 = unsafe { slice_out(out_ptrs[1], t0, chunk_len) };
1242            let mut outs = [&mut s0 as &mut [f32], &mut s1];
1243            let mut buffer = unsafe {
1244                AudioBuffer::from_slices_with_buses_unchecked(
1245                    in_refs,
1246                    &mut outs,
1247                    chunk_len,
1248                    main_in_ch,
1249                    sidechain_in_ch,
1250                    main_out,
1251                )
1252            };
1253            L::process(state, params, &mut buffer, ctx)
1254        }
1255        3 => {
1256            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
1257            let mut s1 = unsafe { slice_out(out_ptrs[1], t0, chunk_len) };
1258            let mut s2 = unsafe { slice_out(out_ptrs[2], t0, chunk_len) };
1259            let mut outs = [&mut s0 as &mut [f32], &mut s1, &mut s2];
1260            let mut buffer = unsafe {
1261                AudioBuffer::from_slices_with_buses_unchecked(
1262                    in_refs,
1263                    &mut outs,
1264                    chunk_len,
1265                    main_in_ch,
1266                    sidechain_in_ch,
1267                    main_out,
1268                )
1269            };
1270            L::process(state, params, &mut buffer, ctx)
1271        }
1272        4 => {
1273            let mut s0 = unsafe { slice_out(out_ptrs[0], t0, chunk_len) };
1274            let mut s1 = unsafe { slice_out(out_ptrs[1], t0, chunk_len) };
1275            let mut s2 = unsafe { slice_out(out_ptrs[2], t0, chunk_len) };
1276            let mut s3 = unsafe { slice_out(out_ptrs[3], t0, chunk_len) };
1277            let mut outs = [&mut s0 as &mut [f32], &mut s1, &mut s2, &mut s3];
1278            let mut buffer = unsafe {
1279                AudioBuffer::from_slices_with_buses_unchecked(
1280                    in_refs,
1281                    &mut outs,
1282                    chunk_len,
1283                    main_in_ch,
1284                    sidechain_in_ch,
1285                    main_out,
1286                )
1287            };
1288            L::process(state, params, &mut buffer, ctx)
1289        }
1290        _ => aura_core::ProcessStatus::Error,
1291    }
1292}
1293
1294/// Drain the host input event list into `midi` (note on/off only).
1295unsafe fn collect_input_events(events: *mut IEventList, midi: &mut MidiBuffer) {
1296    // SAFETY: host guarantees `events` is valid for this process call;
1297    // ComRef does not touch the refcount.
1298    let Some(events) = (unsafe { ComRef::from_raw(events) }) else {
1299        return;
1300    };
1301    let count = unsafe { events.getEventCount() };
1302    for i in 0..count {
1303        // SAFETY: plain-C out struct, fully overwritten by getEvent on success.
1304        let mut ev: Event = unsafe { std::mem::zeroed() };
1305        if unsafe { events.getEvent(i, &mut ev) } != kResultOk {
1306            continue;
1307        }
1308        let offset = ev.sampleOffset.max(0) as u32;
1309        let msg = match u32::from(ev.r#type) {
1310            t if t == EventTypes_::kNoteOnEvent as u32 => {
1311                // SAFETY: union field valid for kNoteOnEvent.
1312                let n = unsafe { ev.__field0.noteOn };
1313                note_to_midi(true, n.channel, n.pitch, n.velocity)
1314            }
1315            t if t == EventTypes_::kNoteOffEvent as u32 => {
1316                // SAFETY: union field valid for kNoteOffEvent.
1317                let n = unsafe { ev.__field0.noteOff };
1318                note_to_midi(false, n.channel, n.pitch, n.velocity)
1319            }
1320            _ => None,
1321        };
1322        if let Some(msg) = msg
1323            && accept_midi_event(midi.len(), true)
1324        {
1325            midi.push(offset, msg);
1326        }
1327    }
1328}
1329
1330/// Map a VST3 note event into channel MIDI (velocity 0..=127), same
1331/// conventions as the CLAP wrapper.
1332fn note_to_midi(is_on: bool, channel: i16, pitch: i16, velocity: f32) -> Option<MidiMessage> {
1333    if !(0..=127).contains(&pitch) {
1334        return None;
1335    }
1336    let channel = channel.clamp(0, 15) as u8;
1337    let velocity = (f64::from(velocity) * 127.0).round().clamp(0.0, 127.0) as u8;
1338    if is_on {
1339        Some(MidiMessage::note_on(channel, pitch as u8, velocity.max(1)))
1340    } else {
1341        Some(MidiMessage::note_off(channel, pitch as u8, velocity))
1342    }
1343}
1344
1345/// Push plugin-generated MIDI events to the host's VST3 output event list.
1346unsafe fn emit_output_events(events: *mut IEventList, midi: &MidiBuffer) {
1347    let Some(events) = (unsafe { ComRef::from_raw(events) }) else {
1348        return;
1349    };
1350    for ev in midi.iter() {
1351        let mut vst_ev: Event = unsafe { std::mem::zeroed() };
1352        vst_ev.busIndex = 0;
1353        vst_ev.sampleOffset = ev.sample_offset as int32;
1354        vst_ev.flags = 0;
1355        match ev.message.status {
1356            MidiStatus::NoteOn if ev.message.data2 > 0 => {
1357                vst_ev.r#type = EventTypes_::kNoteOnEvent as u16;
1358                vst_ev.__field0.noteOn = NoteOnEvent {
1359                    channel: i16::from(ev.message.channel),
1360                    pitch: i16::from(ev.message.data1),
1361                    tuning: 0.0,
1362                    velocity: f32::from(ev.message.data2) / 127.0,
1363                    length: 0,
1364                    noteId: -1,
1365                };
1366                unsafe { events.addEvent(&mut vst_ev) };
1367            }
1368            MidiStatus::NoteOn | MidiStatus::NoteOff => {
1369                vst_ev.r#type = EventTypes_::kNoteOffEvent as u16;
1370                vst_ev.__field0.noteOff = NoteOffEvent {
1371                    channel: i16::from(ev.message.channel),
1372                    pitch: i16::from(ev.message.data1),
1373                    velocity: f32::from(ev.message.data2) / 127.0,
1374                    noteId: -1,
1375                    tuning: 0.0,
1376                };
1377                unsafe { events.addEvent(&mut vst_ev) };
1378            }
1379            _ => {
1380                // Non-note messages are not emitted by the VST3 wrapper yet
1381                // (would need LegacyMIDICCOutEvent or DataEvent support).
1382            }
1383        }
1384    }
1385}
1386
1387// ---------------------------------------------------------------------------
1388// Bus / speaker helpers
1389// ---------------------------------------------------------------------------
1390
1391fn speaker_channel_count(arr: SpeakerArrangement) -> u32 {
1392    use vst3::Steinberg::Vst::SpeakerArr::{kMono, kStereo};
1393    if arr == kMono {
1394        1
1395    } else if arr == kStereo {
1396        2
1397    } else {
1398        // Fall back to popcount of speaker bits for exotic layouts we reject.
1399        arr.count_ones()
1400    }
1401}
1402
1403fn arrangement_for_channels(n: u32) -> Option<SpeakerArrangement> {
1404    use vst3::Steinberg::Vst::SpeakerArr::{kMono, kStereo};
1405    match n {
1406        1 => Some(kMono),
1407        2 => Some(kStereo),
1408        _ => None,
1409    }
1410}
1411
1412// ---------------------------------------------------------------------------
1413// Param / state / transport helpers
1414// ---------------------------------------------------------------------------
1415
1416fn fill_parameter_info(meta: &ParamInfo, out: &mut ParameterInfo) {
1417    out.id = meta.id;
1418    write_string128(&mut out.title, meta.name);
1419    write_string128(&mut out.shortTitle, meta.short_name);
1420    write_string128(&mut out.units, meta.unit.as_str());
1421    let stepped = matches!(
1422        meta.kind,
1423        ParamValueKind::Int | ParamValueKind::Bool | ParamValueKind::Enum
1424    );
1425    out.stepCount = if stepped {
1426        meta.range.step_count().map_or(
1427            // Bool fallback when the range isn't discrete.
1428            int32::from(meta.kind == ParamValueKind::Bool),
1429            |n| n.get() as int32,
1430        )
1431    } else {
1432        0
1433    };
1434    out.defaultNormalizedValue = meta.range.normalize(meta.default_plain);
1435    out.unitId = kRootUnitId;
1436    let mut flags: int32 = 0;
1437    if meta.flags.contains(ParamFlags::AUTOMATABLE) {
1438        flags |= kCanAutomate;
1439    }
1440    if meta.flags.contains(ParamFlags::HIDDEN) {
1441        flags |= kIsHidden;
1442    }
1443    if meta.flags.contains(ParamFlags::READONLY) {
1444        flags |= kIsReadOnly;
1445    }
1446    if meta.flags.contains(ParamFlags::IS_BYPASS) {
1447        flags |= kIsBypass;
1448    }
1449    if meta.kind == ParamValueKind::Enum {
1450        flags |= kIsList;
1451    }
1452    out.flags = flags;
1453}
1454
1455fn map_process_mode(mode: int32) -> ProcessMode {
1456    if mode == kPrefetch as int32 {
1457        ProcessMode::Buffered
1458    } else if mode == kOffline as int32 {
1459        ProcessMode::Offline
1460    } else {
1461        ProcessMode::Realtime
1462    }
1463}
1464
1465fn map_transport(ctx: &vst3::Steinberg::Vst::ProcessContext) -> Transport {
1466    let s = ctx.state;
1467    let has = |flag: u32| s & flag != 0;
1468    let time_sig = has(kTimeSigValid as u32)
1469        .then_some((ctx.timeSigNumerator as u16, ctx.timeSigDenominator as u16));
1470    let bar_number = if has(kBarPositionValid as u32)
1471        && let Some((num, den)) = time_sig
1472        && den > 0
1473    {
1474        let quarters_per_bar = f64::from(num) * 4.0 / f64::from(den);
1475        Some((ctx.barPositionMusic / quarters_per_bar).floor() as i32)
1476    } else {
1477        None
1478    };
1479    Transport {
1480        playing: has(kPlaying as u32),
1481        recording: has(kRecording as u32),
1482        loop_active: has(kCycleActive as u32),
1483        tempo: has(kTempoValid as u32).then_some(ctx.tempo),
1484        position_beats: has(kProjectTimeMusicValid as u32).then_some(ctx.projectTimeMusic),
1485        position_seconds: (ctx.sampleRate > 0.0)
1486            .then_some(ctx.projectTimeSamples as f64 / ctx.sampleRate),
1487        loop_beats: has(kCycleValid as u32).then_some((ctx.cycleStartMusic, ctx.cycleEndMusic)),
1488        time_signature: time_sig,
1489        bar_number,
1490    }
1491}
1492
1493/// Read a host stream to EOF.
1494unsafe fn read_stream(stream: *mut IBStream) -> Option<Vec<u8>> {
1495    // SAFETY: host passes a valid IBStream; ComRef does not touch the refcount.
1496    let stream = unsafe { ComRef::from_raw(stream) }?;
1497    let mut blob = Vec::new();
1498    let mut chunk = [0u8; 1024];
1499    loop {
1500        let mut num_read: int32 = 0;
1501        // SAFETY: `chunk` is a valid writable buffer of `chunk.len()` bytes.
1502        let result = unsafe {
1503            stream.read(
1504                chunk.as_mut_ptr().cast::<c_void>(),
1505                chunk.len() as int32,
1506                &mut num_read,
1507            )
1508        };
1509        if result != kResultOk || num_read <= 0 {
1510            break;
1511        }
1512        blob.extend_from_slice(&chunk[..num_read as usize]);
1513        if (num_read as usize) < chunk.len() {
1514            break;
1515        }
1516    }
1517    Some(blob)
1518}
1519
1520fn load_state(params: &dyn Params, stream: *mut IBStream) -> tresult {
1521    host_callback_with("VST3", "state_load", kInternalError, || {
1522        load_state_inner(params, stream)
1523    })
1524}
1525
1526fn load_state_inner(params: &dyn Params, stream: *mut IBStream) -> tresult {
1527    let Some(blob) = (unsafe { read_stream(stream) }) else {
1528        return kInvalidArgument;
1529    };
1530    if decode_state(params, &blob) {
1531        kResultOk
1532    } else {
1533        kResultFalse
1534    }
1535}
1536
1537fn save_state(params: &dyn Params, stream: *mut IBStream) -> tresult {
1538    host_callback_with("VST3", "state_save", kInternalError, || {
1539        // SAFETY: host passes a valid IBStream; ComRef does not touch the refcount.
1540        let Some(stream) = (unsafe { ComRef::from_raw(stream) }) else {
1541            return kInvalidArgument;
1542        };
1543        let blob = encode_state(params);
1544        let mut written: int32 = 0;
1545        // SAFETY: `blob` is a valid readable buffer of `blob.len()` bytes; the
1546        // stream only reads from it.
1547        let result = unsafe {
1548            stream.write(
1549                blob.as_ptr().cast_mut().cast::<c_void>(),
1550                blob.len() as int32,
1551                &mut written,
1552            )
1553        };
1554        if result == kResultOk && written as usize == blob.len() {
1555            kResultOk
1556        } else {
1557            kInternalError
1558        }
1559    })
1560}
1561
1562// ---------------------------------------------------------------------------
1563// Tests
1564// ---------------------------------------------------------------------------
1565
1566#[cfg(test)]
1567mod tests {
1568    use super::tuid_bytes;
1569
1570    #[test]
1571    fn tuid_deterministic() {
1572        assert_eq!(
1573            tuid_bytes("com.lxaudiolabs.smoke-gain"),
1574            tuid_bytes("com.lxaudiolabs.smoke-gain")
1575        );
1576    }
1577
1578    #[test]
1579    fn tuid_differs_for_different_strings() {
1580        assert_ne!(
1581            tuid_bytes("com.lxaudiolabs.gain"),
1582            tuid_bytes("com.lxaudiolabs.eq")
1583        );
1584        // Never the all-zero TUID for a non-empty string.
1585        assert!(tuid_bytes("com.lxaudiolabs.gain").iter().any(|b| *b != 0));
1586    }
1587}