maolan-engine 0.2.0

Audio engine for the Maolan DAW with audio/MIDI tracks, routing, export, and CLAP/VST3/LV2 hosting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
use maolan_engine::message::{Lv2PluginState, Lv2StatePortValue, Lv2StateProperty};
use maolan_plugin_protocol::events::EventPair;
use maolan_plugin_protocol::protocol::*;
use maolan_plugin_protocol::ringbuf::RingBuffer;
use maolan_plugin_protocol::shm::ShmMapping;
use std::collections::HashMap;
use std::sync::atomic::Ordering;
use std::time::Duration;

// ---------------------------------------------------------------------------
// X11 GUI support for VST3 (FreeBSD / Linux only)
// ---------------------------------------------------------------------------
#[cfg(all(unix, not(target_os = "macos")))]
mod x11_ffi {
    use std::os::raw::{c_char, c_int, c_uint, c_ulong};
    pub type Display = std::ffi::c_void;
    pub type Window = c_ulong;

    #[link(name = "X11")]
    unsafe extern "C" {
        pub fn XOpenDisplay(display_name: *const c_char) -> *mut Display;
        pub fn XCloseDisplay(display: *mut Display) -> c_int;
        pub fn XDefaultScreen(display: *mut Display) -> c_int;
        pub fn XRootWindow(display: *mut Display, screen: c_int) -> Window;
        pub fn XBlackPixel(display: *mut Display, screen: c_int) -> c_ulong;
        pub fn XWhitePixel(display: *mut Display, screen: c_int) -> c_ulong;
        pub fn XCreateSimpleWindow(
            display: *mut Display,
            parent: Window,
            x: c_int,
            y: c_int,
            width: c_uint,
            height: c_uint,
            border_width: c_uint,
            border: c_ulong,
            background: c_ulong,
        ) -> Window;
        pub fn XStoreName(display: *mut Display, w: Window, name: *const c_char) -> c_int;
        pub fn XMapWindow(display: *mut Display, w: Window) -> c_int;
        pub fn XUnmapWindow(display: *mut Display, w: Window) -> c_int;
        pub fn XDestroyWindow(display: *mut Display, w: Window) -> c_int;
        pub fn XResizeWindow(
            display: *mut Display,
            w: Window,
            width: c_uint,
            height: c_uint,
        ) -> c_int;
        pub fn XFlush(display: *mut Display) -> c_int;
    }
}

/// Owns the X11 display connection and container window for a VST3 plugin GUI.
#[cfg(all(unix, not(target_os = "macos")))]
struct Vst3GuiWindow {
    display: *mut x11_ffi::Display,
    window: x11_ffi::Window,
}

// The display pointer is only used from the single plugin-host main thread.
#[cfg(all(unix, not(target_os = "macos")))]
unsafe impl Send for Vst3GuiWindow {}

#[cfg(all(unix, not(target_os = "macos")))]
impl Drop for Vst3GuiWindow {
    fn drop(&mut self) {
        unsafe {
            x11_ffi::XDestroyWindow(self.display, self.window);
            x11_ffi::XFlush(self.display);
            x11_ffi::XCloseDisplay(self.display);
        }
    }
}

