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            if floating {
563                header.set_parent_window(0);
564                header.set_gui_parent_api(maolan_plugin_protocol::protocol::GuiParentApi::None);
565            }
566            return Ok(());
567        }
568        Err("No active host to set GUI mode".to_string())
569    }
570
571    pub fn gui_on_size(&self, _width: i32, _height: i32) -> Result<(), String> {
572        Err("GUI not yet supported for VST3 plugins".to_string())
573    }
574
575    pub fn gui_show(&self) -> Result<(), String> {
576        if let Some(ref mapping) = self.mapping
577            && let Some(ref events) = self.events
578        {
579            let header = unsafe { header_mut(mapping.as_ptr()) };
580            header.request_type.store(3, Ordering::Release);
581            let _ = events.signal_host();
582            return Ok(());
583        }
584        Err("No active host to show GUI".to_string())
585    }
586
587    pub fn gui_hide(&self) {
588        if let Some(ref mapping) = self.mapping
589            && let Some(ref events) = self.events
590        {
591            let header = unsafe { header_mut(mapping.as_ptr()) };
592            header.request_type.store(4, Ordering::Release);
593            let _ = events.signal_host();
594        }
595    }
596
597    pub fn gui_destroy(&self) {}
598
599    pub fn gui_on_main_thread(&self) {}
600
601    pub fn gui_on_timer(&self, _timer_id: u32) {}
602
603    pub fn gui_check_resize(&self) -> Option<(i32, i32)> {
604        None
605    }
606
607    pub fn drain_echoed_parameters(&self) -> Vec<ParameterEvent> {
608        let mut result = Vec::new();
609        if let Some(ref mapping) = self.mapping {
610            let ring = unsafe {
611                let buf = echo_ring_ptr(mapping.as_ptr());
612                let (w, r) = echo_indices(mapping.as_ptr());
613                RingBuffer::new(buf, w, r, RING_CAPACITY)
614            };
615            while let Some(ev) = ring.pop() {
616                result.push(ev);
617            }
618        }
619        result
620    }
621}
622
623impl Drop for Vst3Processor {
624    fn drop(&mut self) {
625        let mapping = self.mapping.take();
626        let events = self.events.take();
627        let child = self.child.get_mut().take();
628        let shm_name = std::mem::take(&mut self.shm_name);
629        ipc::drop_host(mapping, events, child, shm_name);
630    }
631}
632
633fn serialize_vst3_state(scratch: *mut u8, state: &Vst3PluginState) -> Result<usize, String> {
634    let max_len = maolan_plugin_protocol::protocol::SCRATCH_SIZE;
635    let mut offset = 0usize;
636
637    let plugin_id_bytes = state.plugin_id.as_bytes();
638    if offset + 4 > max_len {
639        return Err("scratch overflow".to_string());
640    }
641    unsafe {
642        std::ptr::write_unaligned(
643            scratch.add(offset) as *mut u32,
644            plugin_id_bytes.len() as u32,
645        );
646    }
647    offset += 4;
648    if offset + plugin_id_bytes.len() > max_len {
649        return Err("scratch overflow".to_string());
650    }
651    unsafe {
652        std::ptr::copy_nonoverlapping(
653            plugin_id_bytes.as_ptr(),
654            scratch.add(offset),
655            plugin_id_bytes.len(),
656        );
657    }
658    offset += plugin_id_bytes.len();
659
660    if offset + 4 > max_len {
661        return Err("scratch overflow".to_string());
662    }
663    unsafe {
664        std::ptr::write_unaligned(
665            scratch.add(offset) as *mut u32,
666            state.component_state.len() as u32,
667        );
668    }
669    offset += 4;
670    if offset + state.component_state.len() > max_len {
671        return Err("scratch overflow".to_string());
672    }
673    unsafe {
674        std::ptr::copy_nonoverlapping(
675            state.component_state.as_ptr(),
676            scratch.add(offset),
677            state.component_state.len(),
678        );
679    }
680    offset += state.component_state.len();
681
682    if offset + 4 > max_len {
683        return Err("scratch overflow".to_string());
684    }
685    unsafe {
686        std::ptr::write_unaligned(
687            scratch.add(offset) as *mut u32,
688            state.controller_state.len() as u32,
689        );
690    }
691    offset += 4;
692    if offset + state.controller_state.len() > max_len {
693        return Err("scratch overflow".to_string());
694    }
695    unsafe {
696        std::ptr::copy_nonoverlapping(
697            state.controller_state.as_ptr(),
698            scratch.add(offset),
699            state.controller_state.len(),
700        );
701    }
702    offset += state.controller_state.len();
703
704    Ok(offset)
705}
706
707fn deserialize_vst3_state(scratch: *const u8, size: usize) -> Result<Vst3PluginState, String> {
708    if size < 12 {
709        return Err("scratch too small for VST3 state".to_string());
710    }
711    let mut offset = 0usize;
712
713    let plugin_id_len =
714        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
715    offset += 4;
716    if offset + plugin_id_len > size {
717        return Err("scratch underflow".to_string());
718    }
719    let mut plugin_id_bytes = vec![0u8; plugin_id_len];
720    unsafe {
721        std::ptr::copy_nonoverlapping(
722            scratch.add(offset),
723            plugin_id_bytes.as_mut_ptr(),
724            plugin_id_len,
725        );
726    }
727    offset += plugin_id_len;
728    let plugin_id = String::from_utf8(plugin_id_bytes).map_err(|e| e.to_string())?;
729
730    let component_state_len =
731        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
732    offset += 4;
733    if offset + component_state_len > size {
734        return Err("scratch underflow".to_string());
735    }
736    let mut component_state = vec![0u8; component_state_len];
737    unsafe {
738        std::ptr::copy_nonoverlapping(
739            scratch.add(offset),
740            component_state.as_mut_ptr(),
741            component_state_len,
742        );
743    }
744    offset += component_state_len;
745
746    let controller_state_len =
747        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
748    offset += 4;
749    if offset + controller_state_len > size {
750        return Err("scratch underflow".to_string());
751    }
752    let mut controller_state = vec![0u8; controller_state_len];
753    unsafe {
754        std::ptr::copy_nonoverlapping(
755            scratch.add(offset),
756            controller_state.as_mut_ptr(),
757            controller_state_len,
758        );
759    }
760
761    Ok(Vst3PluginState {
762        plugin_id,
763        component_state,
764        controller_state,
765    })
766}
767
768#[cfg(test)]
769mod tests {
770    use super::*;
771
772    fn find_host_binary() -> PathBuf {
773        ipc::find_plugin_host_binary().expect("maolan-plugin-host binary should be built for tests")
774    }
775
776    #[cfg_attr(
777        all(miri, target_os = "freebsd"),
778        ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
779    )]
780    #[test]
781    fn find_host_binary_locates_binary() {
782        let host_bin = find_host_binary();
783        assert!(
784            host_bin.exists(),
785            "plugin-host binary should exist at {}",
786            host_bin.display()
787        );
788    }
789
790    #[test]
791    fn vst3_state_serialization_roundtrip() {
792        let state = Vst3PluginState {
793            plugin_id: "test.plugin.vst3".to_string(),
794            component_state: vec![1, 2, 3, 4, 5],
795            controller_state: vec![10, 20, 30],
796        };
797        let mut scratch = vec![0u8; SCRATCH_SIZE];
798        let size =
799            serialize_vst3_state(scratch.as_mut_ptr(), &state).expect("serialize should succeed");
800        assert!(size > 0);
801        assert!(size < SCRATCH_SIZE);
802
803        let decoded =
804            deserialize_vst3_state(scratch.as_ptr(), size).expect("deserialize should succeed");
805        assert_eq!(decoded.plugin_id, state.plugin_id);
806        assert_eq!(decoded.component_state, state.component_state);
807        assert_eq!(decoded.controller_state, state.controller_state);
808    }
809
810    #[cfg_attr(
811        all(miri, target_os = "freebsd"),
812        ignore = "plugin host discovery/runtime uses OS facilities not supported by Miri on FreeBSD"
813    )]
814    #[test]
815    fn vst3_processor_crash_bypass() {
816        let host_bin = find_host_binary();
817
818        let processor = Vst3Processor::new(48000.0, 256, "__crash__", "__crash__", 1, 1, host_bin)
819            .expect("should create VST3 processor for crash test");
820
821        processor.setup_audio_ports();
822
823        let input_buffers = [vec![1.0; 256]];
824        let mut output_buffers = [vec![0.0; 256]];
825        let inputs = input_buffers.iter().map(Vec::as_slice).collect::<Vec<_>>();
826        let mut outputs = output_buffers
827            .iter_mut()
828            .map(Vec::as_mut_slice)
829            .collect::<Vec<_>>();
830        processor.process_with_audio_buffers(256, &inputs, &mut outputs);
831
832        let out_buf = &output_buffers[0];
833        assert!(
834            out_buf.iter().all(|&s| s == 1.0),
835            "after crash, output should be bypass copy of input"
836        );
837    }
838}