maolan-plugin-host 0.0.1

Out-of-process plugin host for Maolan DAW
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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
#[cfg(unix)]
use crate::lv2::{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: &crate::vst3::Vst3Processor,
    plugin_path: &str,
    ptr: *mut u8,
) -> 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 parent_window = {
        let header = unsafe { header_ref(ptr) };
        let parent = header.parent_window_usize();
        if parent != 0 {
            parent as x11_ffi::Window
        } else {
            root
        }
    };

    let window = unsafe {
        x11_ffi::XCreateSimpleWindow(
            display,
            parent_window,
            0,
            0, // position relative to parent
            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 })
}

// ---------------------------------------------------------------------------
// Windows GUI support for VST3
// ---------------------------------------------------------------------------
#[cfg(windows)]
mod win32_gui {
    use std::sync::atomic::{AtomicUsize, Ordering};

    static CLASS_ATOM: AtomicUsize = AtomicUsize::new(0);

    unsafe extern "system" fn wnd_proc(
        hwnd: windows_sys::Win32::Foundation::HWND,
        msg: u32,
        wparam: windows_sys::Win32::Foundation::WPARAM,
        lparam: windows_sys::Win32::Foundation::LPARAM,
    ) -> windows_sys::Win32::Foundation::LRESULT {
        unsafe {
            windows_sys::Win32::UI::WindowsAndMessaging::DefWindowProcW(hwnd, msg, wparam, lparam)
        }
    }

    pub fn ensure_class_registered() -> u16 {
        let atom = CLASS_ATOM.load(Ordering::Acquire);
        if atom != 0 {
            return atom as u16;
        }

        let class_name: Vec<u16> = "MaolanVst3Container\0".encode_utf16().collect();
        let wndclass = windows_sys::Win32::UI::WindowsAndMessaging::WNDCLASSEXW {
            cbSize: std::mem::size_of::<windows_sys::Win32::UI::WindowsAndMessaging::WNDCLASSEXW>()
                as u32,
            style: 0,
            lpfnWndProc: Some(wnd_proc),
            cbClsExtra: 0,
            cbWndExtra: 0,
            hInstance: unsafe {
                windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(std::ptr::null())
            } as *mut _,
            hIcon: std::ptr::null_mut(),
            hCursor: std::ptr::null_mut(),
            hbrBackground: (5 + 1) as *mut _, // COLOR_WINDOW = 5
            lpszMenuName: std::ptr::null(),
            lpszClassName: class_name.as_ptr(),
            hIconSm: std::ptr::null_mut(),
        };

        let atom =
            unsafe { windows_sys::Win32::UI::WindowsAndMessaging::RegisterClassExW(&wndclass) };
        if atom == 0 {
            return 0;
        }
        CLASS_ATOM.store(atom as usize, Ordering::Release);
        atom as u16
    }
}

/// Owns the Win32 container window for a VST3 plugin GUI.
#[cfg(windows)]
struct Vst3GuiWindow {
    hwnd: windows_sys::Win32::Foundation::HWND,
}

#[cfg(windows)]
impl Drop for Vst3GuiWindow {
    fn drop(&mut self) {
        unsafe {
            windows_sys::Win32::UI::WindowsAndMessaging::DestroyWindow(self.hwnd);
        }
    }
}

/// Create a Win32 container window, attach the VST3 plugin view to it, and show
/// the window. Called the first time GUI show is requested.
#[cfg(windows)]
fn create_vst3_gui(
    processor: &crate::vst3::Vst3Processor,
    plugin_path: &str,
    ptr: *mut u8,
) -> Result<Vst3GuiWindow, String> {
    use windows_sys::Win32::Foundation::HWND;
    use windows_sys::Win32::UI::WindowsAndMessaging::*;

    let atom = win32_gui::ensure_class_registered();
    if atom == 0 {
        return Err("VST3 GUI: failed to register window class".to_string());
    }

    let parent_hwnd: HWND = {
        let header = unsafe { header_ref(ptr) };
        let parent = header.parent_window_usize();
        if parent != 0 {
            parent as HWND
        } else {
            std::ptr::null_mut()
        }
    };

    let title: Vec<u16> = std::path::Path::new(plugin_path)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("Plugin")
        .encode_utf16()
        .chain(std::iter::once(0))
        .collect();

    let hwnd = unsafe {
        CreateWindowExW(
            0,
            atom as *const u16,
            title.as_ptr(),
            if parent_hwnd.is_null() {
                WS_OVERLAPPEDWINDOW
            } else {
                WS_CHILD | WS_VISIBLE
            },
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            800,
            600,
            parent_hwnd,
            std::ptr::null_mut(),
            windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(std::ptr::null()),
            std::ptr::null(),
        )
    };

    if hwnd.is_null() {
        return Err("VST3 GUI: failed to create window".to_string());
    }

    processor.gui_create("HWND").map_err(|e| {
        unsafe { DestroyWindow(hwnd) };
        format!("VST3 GUI: gui_create failed: {e}")
    })?;

    processor
        .gui_set_parent(hwnd as usize, "HWND")
        .map_err(|e| {
            unsafe { DestroyWindow(hwnd) };
            format!("VST3 GUI: gui_set_parent failed: {e}")
        })?;

    if let Ok((w, h)) = processor.gui_get_size()
        && w > 0
        && h > 0
    {
        unsafe {
            SetWindowPos(
                hwnd,
                std::ptr::null_mut(),
                0,
                0,
                w,
                h,
                SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,
            );
        }
    }

    unsafe {
        ShowWindow(hwnd, SW_SHOW);
    }

    Ok(Vst3GuiWindow { hwnd })
}