/// Create an X11 container window, attach the VST3 plugin view to it, and map
/// (show) the window.  Called the first time GUI show is requested.
#[cfg(all(unix, not(target_os = "macos")))]
fn create_vst3_gui(
    processor: &maolan_engine::plugins::vst3::Vst3Processor,
    plugin_path: &str,
) -> Result<Vst3GuiWindow, String> {
    use std::os::raw::c_uint;

    let display = unsafe { x11_ffi::XOpenDisplay(std::ptr::null()) };
    if display.is_null() {
        return Err("VST3 GUI: failed to open X11 display".to_string());
    }

    let screen = unsafe { x11_ffi::XDefaultScreen(display) };
    let root = unsafe { x11_ffi::XRootWindow(display, screen) };
    let black = unsafe { x11_ffi::XBlackPixel(display, screen) };
    let white = unsafe { x11_ffi::XWhitePixel(display, screen) };

    let window = unsafe {
        x11_ffi::XCreateSimpleWindow(
            display, root, 100, 100, // initial position
            800, 600, // initial size (resized after gui_get_size)
            1, black, white,
        )
    };
    if window == 0 {
        unsafe {
            x11_ffi::XCloseDisplay(display);
        }
        return Err("VST3 GUI: failed to create X11 container window".to_string());
    }

    // Use the plugin file name as the window title.
    let title = std::path::Path::new(plugin_path)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("Plugin");
    if let Ok(cstr) = std::ffi::CString::new(title) {
        unsafe {
            x11_ffi::XStoreName(display, window, cstr.as_ptr());
        }
    }

    // Create the VST3 IPlugView and verify X11EmbedWindowID is supported.
    processor.gui_create("X11EmbedWindowID").map_err(|e| {
        unsafe {
            x11_ffi::XDestroyWindow(display, window);
            x11_ffi::XCloseDisplay(display);
        }
        format!("VST3 GUI: gui_create failed: {e}")
    })?;

    // Attach the view to our container window.
    processor
        .gui_set_parent(window as usize, "X11EmbedWindowID")
        .map_err(|e| {
            unsafe {
                x11_ffi::XDestroyWindow(display, window);
                x11_ffi::XCloseDisplay(display);
            }
            format!("VST3 GUI: gui_set_parent failed: {e}")
        })?;

    // Resize container to the plugin's preferred size.
    if let Ok((w, h)) = processor.gui_get_size()
        && w > 0
        && h > 0
    {
        unsafe {
            x11_ffi::XResizeWindow(display, window, w as c_uint, h as c_uint);
        }
    }

    unsafe {
        x11_ffi::XMapWindow(display, window);
        x11_ffi::XFlush(display);
    }

    Ok(Vst3GuiWindow { display, window })
}

fn print_usage() {
    eprintln!(
        "Usage: maolan-engine-plugin-host <format> <plugin-spec> <shm-name> <instance-id> <d2h-fd> <h2d-fd> <sample-rate> <buffer-size> <num-inputs> <num-outputs>"
    );
    eprintln!("  format: vst3 | lv2");
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 11 {
        print_usage();
        std::process::exit(1);
    }

    let format = args[1].clone();
    let plugin_spec = args[2].clone();
    let shm_name = args[3].clone();
    let instance_id = args[4].clone();
    let d2h_fd: i32 = args[5].parse().unwrap_or(-1);
    let h2d_fd: i32 = args[6].parse().unwrap_or(-1);
    let sample_rate: f64 = args[7].parse().unwrap_or(48000.0);
    let buffer_size: usize = args[8].parse().unwrap_or(256);
    let num_inputs: usize = args[9].parse().unwrap_or(2);
    let num_outputs: usize = args[10].parse().unwrap_or(2);

    if d2h_fd < 0 || h2d_fd < 0 {
        eprintln!("Invalid event pipe file descriptors");
        std::process::exit(3);
    }

    let mapping = match ShmMapping::open_existing(&shm_name, SHM_SIZE) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("Failed to attach to shared memory '{}': {}", shm_name, e);
            std::process::exit(2);
        }
    };

    let events = unsafe { EventPair::from_fds(d2h_fd, h2d_fd) };

    // Signal readiness.
    let header = unsafe { header_mut(mapping.as_ptr()) };
    header.ready.store(1, Ordering::Release);
    eprintln!(
        "[plugin-host {}] Ready for {} plugin {}",
        instance_id, format, plugin_spec
    );

    match plugin_spec.as_str() {
        "__test__" => {
            let scratch = unsafe { scratch_ptr(mapping.as_ptr()) };
            unsafe {
                std::ptr::write_unaligned(scratch as *mut u32, 0xDEADBEEF);
            }
            return;
        }
        "__crash__" => {
            // Use exit(1) instead of abort() to avoid core-dump delays
            // that can cause waitpid(WNOHANG) to return 0 on some platforms
            std::process::exit(1);
        }
        "__hang__" => loop {
            std::thread::sleep(Duration::from_secs(60));
        },
        _ => {}
    }

    match format.as_str() {
        "vst3" => run_vst3(Vst3RunArgs {
            plugin_path: &plugin_spec,
            mapping,
            events,
            instance_id: &instance_id,
            sample_rate,
            buffer_size,
            num_inputs,
            num_outputs,
        }),
        "lv2" => run_lv2(
            &plugin_spec,
            mapping,
            events,
            &instance_id,
            sample_rate,
            buffer_size,
        ),
        _ => {
            eprintln!("Unknown format: {}", format);
            std::process::exit(4);
        }
    }
}

