Skip to main content

aura_lv2/
lib.rs

1//! Minimal LV2 wrapper for AURA.
2//!
3//! **Spec:** [lv2plug.in](https://lv2plug.in/) — bindings [`lv2-sys`](https://crates.io/crates/lv2-sys).
4//!
5//! ```ignore
6//! aura_lv2::export_lv2!(MyPlugin);
7//! ```
8//!
9//! Bundle layout (written by `cargo aura install --lv2`):
10//! ```text
11//! name.lv2/
12//!   manifest.ttl
13//!   plugin.ttl
14//!   <binary>          # smoke_gain.dll / libsmoke_gain.so / …
15//! ```
16//!
17//! **Reduced `PluginLogic` subset vs CLAP/VST3:** only the **first**
18//! `bus_layouts()` entry; no latency/tail/presets/transport parity; control
19//! ports update once per `run` (not sample-accurate `CHUNKED`).
20//!
21//! Port map (first layout): mono → 0 in · 1 out · 2+ controls; stereo →
22//! 0/1 in · 2/3 out · 4+ controls (+ sidechain/aux channels when declared).
23//! MIDI atom ports append after controls when `accepts_midi_in` /
24//! `emits_midi`. State: shared [`aura_core::encode_state`] blob. GUI: same
25//! [`Editor`](aura_core::editor::Editor) as CLAP/VST3 via `lv2ui_descriptor`.
26
27#![allow(clippy::missing_safety_doc)]
28#![allow(non_snake_case)]
29// ponytail: LV2 FFI — raw pointers, similar audio channel names, format noise.
30#![allow(
31    clippy::ptr_as_ptr,
32    clippy::ref_as_ptr,
33    clippy::borrow_as_ptr,
34    clippy::cast_ptr_alignment,
35    clippy::cast_possible_truncation,
36    clippy::cast_sign_loss,
37    clippy::cast_possible_wrap,
38    clippy::cast_precision_loss,
39    clippy::similar_names,
40    clippy::must_use_candidate,
41    clippy::if_not_else,
42    clippy::items_after_statements,
43    clippy::uninlined_format_args,
44    clippy::needless_raw_string_hashes
45)]
46
47mod ttl;
48mod ui;
49
50pub use ttl::{BundleTtl, generate_ttl, generate_ttl_with_layout, generate_ttl_with_layout_and_ui};
51pub use ui::ui_descriptor;
52
53use std::ffi::{CStr, CString, c_char, c_void};
54use std::ptr;
55use std::sync::{Arc, OnceLock};
56
57use aura_core::info::PluginInfo;
58use aura_core::{
59    AudioBuffer, AudioConfig, BusLayout, MidiBuffer, MidiMessage, MidiStatus, NoteBuffer,
60    PluginLogic, ProcessContext, ProcessMode, UmpBuffer, append_midi_as_ump, append_notes_as_midi,
61    append_ump_as_midi, decode_state, encode_state, host_callback, host_callback_with, layout_at,
62};
63use aura_params::Params;
64use lv2_sys::{
65    LV2_ATOM__Chunk, LV2_ATOM__Sequence, LV2_Atom, LV2_Atom_Event, LV2_Atom_Sequence,
66    LV2_Descriptor, LV2_Feature, LV2_Handle, LV2_MIDI__MidiEvent, LV2_STATE__interface,
67    LV2_State_Flags, LV2_State_Handle, LV2_State_Interface, LV2_State_Retrieve_Function,
68    LV2_State_Status, LV2_State_Status_LV2_STATE_ERR_NO_FEATURE,
69    LV2_State_Status_LV2_STATE_ERR_UNKNOWN, LV2_State_Status_LV2_STATE_SUCCESS,
70    LV2_State_Store_Function, LV2_URID__map, LV2_URID_Map,
71};
72
73// ---------------------------------------------------------------------------
74// Export
75// ---------------------------------------------------------------------------
76
77/// Hidden re-export for the macro.
78#[doc(hidden)]
79pub use lv2_sys as __lv2_sys;
80
81/// Export `$logic` as this cdylib's LV2 entry (`lv2_descriptor` + `lv2ui_descriptor`).
82#[macro_export]
83macro_rules! export_lv2 {
84    ($logic:ty) => {
85        /// LV2 discovery entry — host calls with index 0 for the single plugin.
86        #[unsafe(no_mangle)]
87        pub unsafe extern "C" fn lv2_descriptor(
88            index: u32,
89        ) -> *const $crate::__lv2_sys::LV2_Descriptor {
90            $crate::descriptor::<$logic>(index)
91        }
92
93        /// LV2 UI discovery entry — host calls with index 0 for the single UI.
94        #[unsafe(no_mangle)]
95        pub unsafe extern "C" fn lv2ui_descriptor(
96            index: u32,
97        ) -> *const $crate::__lv2_sys::LV2UI_Descriptor {
98            $crate::ui_descriptor::<$logic>(index)
99        }
100    };
101}
102
103// ---------------------------------------------------------------------------
104// URI / metadata helpers
105// ---------------------------------------------------------------------------
106
107/// Plugin URI: `PluginInfo::lv2_uri` or derived `https://lx-audiolabs.com/lv2/<bundle_id>`.
108pub fn plugin_uri(info: &PluginInfo) -> String {
109    if !info.lv2_uri.is_empty() {
110        info.lv2_uri.to_string()
111    } else {
112        format!("https://lx-audiolabs.com/lv2/{}", info.bundle_id)
113    }
114}
115
116fn uri_cstring<L: PluginLogic>() -> &'static CStr {
117    static CELL: OnceLock<CString> = OnceLock::new();
118    CELL.get_or_init(|| {
119        let s = plugin_uri(&L::info());
120        CString::new(s).expect("plugin URI has interior NUL")
121    })
122    .as_c_str()
123}
124
125fn param_list<L: PluginLogic>() -> Vec<aura_params::ParamInfo> {
126    let static_list = L::Params::param_infos_static();
127    if static_list.is_empty() {
128        L::Params::default().param_infos()
129    } else {
130        static_list
131    }
132}
133
134// ---------------------------------------------------------------------------
135// Instance
136// ---------------------------------------------------------------------------
137
138/// Static layout for LV2 (first declared `bus_layouts()` entry).
139fn static_layout<L: PluginLogic>() -> BusLayout {
140    layout_at(&L::bus_layouts(), 0)
141}
142
143fn audio_port_count(layout: BusLayout) -> usize {
144    layout.total_input_channels() as usize + layout.total_output_channels() as usize
145}
146
147struct Instance<L: PluginLogic> {
148    params: Arc<L::Params>,
149    state: Option<L::DspState>,
150    sample_rate: f64,
151    /// Audio + control port data locations (host-owned).
152    ports: Vec<*mut c_void>,
153    state_key: u32,
154    chunk_type: u32,
155    layout: BusLayout,
156    /// First control-port index (= audio port count).
157    ctrl0: u32,
158    /// Atom-sequence MIDI input port index when the plugin accepts MIDI.
159    midi_in_port: Option<u32>,
160    /// Atom-sequence MIDI output port index when the plugin emits MIDI.
161    midi_out_port: Option<u32>,
162    /// URID for `midi:MidiEvent` (0 when unmapped / no MIDI port).
163    midi_event_type: u32,
164    /// URID for `atom:Sequence` (0 when unmapped / no MIDI port).
165    sequence_type: u32,
166    scratch: ProcessScratch,
167}
168
169/// Audio-thread working set. Reserved in `activate`.
170struct ProcessScratch {
171    midi: MidiBuffer,
172    midi_out: MidiBuffer,
173    notes_out: NoteBuffer,
174    ump: UmpBuffer,
175    ump_out: UmpBuffer,
176    silence: Vec<f32>,
177}
178
179const MAX_AUDIO_CH: usize = 8;
180const MAX_MIDI_EVENTS: usize = 4096;
181/// LV2 has no host max-block; reserve a generous default and grow once if needed.
182const LV2_SCRATCH_FRAMES: usize = 8192;
183
184impl ProcessScratch {
185    fn new() -> Self {
186        Self {
187            midi: MidiBuffer::new(),
188            midi_out: MidiBuffer::new(),
189            notes_out: NoteBuffer::new(),
190            ump: UmpBuffer::new(),
191            ump_out: UmpBuffer::new(),
192            silence: Vec::new(),
193        }
194    }
195
196    fn prepare(&mut self, max_frames: usize) {
197        self.midi.reserve(MAX_MIDI_EVENTS + 128);
198        self.midi_out.reserve(256);
199        self.notes_out.reserve(256);
200        self.ump.reserve(MAX_MIDI_EVENTS);
201        self.ump_out.reserve(256);
202        if self.silence.len() < max_frames {
203            self.silence.resize(max_frames, 0.0);
204        }
205    }
206}
207
208impl<L: PluginLogic> Instance<L> {
209    fn from_handle<'a>(handle: LV2_Handle) -> Option<&'a mut Self> {
210        if handle.is_null() {
211            return None;
212        }
213        Some(unsafe { &mut *(handle as *mut Self) })
214    }
215
216    fn n_ports() -> usize {
217        audio_port_count(static_layout::<L>())
218            + param_list::<L>().len()
219            + usize::from(L::info().accepts_midi_in)
220            + usize::from(L::info().emits_midi)
221    }
222}
223
224// ---------------------------------------------------------------------------
225// Descriptor callbacks
226// ---------------------------------------------------------------------------
227
228/// Public for the export macro / tests.
229#[must_use]
230pub fn descriptor<L: PluginLogic>(index: u32) -> *const LV2_Descriptor {
231    if index != 0 {
232        return ptr::null();
233    }
234    // OnceLock needs Sync; LV2_Descriptor has raw pointers. Box + leak is fine
235    // for a process-lifetime descriptor (same pattern many LV2 plugins use).
236    static CELL: OnceLock<usize> = OnceLock::new();
237    let addr = *CELL.get_or_init(|| {
238        let desc = Box::new(LV2_Descriptor {
239            URI: uri_cstring::<L>().as_ptr(),
240            instantiate: Some(instantiate::<L>),
241            connect_port: Some(connect_port::<L>),
242            activate: Some(activate::<L>),
243            run: Some(run::<L>),
244            deactivate: Some(deactivate::<L>),
245            cleanup: Some(cleanup::<L>),
246            extension_data: Some(extension_data::<L>),
247        });
248        Box::into_raw(desc) as usize
249    });
250    addr as *const LV2_Descriptor
251}
252
253unsafe extern "C" fn instantiate<L: PluginLogic>(
254    _descriptor: *const LV2_Descriptor,
255    sample_rate: f64,
256    _bundle_path: *const c_char,
257    features: *const *const LV2_Feature,
258) -> LV2_Handle {
259    let params = Arc::new(L::Params::default());
260    params.set_sample_rate(sample_rate);
261    let layout = static_layout::<L>();
262    let n = Instance::<L>::n_ports();
263    let ctrl0 = audio_port_count(layout) as u32;
264    let mut map_ptr: Option<*const LV2_URID_Map> = None;
265    if !features.is_null() {
266        let mut i = 0isize;
267        loop {
268            let f = unsafe { *features.offset(i) };
269            if f.is_null() {
270                break;
271            }
272            let uri = unsafe { (*f).URI };
273            if !uri.is_null() {
274                let u = unsafe { CStr::from_ptr(uri) };
275                if u.to_bytes() == &LV2_URID__map[..LV2_URID__map.len() - 1] {
276                    map_ptr = Some(unsafe { (*f).data as *const LV2_URID_Map });
277                }
278            }
279            i += 1;
280        }
281    }
282
283    let (state_key, chunk_type) = map_ptr
284        .and_then(|m| unsafe { map_state_urids(m, &L::info()) })
285        .unwrap_or((0, 0));
286
287    let info = L::info();
288    // MIDI atom ports sit after controls — audio/control indices unchanged.
289    let mut midi_in_port = None;
290    let mut midi_out_port = None;
291    let mut next_midi = audio_port_count(layout) + param_list::<L>().len();
292    if info.accepts_midi_in {
293        midi_in_port = Some(next_midi as u32);
294        next_midi += 1;
295    }
296    if info.emits_midi {
297        midi_out_port = Some(next_midi as u32);
298    }
299    let (midi_event_type, sequence_type) = match (midi_in_port.or(midi_out_port), map_ptr) {
300        (Some(_), Some(m)) => unsafe {
301            (
302                map_urid(m, LV2_MIDI__MidiEvent),
303                map_urid(m, LV2_ATOM__Sequence),
304            )
305        },
306        _ => (0, 0),
307    };
308
309    let inst = Box::new(Instance::<L> {
310        params,
311        state: None,
312        sample_rate,
313        ports: vec![ptr::null_mut(); n],
314        state_key,
315        chunk_type,
316        layout,
317        ctrl0,
318        midi_in_port,
319        midi_out_port,
320        midi_event_type,
321        sequence_type,
322        scratch: ProcessScratch::new(),
323    });
324    Box::into_raw(inst) as LV2_Handle
325}
326
327/// Map one URI to a URID; 0 on failure.
328unsafe fn map_urid(map: *const LV2_URID_Map, uri: &'static [u8]) -> u32 {
329    let map = unsafe { &*map };
330    let Some(map_fn) = map.map else {
331        return 0;
332    };
333    unsafe { map_fn(map.handle, uri.as_ptr().cast::<c_char>()) }
334}
335
336unsafe fn map_state_urids(map: *const LV2_URID_Map, info: &PluginInfo) -> Option<(u32, u32)> {
337    let map = unsafe { &*map };
338    let map_fn = map.map?;
339    let key_uri = CString::new(format!("{}#state", plugin_uri(info))).ok()?;
340    let key = unsafe { map_fn(map.handle, key_uri.as_ptr()) };
341    let chunk = unsafe { map_fn(map.handle, LV2_ATOM__Chunk.as_ptr().cast::<c_char>()) };
342    if key == 0 || chunk == 0 {
343        return None;
344    }
345    Some((key, chunk))
346}
347
348unsafe extern "C" fn connect_port<L: PluginLogic>(
349    instance: LV2_Handle,
350    port: u32,
351    data_location: *mut c_void,
352) {
353    let Some(inst) = Instance::<L>::from_handle(instance) else {
354        return;
355    };
356    if let Some(slot) = inst.ports.get_mut(port as usize) {
357        *slot = data_location;
358    }
359}
360
361unsafe extern "C" fn activate<L: PluginLogic>(instance: LV2_Handle) {
362    let Some(inst) = Instance::<L>::from_handle(instance) else {
363        return;
364    };
365    // Block size unknown until first run — use a generous default for reset.
366    let config = AudioConfig::new(inst.sample_rate, 8192)
367        .with_process_mode(ProcessMode::Realtime)
368        .with_channels(
369            inst.layout.main_input_channels(),
370            inst.layout.main_output_channels(),
371        )
372        .with_sidechain_channels(inst.layout.sidechain_input_channels())
373        .with_aux_channels(inst.layout.aux_output_channels());
374    let mut dsp = L::init(&inst.params, inst.sample_rate);
375    L::reset(&mut dsp, &inst.params, &config);
376    inst.scratch.prepare(LV2_SCRATCH_FRAMES);
377    inst.state = Some(dsp);
378}
379
380unsafe extern "C" fn deactivate<L: PluginLogic>(instance: LV2_Handle) {
381    if let Some(inst) = Instance::<L>::from_handle(instance) {
382        inst.state = None;
383    }
384}
385
386unsafe extern "C" fn cleanup<L: PluginLogic>(instance: LV2_Handle) {
387    if !instance.is_null() {
388        drop(unsafe { Box::from_raw(instance as *mut Instance<L>) });
389    }
390}
391
392unsafe extern "C" fn run<L: PluginLogic>(instance: LV2_Handle, sample_count: u32) {
393    host_callback("LV2", "run", || {
394        let Some(inst) = Instance::<L>::from_handle(instance) else {
395            return;
396        };
397        let n = sample_count as usize;
398        if n == 0 {
399            return;
400        }
401        if n > inst.scratch.silence.len() {
402            // Host used a larger block than activate reserved — grow once.
403            inst.scratch.prepare(n);
404        }
405
406        // Control ports → params (plain floats).
407        let infos = param_list::<L>();
408        let ctrl0 = inst.ctrl0;
409        for (i, meta) in infos.iter().enumerate() {
410            let port = ctrl0 + i as u32;
411            let ptr = inst
412                .ports
413                .get(port as usize)
414                .copied()
415                .unwrap_or(ptr::null_mut());
416            if !ptr.is_null() {
417                let v = unsafe { *(ptr as *const f32) };
418                inst.params.set_plain(meta.id, f64::from(v));
419            }
420        }
421
422        inst.scratch.midi.clear();
423        inst.scratch.midi_out.clear();
424        inst.scratch.notes_out.clear();
425        inst.scratch.ump.clear();
426        inst.scratch.ump_out.clear();
427        read_midi(inst, n);
428        {
429            let scratch = &mut inst.scratch;
430            append_midi_as_ump(&mut scratch.ump, &scratch.midi);
431        }
432        if inst.state.is_none() {
433            return;
434        }
435
436        let in_ch = inst.layout.main_input_channels() as usize;
437        let sidechain_ch = inst.layout.sidechain_input_channels() as usize;
438        let main_out_ch = inst.layout.main_output_channels() as usize;
439        let total_in_ch = in_ch + sidechain_ch;
440        let out_ch = inst.layout.total_output_channels() as usize;
441        if out_ch == 0 || out_ch > MAX_AUDIO_CH || total_in_ch > MAX_AUDIO_CH {
442            return;
443        }
444
445        // Distinct fields; raw slice so we can also mut-borrow `state`.
446        let silence = unsafe { std::slice::from_raw_parts(inst.scratch.silence.as_ptr(), n) };
447        let mut in_store = [&[] as &[f32]; MAX_AUDIO_CH];
448        for (i, dest) in in_store.iter_mut().enumerate().take(total_in_ch) {
449            *dest = port_audio(inst.ports.get(i).copied(), n).unwrap_or(silence);
450        }
451        let in_refs = &in_store[..total_in_ch];
452
453        let mut out_ptrs = [ptr::null_mut::<f32>(); MAX_AUDIO_CH];
454        for (i, dest) in out_ptrs.iter_mut().take(out_ch).enumerate() {
455            let port_i = total_in_ch + i;
456            *dest = inst
457                .ports
458                .get(port_i)
459                .copied()
460                .unwrap_or(ptr::null_mut())
461                .cast::<f32>();
462        }
463        if out_ptrs[..out_ch].iter().any(|p| p.is_null()) {
464            return;
465        }
466
467        let dsp = inst.state.as_mut().expect("checked is_none above");
468        let mut ctx = ProcessContext::new(inst.sample_rate, n)
469            .with_process_mode(ProcessMode::Realtime)
470            .with_midi(std::mem::take(&mut inst.scratch.midi))
471            .with_midi_out(std::mem::take(&mut inst.scratch.midi_out))
472            .with_notes_out(std::mem::take(&mut inst.scratch.notes_out))
473            .with_ump(std::mem::take(&mut inst.scratch.ump))
474            .with_ump_out(std::mem::take(&mut inst.scratch.ump_out));
475        let _ = unsafe {
476            run_process_chunk::<L>(
477                dsp,
478                &inst.params,
479                in_refs,
480                out_ptrs,
481                out_ch,
482                main_out_ch,
483                n,
484                in_ch,
485                sidechain_ch,
486                &mut ctx,
487            )
488        };
489        inst.scratch.midi = std::mem::take(&mut ctx.midi);
490        append_ump_as_midi(&mut ctx.midi_out, &ctx.ump_out);
491        append_notes_as_midi(&mut ctx.midi_out, &ctx.notes_out);
492        write_midi(inst, n, &ctx.midi_out);
493        inst.scratch.midi_out = std::mem::take(&mut ctx.midi_out);
494        inst.scratch.midi_out.clear();
495        inst.scratch.notes_out = std::mem::take(&mut ctx.notes_out);
496        inst.scratch.notes_out.clear();
497        inst.scratch.ump = std::mem::take(&mut ctx.ump);
498        inst.scratch.ump_out = std::mem::take(&mut ctx.ump_out);
499        inst.scratch.ump_out.clear();
500    });
501}
502
503/// Write one block into host port pointers (main + optional aux, ≤4 ch).
504#[allow(clippy::too_many_arguments)]
505unsafe fn run_process_chunk<L: PluginLogic>(
506    state: &mut L::DspState,
507    params: &L::Params,
508    in_refs: &[&[f32]],
509    out_ptrs: [*mut f32; MAX_AUDIO_CH],
510    out_ch: usize,
511    main_out_ch: usize,
512    frames: usize,
513    main_in_ch: usize,
514    sidechain_in_ch: usize,
515    ctx: &mut ProcessContext,
516) -> aura_core::ProcessStatus {
517    let main_out = main_out_ch.min(out_ch);
518    match out_ch {
519        1 => {
520            let mut s0 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[0], frames) };
521            let mut outs = [&mut s0 as &mut [f32]];
522            let mut buffer = unsafe {
523                AudioBuffer::from_slices_with_buses_unchecked(
524                    in_refs,
525                    &mut outs,
526                    frames,
527                    main_in_ch,
528                    sidechain_in_ch,
529                    main_out,
530                )
531            };
532            L::process(state, params, &mut buffer, ctx)
533        }
534        2 => {
535            let mut s0 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[0], frames) };
536            let mut s1 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[1], frames) };
537            let mut outs = [&mut s0 as &mut [f32], &mut s1];
538            let mut buffer = unsafe {
539                AudioBuffer::from_slices_with_buses_unchecked(
540                    in_refs,
541                    &mut outs,
542                    frames,
543                    main_in_ch,
544                    sidechain_in_ch,
545                    main_out,
546                )
547            };
548            L::process(state, params, &mut buffer, ctx)
549        }
550        3 => {
551            let mut s0 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[0], frames) };
552            let mut s1 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[1], frames) };
553            let mut s2 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[2], frames) };
554            let mut outs = [&mut s0 as &mut [f32], &mut s1, &mut s2];
555            let mut buffer = unsafe {
556                AudioBuffer::from_slices_with_buses_unchecked(
557                    in_refs,
558                    &mut outs,
559                    frames,
560                    main_in_ch,
561                    sidechain_in_ch,
562                    main_out,
563                )
564            };
565            L::process(state, params, &mut buffer, ctx)
566        }
567        4 => {
568            let mut s0 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[0], frames) };
569            let mut s1 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[1], frames) };
570            let mut s2 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[2], frames) };
571            let mut s3 = unsafe { std::slice::from_raw_parts_mut(out_ptrs[3], frames) };
572            let mut outs = [&mut s0 as &mut [f32], &mut s1, &mut s2, &mut s3];
573            let mut buffer = unsafe {
574                AudioBuffer::from_slices_with_buses_unchecked(
575                    in_refs,
576                    &mut outs,
577                    frames,
578                    main_in_ch,
579                    sidechain_in_ch,
580                    main_out,
581                )
582            };
583            L::process(state, params, &mut buffer, ctx)
584        }
585        _ => aura_core::ProcessStatus::Error,
586    }
587}
588
589fn port_audio<'a>(ptr: Option<*mut c_void>, n: usize) -> Option<&'a [f32]> {
590    let p = ptr.filter(|p| !p.is_null())?;
591    Some(unsafe { std::slice::from_raw_parts(p as *const f32, n) })
592}
593
594/// Encode [`MidiBuffer`] events into the MIDI atom-sequence output port.
595///
596/// Writes raw MIDI bytes (status + up to two data bytes) as `midi:MidiEvent`
597/// atoms into the host-provided output sequence buffer. Silently drops events
598/// when the host buffer is too small or unmapped.
599fn write_midi<L: PluginLogic>(inst: &Instance<L>, n: usize, midi: &MidiBuffer) {
600    let Some(port) = inst.midi_out_port else {
601        return;
602    };
603    if inst.midi_event_type == 0 || inst.sequence_type == 0 {
604        return;
605    }
606    let ptr = inst
607        .ports
608        .get(port as usize)
609        .copied()
610        .unwrap_or(ptr::null_mut());
611    if ptr.is_null() {
612        return;
613    }
614    if midi.is_empty() {
615        unsafe {
616            let seq = &mut *(ptr as *mut LV2_Atom_Sequence);
617            seq.atom.type_ = inst.sequence_type;
618            seq.atom.size = (size_of::<LV2_Atom_Sequence>() - size_of::<LV2_Atom>()) as u32;
619            seq.body.unit = 0;
620            seq.body.pad = 0;
621        }
622        return;
623    }
624
625    unsafe {
626        let seq = &mut *(ptr as *mut LV2_Atom_Sequence);
627        let base = ptr as *mut u8;
628        // Use the host-provided size as capacity when non-zero; otherwise fall
629        // back to a conservative default (hosts typically reserve ≥ 4 KiB).
630        let capacity = if seq.atom.size > 0 {
631            size_of::<LV2_Atom>() + seq.atom.size as usize
632        } else {
633            4096
634        };
635
636        seq.atom.type_ = inst.sequence_type;
637        seq.body.unit = 0;
638        seq.body.pad = 0;
639
640        let header_size = size_of::<LV2_Atom_Sequence>();
641        let mut off = header_size;
642        for ev in midi.iter() {
643            let (bytes, len) = message_bytes(ev.message);
644            let event_size = size_of::<LV2_Atom_Event>() + len;
645            let padded = (event_size + 7) & !7;
646            if off + padded > capacity {
647                break; // host buffer full
648            }
649
650            let atom_ev = base.add(off) as *mut LV2_Atom_Event;
651            (*atom_ev).time.frames = i64::from(ev.sample_offset.min(n as u32 - 1));
652            (*atom_ev).body.type_ = inst.midi_event_type;
653            (*atom_ev).body.size = len as u32;
654            let data_ptr = base.add(off + size_of::<LV2_Atom_Event>());
655            std::ptr::copy_nonoverlapping(bytes.as_ptr(), data_ptr, len);
656
657            off += padded;
658        }
659        seq.atom.size = (off - size_of::<LV2_Atom>()) as u32;
660    }
661}
662
663/// Number of raw bytes this message occupies on the wire.
664fn message_len(msg: MidiMessage) -> usize {
665    match msg.status {
666        MidiStatus::ProgramChange | MidiStatus::ChannelPressure => 2,
667        MidiStatus::System => 1,
668        _ => 3,
669    }
670}
671
672/// Raw MIDI bytes for a message. Only the first [`message_len`] bytes are valid.
673fn message_bytes(msg: MidiMessage) -> ([u8; 3], usize) {
674    let len = message_len(msg);
675    ([msg.status_byte(), msg.data1, msg.data2], len)
676}
677
678/// Parse the MIDI atom-sequence input port into `inst.scratch.midi`.
679///
680/// No-op when the plugin has no MIDI port, the host left it unconnected,
681/// URID mapping failed, or the buffer is not an `atom:Sequence`.
682fn read_midi<L: PluginLogic>(inst: &mut Instance<L>, n: usize) {
683    let Some(port) = inst.midi_in_port else {
684        return;
685    };
686    if inst.midi_event_type == 0 {
687        return;
688    }
689    let ptr = inst
690        .ports
691        .get(port as usize)
692        .copied()
693        .unwrap_or(ptr::null_mut());
694    if ptr.is_null() {
695        return;
696    }
697    let midi_event_type = inst.midi_event_type;
698    let sequence_type = inst.sequence_type;
699    let midi = &mut inst.scratch.midi;
700    unsafe {
701        let seq = &*(ptr as *const LV2_Atom_Sequence);
702        if sequence_type != 0 && seq.atom.type_ != sequence_type {
703            return;
704        }
705        let base = ptr as *const u8;
706        // atom.size covers everything after the LV2_Atom header (seq body + events).
707        let total = size_of::<LV2_Atom>() + seq.atom.size as usize;
708        let mut off = size_of::<LV2_Atom_Sequence>();
709        while off + size_of::<LV2_Atom_Event>() <= total {
710            let ev = &*(base.add(off) as *const LV2_Atom_Event);
711            let body_size = ev.body.size as usize;
712            let data_off = off + size_of::<LV2_Atom_Event>();
713            if data_off + body_size > total {
714                break; // corrupt buffer — stop
715            }
716            if ev.body.type_ == midi_event_type && body_size > 0 {
717                if midi.len() >= MAX_MIDI_EVENTS {
718                    break;
719                }
720                // LV2 MIDI events are 1-3 raw bytes, status first (no running status).
721                let data = std::slice::from_raw_parts(base.add(data_off), body_size.min(3));
722                let offset = ev.time.frames.clamp(0, n as i64 - 1) as u32;
723                midi.push(
724                    offset,
725                    MidiMessage::raw(
726                        data[0],
727                        data.get(1).copied().unwrap_or(0),
728                        data.get(2).copied().unwrap_or(0),
729                    ),
730                );
731            }
732            // Events are 64-bit aligned: header + body padded to 8 bytes.
733            off = data_off + ((body_size + 7) & !7);
734        }
735    }
736}
737
738// ---------------------------------------------------------------------------
739// State extension
740// ---------------------------------------------------------------------------
741
742unsafe extern "C" fn extension_data<L: PluginLogic>(uri: *const c_char) -> *const c_void {
743    if uri.is_null() {
744        return ptr::null();
745    }
746    let u = unsafe { CStr::from_ptr(uri) };
747    if u.to_bytes() == &LV2_STATE__interface[..LV2_STATE__interface.len() - 1] {
748        return state_iface::<L>() as *const _ as *const c_void;
749    }
750    ptr::null()
751}
752
753fn state_iface<L: PluginLogic>() -> &'static LV2_State_Interface {
754    static CELL: OnceLock<LV2_State_Interface> = OnceLock::new();
755    CELL.get_or_init(|| LV2_State_Interface {
756        save: Some(state_save::<L>),
757        restore: Some(state_restore::<L>),
758    })
759}
760
761unsafe extern "C" fn state_save<L: PluginLogic>(
762    instance: LV2_Handle,
763    store: LV2_State_Store_Function,
764    handle: LV2_State_Handle,
765    _flags: u32,
766    _features: *const *const LV2_Feature,
767) -> LV2_State_Status {
768    host_callback_with(
769        "LV2",
770        "state_save",
771        LV2_State_Status_LV2_STATE_ERR_UNKNOWN,
772        || {
773            let Some(inst) = Instance::<L>::from_handle(instance) else {
774                return LV2_State_Status_LV2_STATE_ERR_UNKNOWN;
775            };
776            let Some(store) = store else {
777                return LV2_State_Status_LV2_STATE_ERR_NO_FEATURE;
778            };
779            if inst.state_key == 0 || inst.chunk_type == 0 {
780                return LV2_State_Status_LV2_STATE_ERR_NO_FEATURE;
781            }
782            let blob = encode_state(&*inst.params);
783            if blob.is_empty() {
784                return LV2_State_Status_LV2_STATE_SUCCESS;
785            }
786            // LV2_State_Flags underlying repr: u32 on Linux, i32 on Windows.
787            // The cast is required on Windows and redundant (thus linted) on Linux.
788            #[allow(clippy::unnecessary_cast)]
789            let flags = (LV2_State_Flags::LV2_STATE_IS_POD.0
790                | LV2_State_Flags::LV2_STATE_IS_PORTABLE.0) as u32;
791            unsafe {
792                store(
793                    handle,
794                    inst.state_key,
795                    blob.as_ptr().cast(),
796                    blob.len(),
797                    inst.chunk_type,
798                    flags,
799                )
800            }
801        },
802    )
803}
804
805unsafe extern "C" fn state_restore<L: PluginLogic>(
806    instance: LV2_Handle,
807    retrieve: LV2_State_Retrieve_Function,
808    handle: LV2_State_Handle,
809    _flags: u32,
810    _features: *const *const LV2_Feature,
811) -> LV2_State_Status {
812    host_callback_with(
813        "LV2",
814        "state_restore",
815        LV2_State_Status_LV2_STATE_ERR_UNKNOWN,
816        || {
817            let Some(inst) = Instance::<L>::from_handle(instance) else {
818                return LV2_State_Status_LV2_STATE_ERR_UNKNOWN;
819            };
820            let Some(retrieve) = retrieve else {
821                return LV2_State_Status_LV2_STATE_ERR_NO_FEATURE;
822            };
823            if inst.state_key == 0 {
824                return LV2_State_Status_LV2_STATE_ERR_NO_FEATURE;
825            }
826            let mut size = 0usize;
827            let mut type_ = 0u32;
828            let mut flags = 0u32;
829            let ptr =
830                unsafe { retrieve(handle, inst.state_key, &mut size, &mut type_, &mut flags) };
831            if ptr.is_null() || size == 0 {
832                return LV2_State_Status_LV2_STATE_SUCCESS; // empty = defaults
833            }
834            let slice = unsafe { std::slice::from_raw_parts(ptr as *const u8, size) };
835            if decode_state(&*inst.params, slice) {
836                LV2_State_Status_LV2_STATE_SUCCESS
837            } else {
838                LV2_State_Status_LV2_STATE_ERR_UNKNOWN
839            }
840        },
841    )
842}
843
844// ---------------------------------------------------------------------------
845// Bundle helpers (install)
846// ---------------------------------------------------------------------------
847
848/// Generate TTL for `$logic` and the given shared-library stem (crate name with `-` → `_`).
849pub fn bundle_ttl_for<L: PluginLogic>(binary_stem: &str) -> BundleTtl {
850    let info = L::info();
851    let uri = plugin_uri(&info);
852    let params = param_list::<L>();
853    let layout = static_layout::<L>();
854    let has_ui = L::editor(Arc::new(L::Params::default())).is_some();
855    generate_ttl_with_layout_and_ui(&info, &uri, binary_stem, &params, layout, has_ui)
856}
857
858/// Non-generic install helper: TTL from free functions + binary stem.
859///
860/// Defaults to stereo main I/O when the caller has no layout.
861pub fn bundle_ttl_from_parts(
862    info: &PluginInfo,
863    params: &[aura_params::ParamInfo],
864    binary_stem: &str,
865) -> BundleTtl {
866    let uri = plugin_uri(info);
867    generate_ttl(info, &uri, binary_stem, params)
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873    use aura_core::PluginInfo;
874
875    #[test]
876    fn plugin_uri_fallback() {
877        let mut info = PluginInfo::new("X", "V", "0.1", "my-plug");
878        assert_eq!(plugin_uri(&info), "https://lx-audiolabs.com/lv2/my-plug");
879        info.lv2_uri = "https://example.com/lv2/x";
880        assert_eq!(plugin_uri(&info), "https://example.com/lv2/x");
881    }
882}