Skip to main content

maolan_engine/plugins/
vst3_proc.rs

1use crate::audio::io::AudioIO;
2use crate::midi::io::{MIDIIO, MidiEvent};
3use crate::plugins::ipc;
4use crate::plugins::types::ParameterInfo;
5use crate::plugins::types::Vst3PluginState;
6use arc_swap::ArcSwapOption;
7use maolan_plugin_protocol::events::EventPair;
8use maolan_plugin_protocol::protocol::*;
9use maolan_plugin_protocol::ringbuf::RingBuffer;
10use maolan_plugin_protocol::shm::ShmMapping;
11use std::cell::UnsafeCell;
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::process::{Child, ChildStderr};
15use std::sync::Arc;
16use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
17use std::time::Duration;
18
19const SHM_LATENCY_SAMPLES_OFFSET: usize = 84;
20
21unsafe fn latency_samples_atomic(ptr: *mut u8) -> &'static AtomicU32 {
22    unsafe { &*(ptr.add(SHM_LATENCY_SAMPLES_OFFSET) as *const AtomicU32) }
23}
24
25pub struct Vst3Processor {
26    path: String,
27    plugin_id: String,
28    name: String,
29    audio_inputs: Vec<Arc<AudioIO>>,
30    audio_outputs: Vec<Arc<AudioIO>>,
31    main_audio_inputs: usize,
32    main_audio_outputs: usize,
33    midi_input_ports: Vec<Arc<MIDIIO>>,
34    midi_output_ports: Vec<Arc<MIDIIO>>,
35    param_infos: Vec<ParameterInfo>,
36    /// Current value of every known parameter, keyed by parameter id and
37    /// stored as `f64` bits. Pre-populated from `param_infos` at construction
38    /// and only ever touched through atomic loads/stores.
39    param_values: HashMap<u32, AtomicU64>,
40    bypassed: Arc<AtomicBool>,
41
42    /// Host child process handle. Interior-mutable so `process_with_audio_buffers`
43    /// (which takes `&self`) can poll it with `try_wait`.
44    ///
45    /// Invariant: at any moment there is at most one accessor — either the
46    /// audio thread running this plugin's own plan task node (exactly one per
47    /// cycle), or control code running after the last `Arc` reference to this
48    /// processor is gone (`Drop`).
49    child: UnsafeCell<Option<Child>>,
50    /// Host stderr pipe; control-side only (`take_stderr`). RCU-published so
51    /// no blocking primitive is involved.
52    stderr: ArcSwapOption<ChildStderr>,
53    mapping: Option<ShmMapping>,
54    events: Option<EventPair>,
55    shm_name: String,
56
57    crash_count: AtomicU32,
58    last_latency_samples: AtomicUsize,
59    latency_changed: AtomicBool,
60}
61
62// Safety: see the invariants on `child` and `stderr` above. Every other field
63// is either immutable after construction or synchronized on its own
64// (atomics / RCU).
65unsafe impl Sync for Vst3Processor {}
66
67pub type SharedVst3Processor = Arc<Vst3Processor>;
68
69impl Vst3Processor {
70    pub fn new(
71        sample_rate: f64,
72        buffer_size: usize,
73        plugin_path: &str,
74        plugin_id: &str,
75        input_count: usize,
76        output_count: usize,
77        host_binary: PathBuf,
78    ) -> Result<Self, String> {
79        let audio_inputs = (0..input_count.max(1))
80            .map(|_| Arc::new(AudioIO::new(buffer_size)))
81            .collect::<Vec<_>>();
82        let audio_outputs = (0..output_count.max(1))
83            .map(|_| Arc::new(AudioIO::new(buffer_size)))
84            .collect::<Vec<_>>();
85
86        let instance_id = ipc::unique_instance_id("vst3");
87        let num_inputs = input_count.max(1);
88        let num_outputs = output_count.max(1);
89        let (mut child, mapping, events, shm_name, stderr) = ipc::spawn_host(ipc::HostSpawnArgs {
90            host_binary: &host_binary,
91            format: "vst3",
92            plugin_spec: plugin_path,
93            instance_id: &instance_id,
94            extra_args: &[
95                &sample_rate.to_string(),
96                &buffer_size.to_string(),
97                &num_inputs.to_string(),
98                &num_outputs.to_string(),
99            ],
100        })?;
101
102        let header = unsafe { header_ref(mapping.as_ptr()) };
103        if !ipc::wait_for_ready(header, Duration::from_secs(10)) {
104            let _ = child.kill();
105            return Err("VST3 host did not signal ready".to_string());
106        }
107
108        let name = unsafe {
109            maolan_plugin_protocol::protocol::read_plugin_name_from_scratch(mapping.as_ptr())
110                .unwrap_or_else(|| {
111                    Path::new(plugin_path)
112                        .file_stem()
113                        .and_then(|s| s.to_str())
114                        .unwrap_or("VST3")
115                        .to_string()
116                })
117        };
118
119        let param_infos: Vec<ParameterInfo> = Vec::new();
120        let param_values = param_infos
121            .iter()
122            .map(|info| (info.id, AtomicU64::new(info.default_value.to_bits())))
123            .collect();
124
125        let header = unsafe { header_ref(mapping.as_ptr()) };
126        let midi_in_count = header.midi_in_port_count.load(Ordering::Acquire) as usize;
127        let midi_out_count = header.midi_out_port_count.load(Ordering::Acquire) as usize;
128        let midi_input_ports: Vec<_> = (0..midi_in_count)
129            .map(|_| Arc::new(MIDIIO::new()))
130            .collect();
131        let midi_output_ports: Vec<_> = (0..midi_out_count)
132            .map(|_| Arc::new(MIDIIO::new()))
133            .collect();
134
135        Ok(Self {
136            path: plugin_path.to_string(),
137            plugin_id: plugin_id.to_string(),
138            name,
139            audio_inputs,
140            audio_outputs,
141            main_audio_inputs: input_count.max(1),
142            main_audio_outputs: output_count.max(1),
143            midi_input_ports,
144            midi_output_ports,
145            param_infos,
146            param_values,
147            bypassed: Arc::new(AtomicBool::new(false)),
148            child: UnsafeCell::new(Some(child)),
149            stderr: ArcSwapOption::from_pointee(stderr),
150            mapping: Some(mapping),
151            events: Some(events),
152            shm_name,
153            crash_count: AtomicU32::new(0),
154            last_latency_samples: AtomicUsize::new(0),
155            latency_changed: AtomicBool::new(false),
156        })
157    }
158
159    /// Access the host child process handle.
160    ///
161    /// # Safety
162    /// The caller must be the sole accessor of `child` at this time: either
163    /// the audio thread running this plugin's own plan task node (exactly one
164    /// per cycle), or control code running after the last `Arc` reference to
165    /// this processor is gone.
166    unsafe fn with_child<R>(&self, f: impl FnOnce(&mut Option<Child>) -> R) -> R {
167        f(unsafe { &mut *self.child.get() })
168    }
169
170    pub fn setup_audio_ports(&self) {
171        for port in &self.audio_inputs {
172            port.setup();
173        }
174        for port in &self.audio_outputs {
175            port.setup();
176        }
177    }
178
179    pub fn setup_midi_ports(&self) {
180        for port in &self.midi_input_ports {
181            // Safety: plan single-writer invariant — this task is the sole
182            // writer of its own ports this cycle; sources it reads were
183            // produced by earlier plan nodes (LOCKLESS.md Phase 3).
184            unsafe { port.setup() };
185        }
186        for port in &self.midi_output_ports {
187            // Safety: as above — sole writer of this port this cycle.
188            unsafe { port.setup() };
189        }
190    }
191
192    pub fn audio_inputs(&self) -> &[Arc<AudioIO>] {
193        &self.audio_inputs
194    }
195
196    pub fn audio_outputs(&self) -> &[Arc<AudioIO>] {
197        &self.audio_outputs
198    }
199
200    pub fn main_audio_input_count(&self) -> usize {
201        self.main_audio_inputs
202    }
203
204    pub fn main_audio_output_count(&self) -> usize {
205        self.main_audio_outputs
206    }
207
208    pub fn midi_input_count(&self) -> usize {
209        self.midi_input_ports.len()
210    }
211
212    pub fn midi_output_count(&self) -> usize {
213        self.midi_output_ports.len()
214    }
215
216    pub fn midi_input_ports(&self) -> &[Arc<MIDIIO>] {
217        &self.midi_input_ports
218    }
219
220    pub fn midi_output_ports(&self) -> &[Arc<MIDIIO>] {
221        &self.midi_output_ports
222    }
223
224    pub fn set_bypassed(&self, bypassed: bool) {
225        self.bypassed.store(bypassed, Ordering::Relaxed);
226    }
227
228    pub fn is_bypassed(&self) -> bool {
229        self.bypassed.load(Ordering::Relaxed)
230    }
231
232    pub fn latency_samples(&self) -> usize {
233        let latency = self
234            .mapping
235            .as_ref()
236            .map(|mapping| unsafe {
237                latency_samples_atomic(mapping.as_ptr()).load(Ordering::Acquire) as usize
238            })
239            .unwrap_or(0);
240        let previous = self.last_latency_samples.swap(latency, Ordering::AcqRel);
241        if previous != latency {
242            self.latency_changed.store(true, Ordering::Release);
243        }
244        latency
245    }
246
247    pub fn take_latency_changed(&self) -> bool {
248        self.latency_changed.swap(false, Ordering::AcqRel)
249    }
250
251    pub fn parameter_infos(&self) -> Vec<ParameterInfo> {
252        self.param_infos.clone()
253    }
254
255    pub fn parameter_values(&self) -> HashMap<u32, f64> {
256        self.param_values
257            .iter()
258            .map(|(&id, value)| (id, f64::from_bits(value.load(Ordering::Relaxed))))
259            .collect()
260    }
261
262    pub fn set_parameter(&self, param_id: u32, value: f64) -> Result<(), String> {
263        self.set_parameter_at(param_id, value, 0)
264    }
265
266    pub fn set_parameter_at(&self, param_id: u32, value: f64, _frame: u32) -> Result<(), String> {
267        if let Some(slot) = self.param_values.get(&param_id) {
268            slot.store(value.to_bits(), Ordering::Relaxed);
269        } else {
270            tracing::warn!("VST3 set_parameter_at: unknown parameter id {param_id}");
271        }
272
273        if let Some(ref mapping) = self.mapping {
274            let ring = unsafe {
275                let buf = param_ring_ptr(mapping.as_ptr());
276                let (w, r) = param_indices(mapping.as_ptr());
277                RingBuffer::new(buf, w, r, RING_CAPACITY)
278            };
279            let ev = ParameterEvent {
280                param_index: param_id,
281                value: value as f32,
282                sample_offset: 0,
283                event_kind: maolan_plugin_protocol::PARAM_EVENT_VALUE,
284            };
285            if !ring.push(ev) {}
286        }
287        Ok(())
288    }
289
290    pub fn begin_parameter_edit(&self, _param_id: u32) -> Result<(), String> {
291        Ok(())
292    }
293
294    pub fn end_parameter_edit(&self, _param_id: u32) -> Result<(), String> {
295        Ok(())
296    }
297
298    pub fn is_parameter_edit_active(&self, _param_id: u32) -> bool {
299        false
300    }
301
302    pub fn snapshot_state(&self) -> Result<Vst3PluginState, String> {
303        let (mapping, events) = match (&self.mapping, &self.events) {
304            (Some(m), Some(e)) => (m, e),
305            _ => return Err("VST3 processor not initialized".to_string()),
306        };
307        let ptr = mapping.as_ptr();
308        let header = unsafe { header_mut(ptr) };
309
310        header.request_type.store(1, Ordering::Release);
311        header.request_status.store(0, Ordering::Release);
312        if let Err(e) = events.signal_host() {
313            header.request_type.store(0, Ordering::Release);
314            return Err(format!("Failed to signal host for state save: {}", e));
315        }
316
317        if let Err(e) = events.wait_host(Duration::from_secs(5)) {
318            header.request_type.store(0, Ordering::Release);
319            return Err(format!("Host did not respond to state save: {}", e));
320        }
321
322        let status = header.request_status.load(Ordering::Acquire);
323        let size = header.scratch_size.load(Ordering::Acquire) as usize;
324        if status != 1 {
325            header.request_type.store(0, Ordering::Release);
326            return Err("State save failed in host".to_string());
327        }
328
329        let scratch = unsafe { scratch_ptr(ptr) };
330        let state = deserialize_vst3_state(scratch, size)?;
331        header.request_type.store(0, Ordering::Release);
332        Ok(state)
333    }
334
335    pub fn restore_state(&self, state: &Vst3PluginState) -> Result<(), String> {
336        let (mapping, events) = match (&self.mapping, &self.events) {
337            (Some(m), Some(e)) => (m, e),
338            _ => return Err("VST3 processor not initialized".to_string()),
339        };
340        let ptr = mapping.as_ptr();
341        let header = unsafe { header_mut(ptr) };
342
343        let scratch = unsafe { scratch_ptr(ptr) };
344        let size = serialize_vst3_state(scratch, state)?;
345        header.scratch_size.store(size as u32, Ordering::Release);
346
347        header.request_type.store(2, Ordering::Release);
348        header.request_status.store(0, Ordering::Release);
349        if let Err(e) = events.signal_host() {
350            header.request_type.store(0, Ordering::Release);
351            return Err(format!("Failed to signal host for state restore: {}", e));
352        }
353
354        if let Err(e) = events.wait_host(Duration::from_secs(5)) {
355            header.request_type.store(0, Ordering::Release);
356            return Err(format!("Host did not respond to state restore: {}", e));
357        }
358
359        let status = header.request_status.load(Ordering::Acquire);
360        header.request_type.store(0, Ordering::Release);
361        if status != 1 {
362            return Err("State restore failed in host".to_string());
363        }
364        Ok(())
365    }
366
367    pub fn process_with_audio_buffers(
368        &self,
369        frames: usize,
370        audio_inputs: &[&[f32]],
371        audio_outputs: &mut [&mut [f32]],
372    ) -> Vec<MidiEvent> {
373        if self.bypassed.load(Ordering::Relaxed) {
374            ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
375            return Vec::new();
376        }
377
378        // Safety: the sole RT accessor of `child` is this processor's own
379        // plan task node, which runs exactly once per cycle.
380        let crashed = unsafe {
381            self.with_child(|child| {
382                if let Some(c) = child.as_mut()
383                    && let Ok(Some(status)) = c.try_wait()
384                    && !status.success()
385                {
386                    self.crash_count.fetch_add(1, Ordering::Relaxed);
387                    return true;
388                }
389                false
390            })
391        };
392        if crashed {
393            ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
394            return Vec::new();
395        }
396
397        let (mapping, events) = match (&self.mapping, &self.events) {
398            (Some(m), Some(e)) => (m, e),
399            _ => {
400                ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
401                return Vec::new();
402            }
403        };
404
405        let ptr = mapping.as_ptr();
406        let num_in = audio_inputs.len();
407        let num_out = audio_outputs.len();
408        let midi_in_count = self.midi_input_ports.len();
409        let midi_out_count = self.midi_output_ports.len();
410        unsafe {
411            ipc::configure_shm_header(ptr, frames, num_in, num_out, midi_in_count, midi_out_count);
412
413            let t = transport_mut(ptr);
414            t.playhead_sample = 0;
415            t.tempo = 120.0;
416            t.numerator = 4;
417            t.denominator = 4;
418            t.flags = 1;
419
420            ipc::copy_input_slices_to_shm(audio_inputs, ptr, frames);
421
422            for (port_idx, port) in self.midi_input_ports.iter().enumerate() {
423                let buf = midi_in_ring_ptr(ptr, port_idx);
424                let (w, r) = midi_in_indices(ptr, port_idx);
425                let ring = RingBuffer::new(buf, w, r, RING_CAPACITY);
426                // Safety: plan single-writer invariant — this task is the sole
427                // writer of its own ports this cycle; this read is of the
428                // port's own buffer, which no other node touches now
429                // (LOCKLESS.md Phase 3).
430                let port_buffer = port.buffer();
431                for ev in port_buffer {
432                    let data = {
433                        let mut d = [0u8; 3];
434                        for (i, b) in ev.data.iter().enumerate().take(3) {
435                            d[i] = *b;
436                        }
437                        d
438                    };
439                    let _ = ring.push(maolan_plugin_protocol::MidiEvent {
440                        sample_offset: ev.frame,
441                        data,
442                        channel: ev.data.first().copied().unwrap_or(0) & 0x0F,
443                        flags: 0,
444                        _pad: 0,
445                    });
446                }
447                port.mark_finished();
448            }
449        }
450
451        if events.signal_host().is_err() {
452            ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
453            return Vec::new();
454        }
455
456        let timeout = Duration::from_millis(100);
457        match events.wait_host(timeout) {
458            Ok(()) => {}
459            Err(_) => {
460                ipc::bypass_copy_input_slices_to_outputs(audio_inputs, audio_outputs);
461                return Vec::new();
462            }
463        }
464
465        unsafe {
466            ipc::copy_outputs_from_shm_to_slices(audio_outputs, ptr, frames);
467
468            let mut output_events = Vec::new();
469            for (port_idx, port) in self.midi_output_ports.iter().enumerate() {
470                let buf = midi_out_ring_ptr(ptr, port_idx);
471                let (w, r) = midi_out_indices(ptr, port_idx);
472                let ring = RingBuffer::new(buf, w, r, RING_CAPACITY);
473                // Safety: plan single-writer invariant — this task is the sole
474                // writer of its own ports this cycle (LOCKLESS.md Phase 3).
475                let mut port_buffer = port.buffer_mut();
476                port_buffer.clear();
477                while let Some(ev) = ring.pop() {
478                    let event = MidiEvent {
479                        frame: ev.sample_offset,
480                        data: ev.data.to_vec(),
481                    };
482                    port_buffer.push(event.clone());
483                    output_events.push(event);
484                }
485                port.mark_finished();
486            }
487            output_events
488        }
489    }
490
491    pub fn path(&self) -> &str {
492        &self.path
493    }
494
495    pub fn plugin_id(&self) -> &str {
496        &self.plugin_id
497    }
498
499    pub fn name(&self) -> &str {
500        &self.name
501    }
502
503    pub fn take_stderr(&self) -> Option<ChildStderr> {
504        // Control-side only: the EC is the sole accessor, so after `swap`
505        // the `Arc` is unique and `try_unwrap` cannot fail in practice.
506        self.stderr.swap(None).and_then(|s| Arc::try_unwrap(s).ok())
507    }
508
509    pub fn begin_parameter_edit_at(&self, _param_id: u32, _frame: u32) -> Result<(), String> {
510        Ok(())
511    }
512
513    pub fn end_parameter_edit_at(&self, _param_id: u32, _frame: u32) -> Result<(), String> {
514        Ok(())
515    }
516
517    pub fn run_host_callbacks_main_thread(&self) {}
518
519    pub fn reconfigure_ports_if_needed(&self) -> Result<bool, String> {
520        Ok(false)
521    }
522
523    pub fn ui_begin_session(&self) {}
524    pub fn ui_end_session(&self) {}
525    pub fn ui_should_close(&self) -> bool {
526        false
527    }
528    pub fn ui_take_due_timers(&self) -> Vec<u32> {
529        Vec::new()
530    }
531    pub fn ui_take_param_updates(&self) -> Vec<(u32, f64)> {
532        Vec::new()
533    }
534    pub fn ui_take_state_update(&self) -> Option<Vst3PluginState> {
535        None
536    }
537
538    pub fn gui_info(&self) -> Result<crate::plugins::types::Vst3GuiInfo, String> {
539        Err("GUI not yet supported for VST3 plugins".to_string())
540    }
541
542    pub fn gui_create(&self, _platform_type: &str) -> Result<(), String> {
543        Err("GUI not yet supported for VST3 plugins".to_string())
544    }
545
546    pub fn gui_get_size(&self) -> Result<(i32, i32), String> {
547        Err("GUI not yet supported for VST3 plugins".to_string())
548    }
549
550    pub fn gui_set_parent(&self, _window: usize, _platform_type: &str) -> Result<(), String> {
551        Err("GUI not yet supported for VST3 plugins".to_string())
552    }
553
554    pub fn gui_set_floating_mode(&self, floating: bool) -> Result<(), String> {
555        if let Some(ref mapping) = self.mapping {
556            let header = unsafe { header_mut(mapping.as_ptr()) };
557            header.set_gui_mode(if floating {
558                GuiMode::Floating
559            } else {
560                GuiMode::Embedded
561            });
562            return Ok(());
563        }
564        Err("No active host to set GUI mode".to_string())
565    }
566
567    pub fn gui_on_size(&self, _width: i32, _height: i32) -> Result<(), String> {
568        Err("GUI not yet supported for VST3 plugins".to_string())
569    }
570
571    pub fn gui_show(&self) -> Result<(), String> {
572        if let Some(ref mapping) = self.mapping
573            && let Some(ref events) = self.events
574        {
575            let header = unsafe { header_mut(mapping.as_ptr()) };
576            header.request_type.store(3, Ordering::Release);
577            let _ = events.signal_host();
578            return Ok(());
579        }
580        Err("No active host to show GUI".to_string())
581    }
582
583    pub fn gui_hide(&self) {
584        if let Some(ref mapping) = self.mapping
585            && let Some(ref events) = self.events
586        {
587            let header = unsafe { header_mut(mapping.as_ptr()) };
588            header.request_type.store(4, Ordering::Release);
589            let _ = events.signal_host();
590        }
591    }
592
593    pub fn gui_destroy(&self) {}
594
595    pub fn gui_on_main_thread(&self) {}
596
597    pub fn gui_on_timer(&self, _timer_id: u32) {}
598
599    pub fn gui_check_resize(&self) -> Option<(i32, i32)> {
600        None
601    }
602
603    pub fn drain_echoed_parameters(&self) -> Vec<ParameterEvent> {
604        let mut result = Vec::new();
605        if let Some(ref mapping) = self.mapping {
606            let ring = unsafe {
607                let buf = echo_ring_ptr(mapping.as_ptr());
608                let (w, r) = echo_indices(mapping.as_ptr());
609                RingBuffer::new(buf, w, r, RING_CAPACITY)
610            };
611            while let Some(ev) = ring.pop() {
612                result.push(ev);
613            }
614        }
615        result
616    }
617}
618
619impl Drop for Vst3Processor {
620    fn drop(&mut self) {
621        let mapping = self.mapping.take();
622        let events = self.events.take();
623        let child = self.child.get_mut().take();
624        let shm_name = std::mem::take(&mut self.shm_name);
625        ipc::drop_host(mapping, events, child, shm_name);
626    }
627}
628
629fn serialize_vst3_state(scratch: *mut u8, state: &Vst3PluginState) -> Result<usize, String> {
630    let max_len = maolan_plugin_protocol::protocol::SCRATCH_SIZE;
631    let mut offset = 0usize;
632
633    let plugin_id_bytes = state.plugin_id.as_bytes();
634    if offset + 4 > max_len {
635        return Err("scratch overflow".to_string());
636    }
637    unsafe {
638        std::ptr::write_unaligned(
639            scratch.add(offset) as *mut u32,
640            plugin_id_bytes.len() as u32,
641        );
642    }
643    offset += 4;
644    if offset + plugin_id_bytes.len() > max_len {
645        return Err("scratch overflow".to_string());
646    }
647    unsafe {
648        std::ptr::copy_nonoverlapping(
649            plugin_id_bytes.as_ptr(),
650            scratch.add(offset),
651            plugin_id_bytes.len(),
652        );
653    }
654    offset += plugin_id_bytes.len();
655
656    if offset + 4 > max_len {
657        return Err("scratch overflow".to_string());
658    }
659    unsafe {
660        std::ptr::write_unaligned(
661            scratch.add(offset) as *mut u32,
662            state.component_state.len() as u32,
663        );
664    }
665    offset += 4;
666    if offset + state.component_state.len() > max_len {
667        return Err("scratch overflow".to_string());
668    }
669    unsafe {
670        std::ptr::copy_nonoverlapping(
671            state.component_state.as_ptr(),
672            scratch.add(offset),
673            state.component_state.len(),
674        );
675    }
676    offset += state.component_state.len();
677
678    if offset + 4 > max_len {
679        return Err("scratch overflow".to_string());
680    }
681    unsafe {
682        std::ptr::write_unaligned(
683            scratch.add(offset) as *mut u32,
684            state.controller_state.len() as u32,
685        );
686    }
687    offset += 4;
688    if offset + state.controller_state.len() > max_len {
689        return Err("scratch overflow".to_string());
690    }
691    unsafe {
692        std::ptr::copy_nonoverlapping(
693            state.controller_state.as_ptr(),
694            scratch.add(offset),
695            state.controller_state.len(),
696        );
697    }
698    offset += state.controller_state.len();
699
700    Ok(offset)
701}
702
703fn deserialize_vst3_state(scratch: *const u8, size: usize) -> Result<Vst3PluginState, String> {
704    if size < 12 {
705        return Err("scratch too small for VST3 state".to_string());
706    }
707    let mut offset = 0usize;
708
709    let plugin_id_len =
710        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
711    offset += 4;
712    if offset + plugin_id_len > size {
713        return Err("scratch underflow".to_string());
714    }
715    let mut plugin_id_bytes = vec![0u8; plugin_id_len];
716    unsafe {
717        std::ptr::copy_nonoverlapping(
718            scratch.add(offset),
719            plugin_id_bytes.as_mut_ptr(),
720            plugin_id_len,
721        );
722    }
723    offset += plugin_id_len;
724    let plugin_id = String::from_utf8(plugin_id_bytes).map_err(|e| e.to_string())?;
725
726    let component_state_len =
727        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
728    offset += 4;
729    if offset + component_state_len > size {
730        return Err("scratch underflow".to_string());
731    }
732    let mut component_state = vec![0u8; component_state_len];
733    unsafe {
734        std::ptr::copy_nonoverlapping(
735            scratch.add(offset),
736            component_state.as_mut_ptr(),
737            component_state_len,
738        );
739    }
740    offset += component_state_len;
741
742    let controller_state_len =
743        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
744    offset += 4;
745    if offset + controller_state_len > size {
746        return Err("scratch underflow".to_string());
747    }
748    let mut controller_state = vec![0u8; controller_state_len];
749    unsafe {
750        std::ptr::copy_nonoverlapping(
751            scratch.add(offset),
752            controller_state.as_mut_ptr(),
753            controller_state_len,
754        );
755    }
756
757    Ok(Vst3PluginState {
758        plugin_id,
759        component_state,
760        controller_state,
761    })
762}
763
764#[cfg(test)]
765mod tests {
766    use super::*;
767
768    fn find_host_binary() -> PathBuf {
769        ipc::find_plugin_host_binary().expect("maolan-plugin-host binary should be built for tests")
770    }
771
772    #[cfg_attr(
773        all(miri, target_os = "freebsd"),
774        ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
775    )]
776    #[test]
777    fn find_host_binary_locates_binary() {
778        let host_bin = find_host_binary();
779        assert!(
780            host_bin.exists(),
781            "plugin-host binary should exist at {}",
782            host_bin.display()
783        );
784    }
785
786    #[test]
787    fn vst3_state_serialization_roundtrip() {
788        let state = Vst3PluginState {
789            plugin_id: "test.plugin.vst3".to_string(),
790            component_state: vec![1, 2, 3, 4, 5],
791            controller_state: vec![10, 20, 30],
792        };
793        let mut scratch = vec![0u8; SCRATCH_SIZE];
794        let size =
795            serialize_vst3_state(scratch.as_mut_ptr(), &state).expect("serialize should succeed");
796        assert!(size > 0);
797        assert!(size < SCRATCH_SIZE);
798
799        let decoded =
800            deserialize_vst3_state(scratch.as_ptr(), size).expect("deserialize should succeed");
801        assert_eq!(decoded.plugin_id, state.plugin_id);
802        assert_eq!(decoded.component_state, state.component_state);
803        assert_eq!(decoded.controller_state, state.controller_state);
804    }
805
806    #[cfg_attr(
807        all(miri, target_os = "freebsd"),
808        ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
809    )]
810    #[test]
811    fn vst3_processor_crash_bypass() {
812        let host_bin = find_host_binary();
813
814        let processor = Vst3Processor::new(48000.0, 256, "__crash__", "__crash__", 1, 1, host_bin)
815            .expect("should create VST3 processor for crash test");
816
817        processor.setup_audio_ports();
818
819        let input_buffers = [vec![1.0; 256]];
820        let mut output_buffers = [vec![0.0; 256]];
821        let inputs = input_buffers.iter().map(Vec::as_slice).collect::<Vec<_>>();
822        let mut outputs = output_buffers
823            .iter_mut()
824            .map(Vec::as_mut_slice)
825            .collect::<Vec<_>>();
826        processor.process_with_audio_buffers(256, &inputs, &mut outputs);
827
828        let out_buf = &output_buffers[0];
829        assert!(
830            out_buf.iter().all(|&s| s == 1.0),
831            "after crash, output should be bypass copy of input"
832        );
833    }
834}