/// Drain parameter events from the DAW-side param ring and apply them to a VST3 processor.
fn apply_vst3_param_ring(processor: &maolan_engine::plugins::vst3::Vst3Processor, ptr: *mut u8) {
    let ring = unsafe {
        let buf = param_ring_ptr(ptr);
        let (w, r) = param_indices(ptr);
        RingBuffer::new(buf, w, r, RING_CAPACITY)
    };
    while let Some(ev) = ring.pop() {
        if let Err(e) = processor.set_parameter_value(ev.param_index, ev.value) {
            eprintln!("[plugin-host] VST3 set_parameter_value failed: {}", e);
        }
    }
}

/// Read transport state from shared memory and apply it to a VST3 processor.
fn apply_vst3_transport(processor: &maolan_engine::plugins::vst3::Vst3Processor, ptr: *mut u8) {
    let transport = unsafe { transport_ref(ptr) };
    let info = maolan_engine::plugins::vst3::Vst3TransportInfo {
        playhead_sample: transport.playhead_sample as i64,
        playing: transport.flags & 0x1 != 0, // bit 0 = playing
        tempo: transport.tempo,
        tsig_num: transport.numerator as i32,
        tsig_denom: transport.denominator as i32,
    };
    processor.set_transport_info(info);
}

/// Write VST3 parameter changes to the echo ring.
fn write_vst3_echo_ring(
    processor: &maolan_engine::plugins::vst3::Vst3Processor,
    ptr: *mut u8,
    cache: &mut HashMap<u32, f32>,
) {
    let ring = unsafe {
        let buf = echo_ring_ptr(ptr);
        let (w, r) = echo_indices(ptr);
        RingBuffer::new(buf, w, r, RING_CAPACITY)
    };
    for param in processor.parameters() {
        let current = processor.get_parameter_value(param.id).unwrap_or(0.0);
        if cache.get(&param.id) != Some(&current) {
            let ev = ParameterEvent {
                param_index: param.id,
                value: current,
                sample_offset: 0,
                event_kind: PARAM_EVENT_VALUE,
            };
            if !ring.push(ev) {
                eprintln!("[plugin-host] Echo ring full, dropping parameter event");
                break;
            }
            cache.insert(param.id, current);
        }
    }
}

/// Serialize VST3 state into scratch area. Returns bytes written or error.
fn serialize_vst3_state(
    scratch: *mut u8,
    state: &maolan_engine::plugins::vst3::state::Vst3PluginState,
) -> Result<usize, String> {
    let max_len = SCRATCH_SIZE;
    let mut offset = 0usize;

    let plugin_id_bytes = state.plugin_id.as_bytes();
    if offset + 4 > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::write_unaligned(
            scratch.add(offset) as *mut u32,
            plugin_id_bytes.len() as u32,
        );
    }
    offset += 4;
    if offset + plugin_id_bytes.len() > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::copy_nonoverlapping(
            plugin_id_bytes.as_ptr(),
            scratch.add(offset),
            plugin_id_bytes.len(),
        );
    }
    offset += plugin_id_bytes.len();

    if offset + 4 > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::write_unaligned(
            scratch.add(offset) as *mut u32,
            state.component_state.len() as u32,
        );
    }
    offset += 4;
    if offset + state.component_state.len() > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::copy_nonoverlapping(
            state.component_state.as_ptr(),
            scratch.add(offset),
            state.component_state.len(),
        );
    }
    offset += state.component_state.len();

    if offset + 4 > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::write_unaligned(
            scratch.add(offset) as *mut u32,
            state.controller_state.len() as u32,
        );
    }
    offset += 4;
    if offset + state.controller_state.len() > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::copy_nonoverlapping(
            state.controller_state.as_ptr(),
            scratch.add(offset),
            state.controller_state.len(),
        );
    }
    offset += state.controller_state.len();

    Ok(offset)
}

