Skip to main content

maolan_plugin_protocol/
protocol.rs

1use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
2
3/// Magic number: "MAOL" in big-endian ASCII.
4pub const MAGIC: u32 = 0x4D41_4F4C;
5
6/// Current protocol version.
7/// Version 2: parent_window changed from AtomicU32 to AtomicU64 to support 64-bit HWNDs on Windows.
8/// Version 3: Added MIDI output ring for plugin-generated MIDI events.
9/// Version 4: Per-port MIDI input/output rings (MAX_MIDI_PORTS each direction).
10/// Version 5: Plugin-reported latency in samples.
11/// Version 6: Added GUI parent API tag for native window handles.
12pub const VERSION: u32 = 6;
13
14/// Maximum number of audio channels (main + sidechain combined).
15pub const MAX_CHANNELS: usize = 32;
16
17/// Number of audio buses (main + sidechain).
18pub const NUM_BUSES: usize = 2;
19
20/// Maximum audio block size in samples.
21pub const MAX_BLOCK_SIZE: usize = 4096;
22
23/// Capacity of each ring buffer in slots (power of two).
24pub const RING_CAPACITY: usize = 4096;
25
26/// Maximum number of MIDI ports per direction.
27/// Runtime counts may be lower; this is the SHM capacity.
28pub const MAX_MIDI_PORTS: usize = 16;
29
30// --- Section sizes ---
31pub const HEADER_SIZE: usize = 256;
32pub const CONTROL_SIZE: usize = 256;
33pub const AUDIO_BUFFER_SIZE: usize = MAX_CHANNELS * NUM_BUSES * MAX_BLOCK_SIZE * 4; // f32
34pub const PARAM_RING_SIZE: usize = RING_CAPACITY * std::mem::size_of::<ParameterEvent>();
35/// Size of the data area for one MIDI port ring (event slots only).
36pub const MIDI_RING_SIZE: usize = RING_CAPACITY * std::mem::size_of::<MidiEvent>();
37/// Size of one MIDI port ring area including embedded write/read atomics.
38pub const MIDI_PORT_RING_SIZE: usize = {
39    let raw = 8 + MIDI_RING_SIZE; // head + tail atomics + event slots
40    (raw + 15) & !15 // align up to 16 bytes for MidiEvent
41};
42pub const TRANSPORT_SIZE: usize = 256;
43pub const SCRATCH_SIZE: usize = 65536;
44
45// --- Offsets into the shared-memory segment ---
46/// Control area starts right after the header.
47pub const CONTROL_OFFSET: usize = HEADER_SIZE;
48/// Audio buffers start after the control area.
49pub const AUDIO_OFFSET: usize = HEADER_SIZE + CONTROL_SIZE;
50/// Parameter ring buffer.
51pub const PARAM_RING_OFFSET: usize = AUDIO_OFFSET + AUDIO_BUFFER_SIZE;
52/// Echo/parameter-change ring buffer.
53pub const ECHO_RING_OFFSET: usize = PARAM_RING_OFFSET + PARAM_RING_SIZE;
54pub const ECHO_RING_SIZE: usize = RING_CAPACITY * std::mem::size_of::<ParameterEvent>();
55/// Per-port MIDI input rings start after the echo ring.
56pub const MIDI_IN_RINGS_OFFSET: usize = {
57    let end = ECHO_RING_OFFSET + ECHO_RING_SIZE;
58    (end + 255) & !255
59};
60pub const MIDI_IN_RINGS_SIZE: usize = MAX_MIDI_PORTS * MIDI_PORT_RING_SIZE;
61/// Per-port MIDI output rings follow the input rings.
62pub const MIDI_OUT_RINGS_OFFSET: usize = MIDI_IN_RINGS_OFFSET + MIDI_IN_RINGS_SIZE;
63pub const MIDI_OUT_RINGS_SIZE: usize = MAX_MIDI_PORTS * MIDI_PORT_RING_SIZE;
64/// Transport state block (256-byte aligned from here).
65pub const TRANSPORT_OFFSET: usize = {
66    let end = MIDI_OUT_RINGS_OFFSET + MIDI_OUT_RINGS_SIZE;
67    // Align up to 256 bytes
68    (end + 255) & !255
69};
70/// State blob scratch area.
71pub const SCRATCH_OFFSET: usize = TRANSPORT_OFFSET + TRANSPORT_SIZE;
72
73/// Total bytes actively used by the protocol layout.
74pub const LAYOUT_SIZE: usize = SCRATCH_OFFSET + SCRATCH_SIZE;
75
76/// Total shared-memory allocation size (4 MiB, page-aligned).
77pub const SHM_SIZE: usize = 4 * 1024 * 1024;
78
79// --- Control-area indices (all 4-byte atomics inside CONTROL_OFFSET..CONTROL_OFFSET+256) ---
80pub const PARAM_WRITE_IDX_OFFSET: usize = CONTROL_OFFSET;
81pub const PARAM_READ_IDX_OFFSET: usize = CONTROL_OFFSET + 4;
82pub const ECHO_WRITE_IDX_OFFSET: usize = CONTROL_OFFSET + 8;
83pub const ECHO_READ_IDX_OFFSET: usize = CONTROL_OFFSET + 12;
84pub const GUI_MODE_OFFSET: usize = CONTROL_OFFSET + 16;
85pub const GUI_PARENT_API_OFFSET: usize = CONTROL_OFFSET + 20;
86
87/// GUI mode requested by the DAW.
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
89pub enum GuiMode {
90    /// DAW provides a parent window; plugin UI should be embedded.
91    #[default]
92    Embedded = 0,
93    /// DAW cannot provide a parent window; plugin-host must create a top-level window.
94    Floating = 1,
95}
96
97impl GuiMode {
98    pub fn from_u32(value: u32) -> Self {
99        match value {
100            1 => GuiMode::Floating,
101            _ => GuiMode::Embedded,
102        }
103    }
104
105    pub fn as_u32(self) -> u32 {
106        self as u32
107    }
108}
109
110/// Native window-system API for the GUI parent handle.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
112pub enum GuiParentApi {
113    /// No native parent handle has been provided.
114    #[default]
115    None = 0,
116    /// X11/Xlib window ID.
117    X11 = 1,
118    /// Wayland surface/object handle.
119    Wayland = 2,
120}
121
122impl GuiParentApi {
123    pub fn from_u32(value: u32) -> Self {
124        match value {
125            1 => GuiParentApi::X11,
126            2 => GuiParentApi::Wayland,
127            _ => GuiParentApi::None,
128        }
129    }
130
131    pub fn as_u32(self) -> u32 {
132        self as u32
133    }
134}
135
136// --- Structs ---
137
138pub const PARAM_EVENT_VALUE: u32 = 0;
139pub const PARAM_EVENT_MOD: u32 = 1;
140pub const PARAM_EVENT_GESTURE_BEGIN: u32 = 2;
141pub const PARAM_EVENT_GESTURE_END: u32 = 3;
142
143/// Fixed-size parameter change event (16 bytes, 16-byte aligned).
144#[repr(C, align(16))]
145#[derive(Clone, Copy, Debug, Default)]
146pub struct ParameterEvent {
147    pub param_index: u32,
148    pub value: f32,
149    pub sample_offset: u32,
150    pub event_kind: u32,
151}
152
153/// Fixed-size MIDI event (16 bytes, 16-byte aligned).
154#[repr(C, align(16))]
155#[derive(Clone, Copy, Debug, Default)]
156pub struct MidiEvent {
157    pub sample_offset: u32,
158    pub data: [u8; 3],
159    pub channel: u8,
160    pub flags: u16,
161    pub _pad: u16,
162}
163
164/// Transport state block (256 bytes).
165#[repr(C, align(256))]
166#[derive(Clone, Copy, Debug)]
167pub struct TransportState {
168    pub playhead_sample: u64,
169    pub tempo: f64,
170    pub numerator: u32,
171    pub denominator: u32,
172    pub flags: u32,
173    pub sample_rate_hz: f64,
174    _pad: [u8; 256 - 40],
175}
176
177impl Default for TransportState {
178    fn default() -> Self {
179        Self {
180            playhead_sample: 0,
181            tempo: 120.0,
182            numerator: 4,
183            denominator: 4,
184            flags: 0,
185            sample_rate_hz: 0.0,
186            _pad: [0; 256 - 40],
187        }
188    }
189}
190
191/// Shared-memory header (256 bytes).
192#[repr(C, align(256))]
193pub struct ShmHeader {
194    pub magic: u32,
195    pub version: u32,
196    pub flags: u32,
197    pub ready: AtomicU32,
198    pub heartbeat: AtomicU32,
199    pub error_code: u32,
200    pub shutdown_request: AtomicU32,
201    pub tasks_issued: AtomicU32,
202    pub tasks_completed: AtomicU32,
203    pub block_size: AtomicU32,
204    pub num_input_channels: AtomicU32,
205    pub num_output_channels: AtomicU32,
206    /// Number of MIDI input ports actually used by the plugin (<= MAX_MIDI_PORTS).
207    pub midi_in_port_count: AtomicU32,
208    /// Number of MIDI output ports actually used by the plugin (<= MAX_MIDI_PORTS).
209    pub midi_out_port_count: AtomicU32,
210    /// Request type: 0 = none, 1 = save_state, 2 = restore_state, 3 = gui_show, 4 = gui_hide,
211    /// 5 = set_resource_directory, 6 = enumerate_file_references, 7 = update_file_reference,
212    /// 8 = enumerate_lv2_control_ports, 9 = enumerate_clap_parameters
213    pub request_type: AtomicU32,
214    /// Request status: 0 = pending, 1 = success, 2 = error
215    pub request_status: AtomicU32,
216    /// Valid bytes in scratch area for state operations
217    pub scratch_size: AtomicU32,
218    /// Parent window ID for GUI embedding. See GUI_PARENT_API_OFFSET for Unix API tagging.
219    pub parent_window: AtomicU64,
220    /// Set to 1 by the plugin-host when the plugin calls clap_host_state.mark_dirty()
221    pub state_dirty: AtomicU32,
222    /// Current plugin latency in samples, refreshed by the host.
223    pub latency_samples: AtomicU32,
224    _pad: [u8; 256 - 88],
225}
226
227impl ShmHeader {
228    /// Load parent_window as a `usize` (handles 32- and 64-bit platforms).
229    pub fn parent_window_usize(&self) -> usize {
230        self.parent_window.load(Ordering::Acquire) as usize
231    }
232
233    /// Store a `usize` parent_window (truncates on 32-bit, but HWNDs/XIDs are
234    /// always within 64 bits).
235    pub fn set_parent_window(&self, window: usize) {
236        self.parent_window.store(window as u64, Ordering::Release);
237    }
238
239    fn gui_parent_api_atomic(&self) -> &AtomicU32 {
240        // SAFETY: GUI_PARENT_API_OFFSET is inside the control area, which is
241        // within the header's 256-byte allocation. The offset is aligned to 4 bytes.
242        unsafe {
243            let base = self as *const Self as *const u8;
244            &*(base.add(GUI_PARENT_API_OFFSET) as *const AtomicU32)
245        }
246    }
247
248    /// Load the native API of the GUI parent handle.
249    pub fn gui_parent_api(&self) -> GuiParentApi {
250        GuiParentApi::from_u32(self.gui_parent_api_atomic().load(Ordering::Acquire))
251    }
252
253    /// Store the native API of the GUI parent handle.
254    pub fn set_gui_parent_api(&self, api: GuiParentApi) {
255        self.gui_parent_api_atomic()
256            .store(api.as_u32(), Ordering::Release);
257    }
258
259    fn gui_mode_atomic(&self) -> &AtomicU32 {
260        // SAFETY: GUI_MODE_OFFSET is inside the control area, which is within the
261        // header's 256-byte allocation. The offset is aligned to 4 bytes.
262        unsafe {
263            let base = self as *const Self as *const u8;
264            &*(base.add(GUI_MODE_OFFSET) as *const AtomicU32)
265        }
266    }
267
268    /// Load the requested GUI mode.
269    pub fn gui_mode(&self) -> GuiMode {
270        GuiMode::from_u32(self.gui_mode_atomic().load(Ordering::Acquire))
271    }
272
273    /// Store the requested GUI mode.
274    pub fn set_gui_mode(&self, mode: GuiMode) {
275        self.gui_mode_atomic()
276            .store(mode.as_u32(), Ordering::Release);
277    }
278}
279
280impl Default for ShmHeader {
281    fn default() -> Self {
282        Self {
283            magic: MAGIC,
284            version: VERSION,
285            flags: 0,
286            ready: AtomicU32::new(0),
287            heartbeat: AtomicU32::new(0),
288            error_code: 0,
289            shutdown_request: AtomicU32::new(0),
290            tasks_issued: AtomicU32::new(0),
291            tasks_completed: AtomicU32::new(0),
292            block_size: AtomicU32::new(0),
293            num_input_channels: AtomicU32::new(0),
294            num_output_channels: AtomicU32::new(0),
295            midi_in_port_count: AtomicU32::new(0),
296            midi_out_port_count: AtomicU32::new(0),
297            request_type: AtomicU32::new(0),
298            request_status: AtomicU32::new(0),
299            scratch_size: AtomicU32::new(0),
300            parent_window: AtomicU64::new(0),
301            state_dirty: AtomicU32::new(0),
302            latency_samples: AtomicU32::new(0),
303            _pad: [0; 256 - 88],
304        }
305    }
306}
307
308// --- Layout helpers ---
309
310/// Zero-initialize the entire shared-memory region and write the header.
311///
312/// # Safety
313/// `ptr` must be a valid pointer to a memory region of `size` bytes.
314pub unsafe fn init_shm_layout(ptr: *mut u8, size: usize) {
315    unsafe {
316        std::ptr::write_bytes(ptr, 0, size);
317        let header = ptr as *mut ShmHeader;
318        std::ptr::write(header, ShmHeader::default());
319    }
320}
321
322/// Returns a reference to the header at the start of the mapping.
323///
324/// # Safety
325/// `ptr` must point to a valid allocation containing at least `ShmHeader`'s size.
326pub unsafe fn header_ref(ptr: *mut u8) -> &'static ShmHeader {
327    unsafe { &*(ptr as *mut ShmHeader) }
328}
329
330/// Returns a mutable reference to the header.
331///
332/// # Safety
333/// `ptr` must point to a valid allocation containing at least `ShmHeader`'s size.
334pub unsafe fn header_mut(ptr: *mut u8) -> &'static mut ShmHeader {
335    unsafe { &mut *(ptr as *mut ShmHeader) }
336}
337
338/// Returns a pointer to the audio buffer region.
339///
340/// # Safety
341/// `ptr` must point to an allocation large enough to contain the audio buffer.
342pub unsafe fn audio_ptr(ptr: *mut u8) -> *mut f32 {
343    unsafe { ptr.add(AUDIO_OFFSET) as *mut f32 }
344}
345
346/// Returns a pointer to a specific channel/bus plane.
347///
348/// `channel` is 0-based up to `MAX_CHANNELS - 1`.
349/// `bus` is 0 (main) or 1 (sidechain).
350///
351/// # Safety
352/// `ptr` must point to a valid allocation large enough to contain the audio data.
353pub unsafe fn audio_channel_ptr(ptr: *mut u8, channel: usize, bus: usize) -> *mut f32 {
354    let plane_size = MAX_BLOCK_SIZE * std::mem::size_of::<f32>();
355    let offset = AUDIO_OFFSET + (channel * NUM_BUSES + bus) * plane_size;
356    unsafe { ptr.add(offset) as *mut f32 }
357}
358
359/// Returns a pointer to the parameter ring buffer slot array.
360///
361/// # Safety
362/// `ptr` must point to a valid allocation large enough to contain the parameter ring.
363pub unsafe fn param_ring_ptr(ptr: *mut u8) -> *mut ParameterEvent {
364    unsafe { ptr.add(PARAM_RING_OFFSET) as *mut ParameterEvent }
365}
366
367/// Returns pointers to the parameter ring write/read atomics.
368///
369/// # Safety
370/// `ptr` must point to a valid allocation containing the parameter ring atomics.
371pub unsafe fn param_indices(ptr: *mut u8) -> (*mut AtomicU32, *mut AtomicU32) {
372    unsafe {
373        (
374            ptr.add(PARAM_WRITE_IDX_OFFSET) as *mut AtomicU32,
375            ptr.add(PARAM_READ_IDX_OFFSET) as *mut AtomicU32,
376        )
377    }
378}
379
380/// Returns a pointer to the echo ring buffer slot array.
381///
382/// # Safety
383/// `ptr` must point to a valid allocation large enough to contain the echo ring.
384pub unsafe fn echo_ring_ptr(ptr: *mut u8) -> *mut ParameterEvent {
385    unsafe { ptr.add(ECHO_RING_OFFSET) as *mut ParameterEvent }
386}
387
388/// Returns pointers to the echo ring write/read atomics.
389///
390/// # Safety
391/// `ptr` must point to a valid allocation containing the echo ring atomics.
392pub unsafe fn echo_indices(ptr: *mut u8) -> (*mut AtomicU32, *mut AtomicU32) {
393    unsafe {
394        (
395            ptr.add(ECHO_WRITE_IDX_OFFSET) as *mut AtomicU32,
396            ptr.add(ECHO_READ_IDX_OFFSET) as *mut AtomicU32,
397        )
398    }
399}
400
401const fn midi_port_ring_offset(base_offset: usize, port: usize) -> usize {
402    base_offset + port * MIDI_PORT_RING_SIZE
403}
404
405/// Returns pointers to the embedded write/read atomics for a MIDI input port ring.
406///
407/// # Safety
408/// `ptr` must point to a valid allocation and `port` must be < MAX_MIDI_PORTS.
409pub unsafe fn midi_in_indices(ptr: *mut u8, port: usize) -> (*mut AtomicU32, *mut AtomicU32) {
410    unsafe {
411        let base = ptr.add(midi_port_ring_offset(MIDI_IN_RINGS_OFFSET, port));
412        (base as *mut AtomicU32, base.add(4) as *mut AtomicU32)
413    }
414}
415
416/// Returns a pointer to the MIDI input port ring buffer slot array.
417///
418/// # Safety
419/// `ptr` must point to a valid allocation and `port` must be < MAX_MIDI_PORTS.
420pub unsafe fn midi_in_ring_ptr(ptr: *mut u8, port: usize) -> *mut MidiEvent {
421    unsafe { ptr.add(midi_port_ring_offset(MIDI_IN_RINGS_OFFSET, port) + 8) as *mut MidiEvent }
422}
423
424/// Returns pointers to the embedded write/read atomics for a MIDI output port ring.
425///
426/// # Safety
427/// `ptr` must point to a valid allocation and `port` must be < MAX_MIDI_PORTS.
428pub unsafe fn midi_out_indices(ptr: *mut u8, port: usize) -> (*mut AtomicU32, *mut AtomicU32) {
429    unsafe {
430        let base = ptr.add(midi_port_ring_offset(MIDI_OUT_RINGS_OFFSET, port));
431        (base as *mut AtomicU32, base.add(4) as *mut AtomicU32)
432    }
433}
434
435/// Returns a pointer to the MIDI output port ring buffer slot array.
436///
437/// # Safety
438/// `ptr` must point to a valid allocation and `port` must be < MAX_MIDI_PORTS.
439pub unsafe fn midi_out_ring_ptr(ptr: *mut u8, port: usize) -> *mut MidiEvent {
440    unsafe { ptr.add(midi_port_ring_offset(MIDI_OUT_RINGS_OFFSET, port) + 8) as *mut MidiEvent }
441}
442
443/// Returns a reference to the transport state.
444///
445/// # Safety
446/// `ptr` must point to a valid allocation containing at least `TransportState`'s size.
447pub unsafe fn transport_ref(ptr: *mut u8) -> &'static TransportState {
448    unsafe { &*(ptr.add(TRANSPORT_OFFSET) as *mut TransportState) }
449}
450
451/// Returns a mutable reference to the transport state.
452///
453/// # Safety
454/// `ptr` must point to a valid allocation containing at least `TransportState`'s size.
455pub unsafe fn transport_mut(ptr: *mut u8) -> &'static mut TransportState {
456    unsafe { &mut *(ptr.add(TRANSPORT_OFFSET) as *mut TransportState) }
457}
458
459/// Returns a pointer to the scratch buffer region.
460///
461/// # Safety
462/// `ptr` must point to an allocation large enough to contain the scratch buffer.
463pub unsafe fn scratch_ptr(ptr: *mut u8) -> *mut u8 {
464    unsafe { ptr.add(SCRATCH_OFFSET) }
465}
466
467/// Write a plugin name to the start of the scratch buffer.
468/// The name is encoded as a little-endian u32 length followed by UTF-8 bytes.
469///
470/// # Safety
471/// `ptr` must point to a valid SHM allocation.
472pub unsafe fn write_plugin_name_to_scratch(ptr: *mut u8, name: &str) {
473    unsafe {
474        let scratch = scratch_ptr(ptr);
475        let bytes = name.as_bytes();
476        let len = bytes.len().min(SCRATCH_SIZE - 4);
477        std::ptr::write_unaligned(scratch as *mut u32, len as u32);
478        std::ptr::copy_nonoverlapping(bytes.as_ptr(), scratch.add(4), len);
479    }
480}
481
482/// Read a plugin name from the start of the scratch buffer.
483///
484/// # Safety
485/// `ptr` must point to a valid SHM allocation.
486pub unsafe fn read_plugin_name_from_scratch(ptr: *mut u8) -> Option<String> {
487    unsafe {
488        let scratch = scratch_ptr(ptr);
489        let len = std::ptr::read_unaligned(scratch as *mut u32) as usize;
490        if len == 0 || len > SCRATCH_SIZE - 4 {
491            return None;
492        }
493        let bytes = std::slice::from_raw_parts(scratch.add(4), len);
494        String::from_utf8(bytes.to_vec()).ok()
495    }
496}
497
498/// Magic value written before port counts in scratch.
499pub const PORT_COUNTS_MAGIC: u32 = 0x504F_5254; // "PORT"
500
501/// Offset within scratch where port counts are stored (after plugin name).
502const PORT_COUNTS_OFFSET: usize = 1024;
503
504/// Write audio/MIDI port counts to scratch.
505///
506/// # Safety
507/// `ptr` must point to a valid SHM allocation.
508pub unsafe fn write_port_counts_to_scratch(
509    ptr: *mut u8,
510    audio_in: u32,
511    audio_out: u32,
512    midi_in: u32,
513    midi_out: u32,
514) {
515    unsafe {
516        let dest = scratch_ptr(ptr).add(PORT_COUNTS_OFFSET);
517        std::ptr::write_unaligned(dest as *mut u32, PORT_COUNTS_MAGIC);
518        std::ptr::write_unaligned(dest.add(4) as *mut u32, audio_in);
519        std::ptr::write_unaligned(dest.add(8) as *mut u32, audio_out);
520        std::ptr::write_unaligned(dest.add(12) as *mut u32, midi_in);
521        std::ptr::write_unaligned(dest.add(16) as *mut u32, midi_out);
522    }
523}
524
525/// Read audio/MIDI port counts from scratch.
526///
527/// # Safety
528/// `ptr` must point to a valid SHM allocation.
529pub unsafe fn read_port_counts_from_scratch(ptr: *mut u8) -> Option<(u32, u32, u32, u32)> {
530    unsafe {
531        let src = scratch_ptr(ptr).add(PORT_COUNTS_OFFSET);
532        let magic = std::ptr::read_unaligned(src as *mut u32);
533        if magic != PORT_COUNTS_MAGIC {
534            return None;
535        }
536        let audio_in = std::ptr::read_unaligned(src.add(4) as *mut u32);
537        let audio_out = std::ptr::read_unaligned(src.add(8) as *mut u32);
538        let midi_in = std::ptr::read_unaligned(src.add(12) as *mut u32);
539        let midi_out = std::ptr::read_unaligned(src.add(16) as *mut u32);
540        Some((audio_in, audio_out, midi_in, midi_out))
541    }
542}
543
544/// Magic value written before file-reference string list in scratch.
545pub const FILE_REFS_MAGIC: u32 = 0x4649_4C45; // "FILE"
546
547/// Offset within scratch where file-reference string list is stored.
548const FILE_REFS_OFFSET: usize = 2048;
549
550/// Maximum total bytes available for the file-reference list.
551const FILE_REFS_MAX_SIZE: usize = SCRATCH_SIZE - FILE_REFS_OFFSET;
552
553/// A file reference returned by a plugin, paired with its plugin-side index.
554pub type FileReference = (u32, String);
555
556/// Write a list of file-reference (index, path) pairs to scratch.
557/// Format: magic (u32), count (u32), then for each entry:
558///   index (u32), length (u32) followed by UTF-8 bytes.
559///
560/// # Safety
561/// `ptr` must point to a valid SHM allocation.
562pub unsafe fn write_file_references_to_scratch(
563    ptr: *mut u8,
564    refs: &[FileReference],
565) -> Result<(), String> {
566    unsafe {
567        let mut dest = scratch_ptr(ptr).add(FILE_REFS_OFFSET);
568        let mut remaining = FILE_REFS_MAX_SIZE;
569        if remaining < 8 {
570            return Err("scratch too small for file references".to_string());
571        }
572        std::ptr::write_unaligned(dest as *mut u32, FILE_REFS_MAGIC);
573        dest = dest.add(4);
574        remaining -= 4;
575        let count = refs.len().min(u32::MAX as usize) as u32;
576        std::ptr::write_unaligned(dest as *mut u32, count);
577        dest = dest.add(4);
578        remaining -= 4;
579        for (index, path) in refs.iter().take(count as usize) {
580            if remaining < 8 {
581                return Err("scratch overflow writing file references".to_string());
582            }
583            std::ptr::write_unaligned(dest as *mut u32, *index);
584            dest = dest.add(4);
585            remaining -= 4;
586            let bytes = path.as_bytes();
587            let len = bytes
588                .len()
589                .min(u32::MAX as usize)
590                .min(remaining.saturating_sub(4));
591            if len < bytes.len() {
592                return Err("scratch overflow writing file references".to_string());
593            }
594            std::ptr::write_unaligned(dest as *mut u32, len as u32);
595            dest = dest.add(4);
596            remaining -= 4;
597            std::ptr::copy_nonoverlapping(bytes.as_ptr(), dest, len);
598            dest = dest.add(len);
599            remaining -= len;
600        }
601        Ok(())
602    }
603}
604
605/// Read a list of file-reference (index, path) pairs from scratch.
606///
607/// # Safety
608/// `ptr` must point to a valid SHM allocation.
609pub unsafe fn read_file_references_from_scratch(ptr: *mut u8) -> Option<Vec<FileReference>> {
610    unsafe {
611        let mut src = scratch_ptr(ptr).add(FILE_REFS_OFFSET);
612        let mut remaining = FILE_REFS_MAX_SIZE;
613        if remaining < 8 {
614            return None;
615        }
616        let magic = std::ptr::read_unaligned(src as *mut u32);
617        if magic != FILE_REFS_MAGIC {
618            return None;
619        }
620        src = src.add(4);
621        remaining -= 4;
622        let count = std::ptr::read_unaligned(src as *mut u32) as usize;
623        src = src.add(4);
624        remaining -= 4;
625        let mut refs = Vec::with_capacity(count);
626        for _ in 0..count {
627            if remaining < 8 {
628                return None;
629            }
630            let index = std::ptr::read_unaligned(src as *mut u32);
631            src = src.add(4);
632            remaining -= 4;
633            let len = std::ptr::read_unaligned(src as *mut u32) as usize;
634            src = src.add(4);
635            remaining -= 4;
636            if len > remaining {
637                return None;
638            }
639            let bytes = std::slice::from_raw_parts(src, len);
640            let path = String::from_utf8(bytes.to_vec()).ok()?;
641            refs.push((index, path));
642            src = src.add(len);
643            remaining -= len;
644        }
645        Some(refs)
646    }
647}
648
649/// Write a resource-directory / base-directory path to scratch.
650/// Format: magic (u32), length (u32), UTF-8 bytes.
651///
652/// # Safety
653/// `ptr` must point to a valid SHM allocation.
654pub unsafe fn write_resource_directory_to_scratch(ptr: *mut u8, path: &str) -> Result<(), String> {
655    unsafe {
656        let scratch = scratch_ptr(ptr);
657        let bytes = path.as_bytes();
658        let len = bytes.len().min(SCRATCH_SIZE - 8);
659        if len < bytes.len() {
660            return Err("resource directory path too long".to_string());
661        }
662        std::ptr::write_unaligned(scratch as *mut u32, FILE_REFS_MAGIC);
663        std::ptr::write_unaligned(scratch.add(4) as *mut u32, len as u32);
664        std::ptr::copy_nonoverlapping(bytes.as_ptr(), scratch.add(8), len);
665        Ok(())
666    }
667}
668
669/// Read a resource-directory / base-directory path from scratch.
670///
671/// # Safety
672/// `ptr` must point to a valid SHM allocation.
673pub unsafe fn read_resource_directory_from_scratch(ptr: *mut u8) -> Option<String> {
674    unsafe {
675        let scratch = scratch_ptr(ptr);
676        let magic = std::ptr::read_unaligned(scratch as *mut u32);
677        if magic != FILE_REFS_MAGIC {
678            return None;
679        }
680        let len = std::ptr::read_unaligned(scratch.add(4) as *mut u32) as usize;
681        if len == 0 || len > SCRATCH_SIZE - 8 {
682            return None;
683        }
684        let bytes = std::slice::from_raw_parts(scratch.add(8), len);
685        String::from_utf8(bytes.to_vec()).ok()
686    }
687}
688
689/// Request type: enumerate LV2 control ports (index, name, min, max, value).
690pub const REQUEST_LV2_CONTROL_PORTS: u32 = 8;
691
692/// Request type: enumerate CLAP parameters (id, name, module, min, max, default).
693pub const REQUEST_CLAP_PARAMETERS: u32 = 9;
694
695/// Request type: fetch LV2 midnam note names (MIDI note number -> name).
696pub const REQUEST_LV2_MIDNAM: u32 = 10;
697
698/// Request type: fetch CLAP note names (MIDI note number -> name).
699pub const REQUEST_CLAP_NOTE_NAMES: u32 = 11;
700
701/// Magic value for a single file-reference update in scratch.
702pub const FILE_REF_UPDATE_MAGIC: u32 = 0x5550_4441; // "UPDA"
703
704/// Write a file-reference update (index + new path) to scratch.
705/// Format: magic (u32), index (u32), length (u32), UTF-8 bytes.
706///
707/// # Safety
708/// `ptr` must point to a valid SHM allocation.
709pub unsafe fn write_file_reference_update_to_scratch(
710    ptr: *mut u8,
711    index: u32,
712    path: &str,
713) -> Result<(), String> {
714    unsafe {
715        let scratch = scratch_ptr(ptr);
716        let bytes = path.as_bytes();
717        let len = bytes.len().min(SCRATCH_SIZE - 12);
718        if len < bytes.len() {
719            return Err("file-reference update path too long".to_string());
720        }
721        std::ptr::write_unaligned(scratch as *mut u32, FILE_REF_UPDATE_MAGIC);
722        std::ptr::write_unaligned(scratch.add(4) as *mut u32, index);
723        std::ptr::write_unaligned(scratch.add(8) as *mut u32, len as u32);
724        std::ptr::copy_nonoverlapping(bytes.as_ptr(), scratch.add(12), len);
725        Ok(())
726    }
727}
728
729/// Read a file-reference update (index + new path) from scratch.
730///
731/// # Safety
732/// `ptr` must point to a valid SHM allocation.
733pub unsafe fn read_file_reference_update_from_scratch(ptr: *mut u8) -> Option<(u32, String)> {
734    unsafe {
735        let scratch = scratch_ptr(ptr);
736        let magic = std::ptr::read_unaligned(scratch as *mut u32);
737        if magic != FILE_REF_UPDATE_MAGIC {
738            return None;
739        }
740        let index = std::ptr::read_unaligned(scratch.add(4) as *mut u32);
741        let len = std::ptr::read_unaligned(scratch.add(8) as *mut u32) as usize;
742        if len == 0 || len > SCRATCH_SIZE - 12 {
743            return None;
744        }
745        let bytes = std::slice::from_raw_parts(scratch.add(12), len);
746        let path = String::from_utf8(bytes.to_vec()).ok()?;
747        Some((index, path))
748    }
749}
750
751// --- Static assertions for sizes ---
752
753const _: () = assert!(std::mem::size_of::<ShmHeader>() == 256);
754const _: () = assert!(std::mem::align_of::<ShmHeader>() == 256);
755const _: () = assert!(std::mem::size_of::<ParameterEvent>() == 16);
756const _: () = assert!(std::mem::align_of::<ParameterEvent>() == 16);
757const _: () = assert!(std::mem::size_of::<MidiEvent>() == 16);
758const _: () = assert!(std::mem::align_of::<MidiEvent>() == 16);
759const _: () = assert!(std::mem::size_of::<TransportState>() == 256);
760const _: () = assert!(std::mem::align_of::<TransportState>() == 256);
761const _: () = assert!(LAYOUT_SIZE <= SHM_SIZE);
762
763/// Wait (spin + yield) until `ready` becomes non-zero or timeout elapses.
764pub fn wait_for_ready(header: &ShmHeader, timeout: std::time::Duration) -> bool {
765    let start = std::time::Instant::now();
766    while header.ready.load(Ordering::Acquire) == 0 {
767        if start.elapsed() >= timeout {
768            return false;
769        }
770        std::thread::yield_now();
771    }
772    true
773}