/// Drain parameter events from the DAW-side param ring and apply them to a VST3 processor.
fn apply_vst3_param_ring(processor: &crate::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_at(ev.param_index, ev.value, ev.sample_offset)
        {
            eprintln!("[plugin-host] VST3 set_parameter_value failed: {}", e);
        }
    }
}

/// Drain MIDI events from the DAW-side MIDI ring.
fn drain_midi_ring(ptr: *mut u8) -> Vec<crate::util::MidiEvent> {
    let ring = unsafe {
        let buf = midi_ring_ptr(ptr);
        let (w, r) = midi_indices(ptr);
        RingBuffer::new(buf, w, r, RING_CAPACITY)
    };
    let mut events = Vec::new();
    while let Some(ev) = ring.pop() {
        events.push(crate::util::MidiEvent {
            frame: ev.sample_offset,
            data: ev.data.to_vec(),
        });
    }
    events
}

/// Write MIDI output events to the MIDI out ring so the DAW can read them.
fn write_midi_out_ring(ptr: *mut u8, events: &[crate::util::MidiEvent]) {
    let ring = unsafe {
        let buf = midi_out_ring_ptr(ptr);
        let (w, r) = midi_out_indices(ptr);
        RingBuffer::new(buf, w, r, RING_CAPACITY)
    };
    for ev in events {
        let midi_ev = maolan_plugin_protocol::MidiEvent {
            sample_offset: ev.frame,
            data: {
                let mut d = [0u8; 3];
                for (i, b) in ev.data.iter().enumerate().take(3) {
                    d[i] = *b;
                }
                d
            },
            channel: ev.data.first().copied().unwrap_or(0) & 0x0F,
            flags: 0,
            _pad: 0,
        };
        if !ring.push(midi_ev) {
            eprintln!("[plugin-host] MIDI out ring full, dropping event");
            break;
        }
    }
}

/// Read transport state from shared memory and apply it to a VST3 processor.
fn apply_vst3_transport(processor: &crate::vst3::Vst3Processor, ptr: *mut u8) {
    let transport = unsafe { transport_ref(ptr) };
    let info = crate::vst3::processor::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.
///
/// Drains both:
/// 1. `performEdit` callbacks captured by the in-process `ComponentHandler`.
/// 2. Polled parameter values that changed since the last block.
fn write_vst3_echo_ring(
    processor: &crate::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)
    };

    // 1. Forward performEdit callbacks directly (plugin-initiated parameter echo).
    for (param_id, value) in processor.ui_take_param_updates() {
        let ev = ParameterEvent {
            param_index: param_id,
            value: value as f32,
            sample_offset: 0,
            event_kind: PARAM_EVENT_VALUE,
        };
        if !ring.push(ev) {
            eprintln!("[plugin-host] Echo ring full, dropping performEdit event");
            break;
        }
        // Update cache so the polling loop below doesn't duplicate the event.
        cache.insert(param_id, value as f32);
    }

    // 2. Poll remaining parameter values (catches changes from automation, host, etc.).
    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: &crate::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<crate::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(crate::vst3::state::Vst3PluginState {
        plugin_id,
        component_state,
        controller_state,
    })
}

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