/// Deserialize VST3 state from scratch area.
fn deserialize_vst3_state(
    scratch: *const u8,
    size: usize,
) -> Result<maolan_engine::plugins::vst3::state::Vst3PluginState, String> {
    if size < 12 {
        return Err("scratch too small for VST3 state".to_string());
    }
    let mut offset = 0usize;

    let plugin_id_len =
        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
    offset += 4;
    if offset + plugin_id_len > size {
        return Err("scratch underflow".to_string());
    }
    let mut plugin_id_bytes = vec![0u8; plugin_id_len];
    unsafe {
        std::ptr::copy_nonoverlapping(
            scratch.add(offset),
            plugin_id_bytes.as_mut_ptr(),
            plugin_id_len,
        );
    }
    offset += plugin_id_len;
    let plugin_id = String::from_utf8(plugin_id_bytes).map_err(|e| e.to_string())?;

    let component_state_len =
        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
    offset += 4;
    if offset + component_state_len > size {
        return Err("scratch underflow".to_string());
    }
    let mut component_state = vec![0u8; component_state_len];
    unsafe {
        std::ptr::copy_nonoverlapping(
            scratch.add(offset),
            component_state.as_mut_ptr(),
            component_state_len,
        );
    }
    offset += component_state_len;

    let controller_state_len =
        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
    offset += 4;
    if offset + controller_state_len > size {
        return Err("scratch underflow".to_string());
    }
    let mut controller_state = vec![0u8; controller_state_len];
    unsafe {
        std::ptr::copy_nonoverlapping(
            scratch.add(offset),
            controller_state.as_mut_ptr(),
            controller_state_len,
        );
    }

    Ok(maolan_engine::plugins::vst3::state::Vst3PluginState {
        plugin_id,
        component_state,
        controller_state,
    })
}

struct Vst3RunArgs<'a> {
    plugin_path: &'a str,
    mapping: ShmMapping,
    events: EventPair,
    instance_id: &'a str,
    sample_rate: f64,
    buffer_size: usize,
    num_inputs: usize,
    num_outputs: usize,
}

fn run_vst3(args: Vst3RunArgs) {
    let Vst3RunArgs {
        plugin_path,
        mapping,
        events,
        instance_id,
        sample_rate,
        buffer_size,
        num_inputs,
        num_outputs,
    } = args;
    let processor = match maolan_engine::plugins::vst3::Vst3Processor::new_with_sample_rate(
        sample_rate,
        buffer_size,
        plugin_path,
        num_inputs,
        num_outputs,
    ) {
        Ok(p) => p,
        Err(e) => {
            eprintln!(
                "[plugin-host {}] Failed to load VST3 plugin '{}': {}",
                instance_id, plugin_path, e
            );
            return;
        }
    };

    processor.setup_audio_ports();

    let header = unsafe { header_ref(mapping.as_ptr()) };
    let ptr = mapping.as_ptr();
    let mut vst3_param_cache = HashMap::new();
    // X11 container window for VST3 GUI (created lazily on first GUI show request).
    #[cfg(all(unix, not(target_os = "macos")))]
    let mut vst3_gui_window: Option<Vst3GuiWindow> = None;

    loop {
        if header.shutdown_request.load(Ordering::Acquire) != 0 {
            eprintln!("[plugin-host {}] Shutdown requested", instance_id);
            break;
        }

        // Check for state/GUI request before waiting for audio signal.
        let req = header.request_type.load(Ordering::Acquire);
        if req != 0 {
            let scratch = unsafe { scratch_ptr(ptr) };
            let result = match req {
                1 => {
                    // Save state
                    match processor.snapshot_state() {
                        Ok(state) => match serialize_vst3_state(scratch, &state) {
                            Ok(size) => {
                                header.scratch_size.store(size as u32, Ordering::Release);
                                Ok(())
                            }
                            Err(e) => Err(e),
                        },
                        Err(e) => Err(e),
                    }
                }
                2 => {
                    // Restore state
                    let size = header.scratch_size.load(Ordering::Acquire) as usize;
                    match deserialize_vst3_state(scratch, size) {
                        Ok(state) => processor.restore_state(&state),
                        Err(e) => Err(e),
                    }
                }
                3 => {
                    // GUI show — create an X11 container window on first call,
                    // then attach and map it.
                    #[cfg(all(unix, not(target_os = "macos")))]
                    {
                        if vst3_gui_window.is_none() {
                            match create_vst3_gui(&processor, plugin_path) {
                                Ok(gw) => {
                                    vst3_gui_window = Some(gw);
                                    processor.gui_show()
                                }
                                Err(e) => Err(e),
                            }
                        } else {
                            if let Some(ref gw) = vst3_gui_window {
                                unsafe {
                                    x11_ffi::XMapWindow(gw.display, gw.window);
                                    x11_ffi::XFlush(gw.display);
                                }
                            }
                            processor.gui_show()
                        }
                    }
                    #[cfg(not(all(unix, not(target_os = "macos"))))]
                    Err("VST3 GUI not supported on this platform".to_string())
                }
                4 => {
                    // GUI hide
                    #[cfg(all(unix, not(target_os = "macos")))]
                    if let Some(ref gw) = vst3_gui_window {
                        unsafe {
                            x11_ffi::XUnmapWindow(gw.display, gw.window);
                            x11_ffi::XFlush(gw.display);
                        }
                    }
                    processor.gui_hide();
                    Ok(())
                }
                _ => Err(format!("Unknown request type: {}", req)),
            };
            header
                .request_status
                .store(if result.is_ok() { 1 } else { 2 }, Ordering::Release);
            // Only wake the DAW for state operations (save=1, restore=2).
            // GUI requests (show=3, hide=4) are fire-and-forget — signalling
            // here would corrupt the audio-completion pipe handshake.
            if req == 1 || req == 2 {
                let _ = events.signal_daw();
            }
            header.request_type.store(0, Ordering::Release);
            continue;
        }

        match events.wait_daw(Duration::from_millis(100)) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => continue,
            Err(e) => {
                eprintln!("[plugin-host {}] Event error: {}", instance_id, e);
                break;
            }
        }

        let block_size = header.block_size.load(Ordering::Acquire) as usize;
        let num_in = header.num_input_channels.load(Ordering::Acquire) as usize;
        let num_out = header.num_output_channels.load(Ordering::Acquire) as usize;

        if block_size == 0 || block_size > MAX_BLOCK_SIZE {
            eprintln!(
                "[plugin-host {}] Invalid block size {}, skipping",
                instance_id, block_size
            );
            let _ = events.signal_daw();
            continue;
        }

        // Apply parameter changes from DAW before processing.
        apply_vst3_param_ring(&processor, ptr);

        // Apply transport state before processing.
        apply_vst3_transport(&processor, ptr);

        // Copy SHM input (bus 0) to processor input buffers.
        let inputs = processor.audio_inputs();
        for (ch, input) in inputs.iter().enumerate().take(num_in) {
            let src = unsafe { audio_channel_ptr(ptr, ch, 0) };
            let dst = input.buffer.lock();
            let len = block_size.min(dst.len());
            unsafe {
                std::ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), len);
            }
            *input.finished.lock() = true;
        }

        // Process.
        processor.process_with_audio_io(block_size);

        // Echo parameter changes back to DAW.
        write_vst3_echo_ring(&processor, ptr, &mut vst3_param_cache);

        // Copy processor output buffers to SHM output (bus 1).
        let outputs = processor.audio_outputs();
        for (ch, output) in outputs.iter().enumerate().take(num_out) {
            let src = output.buffer.lock();
            let dst = unsafe { audio_channel_ptr(ptr, ch, 1) };
            let len = block_size.min(src.len());
            unsafe {
                std::ptr::copy_nonoverlapping(src.as_ptr(), dst, len);
            }
        }

        if let Err(e) = events.signal_daw() {
            eprintln!("[plugin-host {}] Failed to signal DAW: {}", instance_id, e);
            break;
        }
    }

    eprintln!("[plugin-host {}] VST3 host exiting", instance_id);
}

/// Drain parameter events from the DAW-side param ring and apply them to an LV2 processor.
fn apply_lv2_param_ring(processor: &mut maolan_engine::plugins::lv2::Lv2Processor, ptr: *mut u8) {
    let ring = unsafe {
        let buf = param_ring_ptr(ptr);
        let (w, r) = param_indices(ptr);
        RingBuffer::new(buf, w, r, RING_CAPACITY)
    };
    while let Some(ev) = ring.pop() {
        if let Err(e) = processor.set_control_value(ev.param_index, ev.value) {
            eprintln!("[plugin-host] LV2 set_control_value failed: {}", e);
        }
    }
}