pub fn run_vst3(args: Vst3RunArgs) {
    let Vst3RunArgs {
        plugin_path,
        mapping,
        events,
        instance_id,
        sample_rate,
        buffer_size,
        num_inputs,
        num_outputs,
    } = args;

    // Handle sentinel plugin paths for tests.
    match plugin_path {
        "__test__" => {
            let scratch = unsafe { scratch_ptr(mapping.as_ptr()) };
            unsafe {
                std::ptr::write_unaligned(scratch as *mut u32, 0xDEADBEEF);
            }
            return;
        }
        "__crash__" => {
            std::process::exit(1);
        }
        "__hang__" => loop {
            std::thread::sleep(Duration::from_secs(60));
        },
        _ => {}
    }

    let processor = match crate::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();

    unsafe {
        maolan_plugin_protocol::protocol::write_plugin_name_to_scratch(
            mapping.as_ptr(),
            processor.name(),
        );
    }

    let header = unsafe { header_ref(mapping.as_ptr()) };
    let ptr = mapping.as_ptr();
    let mut vst3_param_cache = HashMap::new();
    // Container window for VST3 GUI (created lazily on first GUI show request).
    #[cfg(any(windows, 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 container window on first call, then attach and map it.
                    #[cfg(any(windows, all(unix, not(target_os = "macos"))))]
                    {
                        if vst3_gui_window.is_none() {
                            match create_vst3_gui(&processor, plugin_path, ptr) {
                                Ok(gw) => {
                                    vst3_gui_window = Some(gw);
                                    processor.gui_show()
                                }
                                Err(e) => Err(e),
                            }
                        } else {
                            #[cfg(all(unix, not(target_os = "macos")))]
                            if let Some(ref gw) = vst3_gui_window {
                                unsafe {
                                    x11_ffi::XMapWindow(gw.display, gw.window);
                                    x11_ffi::XFlush(gw.display);
                                }
                            }
                            #[cfg(windows)]
                            if let Some(ref gw) = vst3_gui_window {
                                unsafe {
                                    windows_sys::Win32::UI::WindowsAndMessaging::ShowWindow(
                                        gw.hwnd,
                                        windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOW,
                                    );
                                }
                            }
                            processor.gui_show()
                        }
                    }
                    #[cfg(not(any(windows, 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);
                        }
                    }
                    #[cfg(windows)]
                    if let Some(ref gw) = vst3_gui_window {
                        unsafe {
                            windows_sys::Win32::UI::WindowsAndMessaging::ShowWindow(
                                gw.hwnd,
                                windows_sys::Win32::UI::WindowsAndMessaging::SW_HIDE,
                            );
                        }
                    }
                    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;
        }

        // Read MIDI input events from DAW.
        let midi_input = drain_midi_ring(ptr);

        // Process.
        let _midi_output = if processor.midi_input_count() > 0 || processor.midi_output_count() > 0
        {
            processor.process_with_midi(block_size, &midi_input)
        } else {
            processor.process_with_audio_io(block_size);
            Vec::new()
        };

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

        // Write MIDI output events back to DAW.
        write_midi_out_ring(ptr, &_midi_output);

        // 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.
#[cfg(unix)]
fn apply_lv2_param_ring(processor: &mut crate::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.
#[cfg(unix)]
fn read_lv2_transport(ptr: *mut u8) -> crate::lv2::Lv2TransportInfo {
    let transport = unsafe { transport_ref(ptr) };
    crate::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.
#[cfg(unix)]
fn write_lv2_echo_ring(
    processor: &crate::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.
#[cfg(unix)]
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.
#[cfg(unix)]
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,
    })
}

#[cfg(unix)]
pub fn run_lv2(
    plugin_uri: &str,
    mapping: ShmMapping,
    events: EventPair,
    instance_id: &str,
    sample_rate: f64,
    buffer_size: usize,
) {
    // Handle sentinel plugin paths for tests.
    match plugin_uri {
        "__test__" => {
            let scratch = unsafe { scratch_ptr(mapping.as_ptr()) };
            unsafe {
                std::ptr::write_unaligned(scratch as *mut u32, 0xDEADBEEF);
            }
            return;
        }
        "__crash__" => {
            std::process::exit(1);
        }
        "__hang__" => loop {
            std::thread::sleep(Duration::from_secs(60));
        },
        _ => {}
    }

    let mut processor = match crate::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;
        }
    };

    unsafe {
        maolan_plugin_protocol::protocol::write_plugin_name_to_scratch(
            mapping.as_ptr(),
            processor.name(),
        );
    }

    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;
        }

        // Read MIDI input events from DAW.
        let midi_input = drain_midi_ring(ptr);
        let midi_per_port: Vec<Vec<crate::util::MidiEvent>> = if processor.midi_input_count() > 0 {
            vec![midi_input]
        } else {
            vec![]
        };

        // Process.
        let midi_out = processor.process_with_audio_io(block_size, &midi_per_port, transport);

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

        // Write MIDI output events back to DAW.
        let mut all_midi_out = Vec::new();
        for port_events in midi_out {
            all_midi_out.extend(port_events);
        }
        write_midi_out_ring(ptr, &all_midi_out);

        // 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 {
    #[cfg(unix)]
    use super::*;

    #[test]
    #[cfg(unix)]
    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);
    }
}