/// Read transport state from shared memory and build LV2 transport info.
fn read_lv2_transport(ptr: *mut u8) -> maolan_engine::plugins::lv2::Lv2TransportInfo {
    let transport = unsafe { transport_ref(ptr) };
    maolan_engine::plugins::lv2::Lv2TransportInfo {
        transport_sample: transport.playhead_sample as usize,
        playing: transport.flags & 0x1 != 0,
        bpm: transport.tempo,
        tsig_num: transport.numerator,
        tsig_denom: transport.denominator,
    }
}

/// Write LV2 control-port changes to the echo ring.
fn write_lv2_echo_ring(
    processor: &maolan_engine::plugins::lv2::Lv2Processor,
    ptr: *mut u8,
    cache: &mut HashMap<u32, f32>,
) {
    let ring = unsafe {
        let buf = echo_ring_ptr(ptr);
        let (w, r) = echo_indices(ptr);
        RingBuffer::new(buf, w, r, RING_CAPACITY)
    };
    for port in processor.control_ports_with_values() {
        let current = port.value;
        if cache.get(&port.index) != Some(&current) {
            let ev = ParameterEvent {
                param_index: port.index,
                value: current,
                sample_offset: 0,
                event_kind: PARAM_EVENT_VALUE,
            };
            if !ring.push(ev) {
                eprintln!("[plugin-host] Echo ring full, dropping parameter event");
                break;
            }
            cache.insert(port.index, current);
        }
    }
}

/// Serialize LV2 state into scratch area. Returns bytes written or error.
fn serialize_lv2_state(scratch: *mut u8, state: &Lv2PluginState) -> Result<usize, String> {
    let max_len = SCRATCH_SIZE;
    let mut offset = 0usize;

    // Port values
    if offset + 4 > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::write_unaligned(
            scratch.add(offset) as *mut u32,
            state.port_values.len() as u32,
        );
    }
    offset += 4;
    for v in &state.port_values {
        if offset + 8 > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::write_unaligned(scratch.add(offset) as *mut u32, v.index);
        }
        offset += 4;
        unsafe {
            std::ptr::write_unaligned(scratch.add(offset) as *mut u32, v.value.to_bits());
        }
        offset += 4;
    }

    // Properties
    if offset + 4 > max_len {
        return Err("scratch overflow".to_string());
    }
    unsafe {
        std::ptr::write_unaligned(
            scratch.add(offset) as *mut u32,
            state.properties.len() as u32,
        );
    }
    offset += 4;
    for prop in &state.properties {
        let key_bytes = prop.key_uri.as_bytes();
        if offset + 4 > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::write_unaligned(scratch.add(offset) as *mut u32, key_bytes.len() as u32);
        }
        offset += 4;
        if offset + key_bytes.len() > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::copy_nonoverlapping(key_bytes.as_ptr(), scratch.add(offset), key_bytes.len());
        }
        offset += key_bytes.len();

        let type_bytes = prop.type_uri.as_bytes();
        if offset + 4 > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::write_unaligned(scratch.add(offset) as *mut u32, type_bytes.len() as u32);
        }
        offset += 4;
        if offset + type_bytes.len() > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::copy_nonoverlapping(
                type_bytes.as_ptr(),
                scratch.add(offset),
                type_bytes.len(),
            );
        }
        offset += type_bytes.len();

        if offset + 4 > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::write_unaligned(scratch.add(offset) as *mut u32, prop.flags);
        }
        offset += 4;
        if offset + 4 > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::write_unaligned(scratch.add(offset) as *mut u32, prop.value.len() as u32);
        }
        offset += 4;
        if offset + prop.value.len() > max_len {
            return Err("scratch overflow".to_string());
        }
        unsafe {
            std::ptr::copy_nonoverlapping(
                prop.value.as_ptr(),
                scratch.add(offset),
                prop.value.len(),
            );
        }
        offset += prop.value.len();
    }

    Ok(offset)
}

/// Deserialize LV2 state from scratch area.
fn deserialize_lv2_state(scratch: *const u8, size: usize) -> Result<Lv2PluginState, String> {
    if size < 8 {
        return Err("scratch too small for LV2 state".to_string());
    }
    let mut offset = 0usize;

    let port_count =
        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
    offset += 4;
    let mut port_values = Vec::with_capacity(port_count);
    for _ in 0..port_count {
        if offset + 8 > size {
            return Err("scratch underflow".to_string());
        }
        let index = unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) };
        offset += 4;
        let bits = unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) };
        offset += 4;
        port_values.push(Lv2StatePortValue {
            index,
            value: f32::from_bits(bits),
        });
    }

    let prop_count =
        unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
    offset += 4;
    let mut properties = Vec::with_capacity(prop_count);
    for _ in 0..prop_count {
        let key_len =
            unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
        offset += 4;
        if offset + key_len > size {
            return Err("scratch underflow".to_string());
        }
        let mut key_bytes = vec![0u8; key_len];
        unsafe {
            std::ptr::copy_nonoverlapping(scratch.add(offset), key_bytes.as_mut_ptr(), key_len);
        }
        offset += key_len;
        let key_uri = String::from_utf8(key_bytes).map_err(|e| e.to_string())?;

        let type_len =
            unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
        offset += 4;
        if offset + type_len > size {
            return Err("scratch underflow".to_string());
        }
        let mut type_bytes = vec![0u8; type_len];
        unsafe {
            std::ptr::copy_nonoverlapping(scratch.add(offset), type_bytes.as_mut_ptr(), type_len);
        }
        offset += type_len;
        let type_uri = String::from_utf8(type_bytes).map_err(|e| e.to_string())?;

        let flags = unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) };
        offset += 4;
        let value_len =
            unsafe { std::ptr::read_unaligned(scratch.add(offset) as *const u32) } as usize;
        offset += 4;
        if offset + value_len > size {
            return Err("scratch underflow".to_string());
        }
        let mut value = vec![0u8; value_len];
        unsafe {
            std::ptr::copy_nonoverlapping(scratch.add(offset), value.as_mut_ptr(), value_len);
        }
        offset += value_len;

        properties.push(Lv2StateProperty {
            key_uri,
            type_uri,
            flags,
            value,
        });
    }

    Ok(Lv2PluginState {
        port_values,
        properties,
    })
}

fn run_lv2(
    plugin_uri: &str,
    mapping: ShmMapping,
    events: EventPair,
    instance_id: &str,
    sample_rate: f64,
    buffer_size: usize,
) {
    let mut processor = match maolan_engine::plugins::lv2::Lv2Processor::new(
        sample_rate,
        buffer_size,
        plugin_uri,
    ) {
        Ok(p) => p,
        Err(e) => {
            eprintln!(
                "[plugin-host {}] Failed to load LV2 plugin '{}': {}",
                instance_id, plugin_uri, e
            );
            return;
        }
    };

    let header = unsafe { header_ref(mapping.as_ptr()) };
    let ptr = mapping.as_ptr();
    let mut lv2_param_cache = HashMap::new();

    loop {
        if header.shutdown_request.load(Ordering::Acquire) != 0 {
            eprintln!("[plugin-host {}] Shutdown requested", instance_id);
            break;
        }

        // Check for state/GUI request before waiting for audio signal.
        let req = header.request_type.load(Ordering::Acquire);
        if req != 0 {
            let scratch = unsafe { scratch_ptr(ptr) };
            let result = match req {
                1 => {
                    // Save state
                    let state = processor.snapshot_state();
                    match serialize_lv2_state(scratch, &state) {
                        Ok(size) => {
                            header.scratch_size.store(size as u32, Ordering::Release);
                            Ok(())
                        }
                        Err(e) => Err(e),
                    }
                }
                2 => {
                    // Restore state
                    let size = header.scratch_size.load(Ordering::Acquire) as usize;
                    match deserialize_lv2_state(scratch, size) {
                        Ok(state) => processor.restore_state(&state),
                        Err(e) => Err(e),
                    }
                }
                // GUI show/hide: LV2 has no GUI support in the plugin host yet.
                3 => Err("LV2 GUI not yet supported".to_string()),
                4 => Ok(()),
                _ => Err(format!("Unknown request type: {}", req)),
            };
            header
                .request_status
                .store(if result.is_ok() { 1 } else { 2 }, Ordering::Release);
            // Only wake the DAW for state operations (save=1, restore=2).
            // GUI requests (show=3, hide=4) are fire-and-forget — signalling
            // here would corrupt the audio-completion pipe handshake.
            if req == 1 || req == 2 {
                let _ = events.signal_daw();
            }
            header.request_type.store(0, Ordering::Release);
            continue;
        }

        match events.wait_daw(Duration::from_millis(100)) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => continue,
            Err(e) => {
                eprintln!("[plugin-host {}] Event error: {}", instance_id, e);
                break;
            }
        }

        let block_size = header.block_size.load(Ordering::Acquire) as usize;
        let num_in = header.num_input_channels.load(Ordering::Acquire) as usize;
        let num_out = header.num_output_channels.load(Ordering::Acquire) as usize;

        if block_size == 0 || block_size > MAX_BLOCK_SIZE {
            eprintln!(
                "[plugin-host {}] Invalid block size {}, skipping",
                instance_id, block_size
            );
            let _ = events.signal_daw();
            continue;
        }

        // Apply parameter changes from DAW before processing.
        apply_lv2_param_ring(&mut processor, ptr);

        // Read transport state before processing.
        let transport = read_lv2_transport(ptr);

        // Copy SHM input (bus 0) to processor input buffers.
        let inputs = processor.audio_inputs();
        for (ch, input) in inputs.iter().enumerate().take(num_in) {
            let src = unsafe { audio_channel_ptr(ptr, ch, 0) };
            let dst = input.buffer.lock();
            let len = block_size.min(dst.len());
            unsafe {
                std::ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), len);
            }
            *input.finished.lock() = true;
        }

        // Process.
        let _midi_out = processor.process_with_audio_io(block_size, &[], transport);

        // Echo parameter changes back to DAW.
        write_lv2_echo_ring(&processor, ptr, &mut lv2_param_cache);

        // Copy processor output buffers to SHM output (bus 1).
        let outputs = processor.audio_outputs();
        for (ch, output) in outputs.iter().enumerate().take(num_out) {
            let src = output.buffer.lock();
            let dst = unsafe { audio_channel_ptr(ptr, ch, 1) };
            let len = block_size.min(src.len());
            unsafe {
                std::ptr::copy_nonoverlapping(src.as_ptr(), dst, len);
            }
        }

        if let Err(e) = events.signal_daw() {
            eprintln!("[plugin-host {}] Failed to signal DAW: {}", instance_id, e);
            break;
        }
    }

    eprintln!("[plugin-host {}] LV2 host exiting", instance_id);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lv2_state_serialization_roundtrip() {
        let state = Lv2PluginState {
            port_values: vec![
                Lv2StatePortValue {
                    index: 0,
                    value: 0.5,
                },
                Lv2StatePortValue {
                    index: 1,
                    value: 1.0,
                },
            ],
            properties: vec![Lv2StateProperty {
                key_uri: "http://example.com/key".to_string(),
                type_uri: "http://example.com/type".to_string(),
                flags: 0,
                value: vec![1, 2, 3],
            }],
        };
        let mut scratch = vec![0u8; SCRATCH_SIZE];
        let size =
            serialize_lv2_state(scratch.as_mut_ptr(), &state).expect("serialize should succeed");
        assert!(size > 0);
        assert!(size < SCRATCH_SIZE);

        let decoded =
            deserialize_lv2_state(scratch.as_ptr(), size).expect("deserialize should succeed");
        assert_eq!(decoded.port_values.len(), state.port_values.len());
        assert_eq!(decoded.port_values[0].index, state.port_values[0].index);
        assert_eq!(decoded.port_values[0].value, state.port_values[0].value);
        assert_eq!(decoded.properties.len(), state.properties.len());
        assert_eq!(decoded.properties[0].key_uri, state.properties[0].key_uri);
        assert_eq!(decoded.properties[0].type_uri, state.properties[0].type_uri);
        assert_eq!(decoded.properties[0].flags, state.properties[0].flags);
        assert_eq!(decoded.properties[0].value, state.properties[0].value);
    }
}