vst3-host 0.7.0

Safe, simple VST3 plugin hosting with audio playback, MIDI, and crash protection
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
//! Internal COM interface implementations for VST3

use std::collections::HashMap;
use std::ffi::CStr;
use std::ptr;
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use vst3::{Class, ComWrapper, Interface, Steinberg::Vst::*, Steinberg::*};

// Host Application implementation.
//
// Many plugins (u-he, Waves, ...) query the context passed to `IComponent::initialize`
// for `IHostApplication` and dereference it. Passing a null context makes them crash.
// Providing a real host-application object that at least answers `getName` lets them
// initialize. (We don't yet vend host-created objects like IMessage/IAttributeList.)
pub struct HostApplication;

impl Class for HostApplication {
    // The standard SDK host context implements both IHostApplication and
    // IPlugInterfaceSupport; plugins query the context for either.
    type Interfaces = (IHostApplication, IPlugInterfaceSupport);
}

impl IPlugInterfaceSupportTrait for HostApplication {
    unsafe fn isPlugInterfaceSupported(&self, iid: *const TUID) -> tresult {
        if iid.is_null() {
            return kResultFalse;
        }
        // Advertise the host-side interfaces we genuinely provide (the component handler
        // installed on the controller); decline the rest so plugins use their defaults.
        let bytes = std::slice::from_raw_parts(iid as *const u8, 16);
        if bytes == &IComponentHandler::IID[..] || bytes == &IComponentHandler2::IID[..] {
            kResultTrue
        } else {
            kResultFalse
        }
    }
}

impl IHostApplicationTrait for HostApplication {
    unsafe fn getName(&self, name: *mut String128) -> tresult {
        if name.is_null() {
            return kResultFalse;
        }
        let dst = &mut *name;
        let mut i = 0;
        for ch in "vst3-host".encode_utf16() {
            if i + 1 >= dst.len() {
                break;
            }
            dst[i] = ch;
            i += 1;
        }
        dst[i] = 0;
        kResultOk
    }

    unsafe fn createInstance(
        &self,
        cid: *mut TUID,
        _iid: *mut TUID,
        obj: *mut *mut std::ffi::c_void,
    ) -> tresult {
        // Vend the host-created objects plugins ask for (the SDK's HostApplication does
        // this): IMessage and IAttributeList, used to pass data between a plugin's
        // component and controller halves. Anything else fails cleanly.
        if obj.is_null() || cid.is_null() {
            return kResultFalse;
        }
        *obj = ptr::null_mut();

        // Compare the requested class id to a known IID by raw bytes (TUID element type
        // is platform-dependent, so avoid a typed array compare).
        let cid_bytes = std::slice::from_raw_parts(cid as *const u8, 16);
        let matches = |iid: &[u8; 16]| cid_bytes == &iid[..];

        if matches(&IMessage::IID) {
            if let Some(p) = create_host_message().to_com_ptr::<IMessage>() {
                *obj = p.into_raw() as *mut std::ffi::c_void;
                return kResultTrue;
            }
        } else if matches(&IAttributeList::IID) {
            if let Some(p) = create_host_attribute_list().to_com_ptr::<IAttributeList>() {
                *obj = p.into_raw() as *mut std::ffi::c_void;
                return kResultTrue;
            }
        }
        kResultFalse
    }
}

/// Create a host-application context to pass to `IComponent::initialize`.
pub fn create_host_application() -> ComWrapper<HostApplication> {
    ComWrapper::new(HostApplication)
}

// A host-side IAttributeList: a typed key/value bag plugins use (via the host's
// createInstance) to pass data between their component and controller halves.
#[derive(Debug, Clone, PartialEq)]
enum AttrValue {
    Int(i64),
    Float(f64),
    /// UTF-16 (TChar) string, not null-terminated.
    Str(Vec<u16>),
    Bin(Vec<u8>),
}

/// Host implementation of `IAttributeList`.
#[derive(Default)]
pub struct HostAttributeList {
    attrs: Mutex<HashMap<String, AttrValue>>,
}

impl HostAttributeList {
    pub fn new() -> Self {
        Self::default()
    }

    // Safe inner API (also the unit-test surface).
    fn put(&self, key: String, value: AttrValue) {
        if let Ok(mut m) = self.attrs.lock() {
            m.insert(key, value);
        }
    }
    fn get_value(&self, key: &str) -> Option<AttrValue> {
        self.attrs.lock().ok().and_then(|m| m.get(key).cloned())
    }
}

/// Decode an `AttrID` (a C string) into an owned key.
unsafe fn attr_key(id: *const std::os::raw::c_char) -> String {
    if id.is_null() {
        return String::new();
    }
    CStr::from_ptr(id).to_string_lossy().into_owned()
}

impl Class for HostAttributeList {
    type Interfaces = (IAttributeList,);
}

impl IAttributeListTrait for HostAttributeList {
    unsafe fn setInt(&self, id: *const std::os::raw::c_char, value: i64) -> tresult {
        self.put(attr_key(id), AttrValue::Int(value));
        kResultOk
    }
    unsafe fn getInt(&self, id: *const std::os::raw::c_char, value: *mut i64) -> tresult {
        match self.get_value(&attr_key(id)) {
            Some(AttrValue::Int(v)) if !value.is_null() => {
                *value = v;
                kResultOk
            }
            _ => kResultFalse,
        }
    }
    unsafe fn setFloat(&self, id: *const std::os::raw::c_char, value: f64) -> tresult {
        self.put(attr_key(id), AttrValue::Float(value));
        kResultOk
    }
    unsafe fn getFloat(&self, id: *const std::os::raw::c_char, value: *mut f64) -> tresult {
        match self.get_value(&attr_key(id)) {
            Some(AttrValue::Float(v)) if !value.is_null() => {
                *value = v;
                kResultOk
            }
            _ => kResultFalse,
        }
    }
    unsafe fn setString(&self, id: *const std::os::raw::c_char, string: *const u16) -> tresult {
        if string.is_null() {
            return kResultFalse;
        }
        let mut buf = Vec::new();
        let mut p = string;
        while *p != 0 {
            buf.push(*p);
            p = p.add(1);
        }
        self.put(attr_key(id), AttrValue::Str(buf));
        kResultOk
    }
    unsafe fn getString(
        &self,
        id: *const std::os::raw::c_char,
        string: *mut u16,
        size_in_bytes: u32,
    ) -> tresult {
        match self.get_value(&attr_key(id)) {
            Some(AttrValue::Str(v)) if !string.is_null() => {
                // Copy up to capacity-1 chars, then null-terminate.
                let cap_chars = (size_in_bytes as usize / 2).saturating_sub(1);
                let n = v.len().min(cap_chars);
                for (i, &ch) in v.iter().take(n).enumerate() {
                    *string.add(i) = ch;
                }
                *string.add(n) = 0;
                kResultOk
            }
            _ => kResultFalse,
        }
    }
    unsafe fn setBinary(
        &self,
        id: *const std::os::raw::c_char,
        data: *const std::ffi::c_void,
        size_in_bytes: u32,
    ) -> tresult {
        if data.is_null() {
            return kResultFalse;
        }
        let bytes = std::slice::from_raw_parts(data as *const u8, size_in_bytes as usize).to_vec();
        self.put(attr_key(id), AttrValue::Bin(bytes));
        kResultOk
    }
    unsafe fn getBinary(
        &self,
        id: *const std::os::raw::c_char,
        data: *mut *const std::ffi::c_void,
        size_in_bytes: *mut u32,
    ) -> tresult {
        // Note: returns a pointer into the stored buffer; valid until the entry is
        // replaced. VST3 plugins read it synchronously during init, which is safe here.
        if data.is_null() || size_in_bytes.is_null() {
            return kResultFalse;
        }
        if let Ok(m) = self.attrs.lock() {
            if let Some(AttrValue::Bin(v)) = m.get(&attr_key(id)) {
                *data = v.as_ptr() as *const std::ffi::c_void;
                *size_in_bytes = v.len() as u32;
                return kResultOk;
            }
        }
        kResultFalse
    }
}

/// Create a host attribute list.
pub fn create_host_attribute_list() -> ComWrapper<HostAttributeList> {
    ComWrapper::new(HostAttributeList::new())
}

/// Host implementation of `IMessage` (an id + an attribute list), used for
/// component<->controller communication that plugins allocate via the host.
pub struct HostMessage {
    id: Mutex<Option<std::ffi::CString>>,
    attributes: ComWrapper<HostAttributeList>,
}

impl Default for HostMessage {
    fn default() -> Self {
        Self {
            id: Mutex::new(None),
            attributes: create_host_attribute_list(),
        }
    }
}

impl HostMessage {
    pub fn new() -> Self {
        Self::default()
    }
}

impl Class for HostMessage {
    type Interfaces = (IMessage,);
}

impl IMessageTrait for HostMessage {
    unsafe fn getMessageID(&self) -> FIDString {
        // Pointer to the stored id (valid until replaced); null if unset.
        if let Ok(g) = self.id.lock() {
            if let Some(ref s) = *g {
                return s.as_ptr();
            }
        }
        ptr::null()
    }
    unsafe fn setMessageID(&self, id: FIDString) {
        if id.is_null() {
            return;
        }
        let owned = CStr::from_ptr(id).to_owned();
        if let Ok(mut g) = self.id.lock() {
            *g = Some(owned);
        }
    }
    unsafe fn getAttributes(&self) -> *mut IAttributeList {
        // Borrowed pointer to the message's own attribute list (kept alive by `self`).
        self.attributes
            .to_com_ptr::<IAttributeList>()
            .map(|p| p.as_ptr())
            .unwrap_or(ptr::null_mut())
    }
}

/// Create a host message.
pub fn create_host_message() -> ComWrapper<HostMessage> {
    ComWrapper::new(HostMessage::new())
}

// Host-side in-memory `IBStream`. Plugins serialize their state into a stream the host
// provides (`IComponent::getState`) and restore from one the host fills
// (`IComponent::setState`). This backs both with a growable byte buffer plus a cursor.
struct MemBuf {
    data: Vec<u8>,
    pos: usize,
}

/// Host implementation of `IBStream` over an in-memory buffer.
pub struct MemoryStream {
    inner: Mutex<MemBuf>,
}

impl MemoryStream {
    fn new(data: Vec<u8>) -> Self {
        Self {
            inner: Mutex::new(MemBuf { data, pos: 0 }),
        }
    }

    /// A copy of everything written to the stream (used after `getState`).
    pub fn to_vec(&self) -> Vec<u8> {
        self.inner
            .lock()
            .map(|b| b.data.clone())
            .unwrap_or_default()
    }

    // Safe inner ops — also the unit-test surface for the read/write/seek logic.
    fn write_at_cursor(&self, src: &[u8]) -> usize {
        if let Ok(mut b) = self.inner.lock() {
            let end = b.pos + src.len();
            if end > b.data.len() {
                b.data.resize(end, 0);
            }
            let pos = b.pos;
            b.data[pos..end].copy_from_slice(src);
            b.pos = end;
            src.len()
        } else {
            0
        }
    }

    fn read_at_cursor(&self, n: usize) -> Vec<u8> {
        if let Ok(mut b) = self.inner.lock() {
            let start = b.pos.min(b.data.len());
            let end = (start + n).min(b.data.len());
            let out = b.data[start..end].to_vec();
            b.pos = end;
            out
        } else {
            Vec::new()
        }
    }

    fn seek_to(&self, pos: i64, mode: u32) -> i64 {
        if let Ok(mut b) = self.inner.lock() {
            let base = match mode {
                SEEK_CUR => b.pos as i64,
                SEEK_END => b.data.len() as i64,
                _ => 0, // SEEK_SET
            };
            let new = (base + pos).max(0);
            b.pos = new as usize;
            new
        } else {
            0
        }
    }

    fn position(&self) -> i64 {
        self.inner.lock().map(|b| b.pos as i64).unwrap_or(0)
    }
}

// IBStream seek modes — fixed by the VST3 ABI. kIBSeekSet (0) is the `_` arm in seek_to.
const SEEK_CUR: u32 = 1; // kIBSeekCur
const SEEK_END: u32 = 2; // kIBSeekEnd

impl Class for MemoryStream {
    type Interfaces = (IBStream,);
}

impl IBStreamTrait for MemoryStream {
    unsafe fn read(
        &self,
        buffer: *mut std::ffi::c_void,
        num_bytes: i32,
        num_bytes_read: *mut i32,
    ) -> tresult {
        if buffer.is_null() || num_bytes < 0 {
            return kResultFalse;
        }
        let bytes = self.read_at_cursor(num_bytes as usize);
        ptr::copy_nonoverlapping(bytes.as_ptr(), buffer as *mut u8, bytes.len());
        if !num_bytes_read.is_null() {
            *num_bytes_read = bytes.len() as i32;
        }
        kResultOk
    }

    unsafe fn write(
        &self,
        buffer: *mut std::ffi::c_void,
        num_bytes: i32,
        num_bytes_written: *mut i32,
    ) -> tresult {
        if buffer.is_null() || num_bytes < 0 {
            return kResultFalse;
        }
        let src = std::slice::from_raw_parts(buffer as *const u8, num_bytes as usize);
        let written = self.write_at_cursor(src);
        if !num_bytes_written.is_null() {
            *num_bytes_written = written as i32;
        }
        kResultOk
    }

    unsafe fn seek(&self, pos: i64, mode: i32, result: *mut i64) -> tresult {
        let new = self.seek_to(pos, mode as u32);
        if !result.is_null() {
            *result = new;
        }
        kResultOk
    }

    unsafe fn tell(&self, pos: *mut i64) -> tresult {
        if pos.is_null() {
            return kResultFalse;
        }
        *pos = self.position();
        kResultOk
    }
}

/// Create an empty stream for the plugin to write its state into (`getState`).
pub fn create_memory_stream() -> ComWrapper<MemoryStream> {
    ComWrapper::new(MemoryStream::new(Vec::new()))
}

/// Create a stream seeded with bytes for the plugin to read its state from (`setState`).
pub fn create_memory_stream_from(data: Vec<u8>) -> ComWrapper<MemoryStream> {
    ComWrapper::new(MemoryStream::new(data))
}

// Host implementation of `IPlugFrame`. A plugin editor calls `resizeView` to ask the host
// to resize the window hosting its view. We record the requested size; the host polls it
// (take_editor_resize_request) and resizes its container on the UI thread.
pub struct HostPlugFrame {
    requested: Arc<Mutex<Option<(i32, i32)>>>,
}

impl HostPlugFrame {
    pub fn new(requested: Arc<Mutex<Option<(i32, i32)>>>) -> Self {
        Self { requested }
    }
}

impl Class for HostPlugFrame {
    type Interfaces = (IPlugFrame,);
}

impl IPlugFrameTrait for HostPlugFrame {
    unsafe fn resizeView(&self, _view: *mut IPlugView, new_size: *mut ViewRect) -> tresult {
        if new_size.is_null() {
            return kResultFalse;
        }
        let r = &*new_size;
        let (w, h) = (r.right - r.left, r.bottom - r.top);
        if let Ok(mut slot) = self.requested.lock() {
            *slot = Some((w, h));
        }
        // The host resizes its container to (w, h) from take_editor_resize_request on the
        // UI thread; acknowledging here is enough for the plugin to proceed.
        kResultOk
    }
}

/// Create a host plug-frame backed by a shared resize-request slot.
pub fn create_host_plug_frame(
    requested: Arc<Mutex<Option<(i32, i32)>>>,
) -> ComWrapper<HostPlugFrame> {
    ComWrapper::new(HostPlugFrame::new(requested))
}

// Component Handler implementation
pub struct ComponentHandler {
    // Track parameter changes from the plugin
    pub parameter_changes: Arc<Mutex<Vec<(u32, f64)>>>,
    // Ordered log of begin/change/end gestures the editor reports, preserving their order so
    // the host can reconstruct each gesture (drained via `take_parameter_edits`). This is the
    // richer superset of `parameter_changes` (which keeps only the value changes for the DSP).
    edits: Arc<Mutex<Vec<crate::plugin::ParameterEdit>>>,
}

impl ComponentHandler {
    pub fn new(parameter_changes: Arc<Mutex<Vec<(u32, f64)>>>) -> Self {
        ComponentHandler {
            parameter_changes,
            edits: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Drain the ordered parameter-edit gesture log accumulated since the last call.
    pub fn take_parameter_edits(&self) -> Vec<crate::plugin::ParameterEdit> {
        // A COM FFI callback could be mid-push when a previous one panicked; recover the lock
        // rather than propagating a poison panic across the boundary.
        let mut edits = self.edits.lock().unwrap_or_else(|p| p.into_inner());
        std::mem::take(&mut *edits)
    }

    // Append a gesture event, recovering a poisoned lock (these run on the COM FFI callback
    // path, where a panic would unwind across the C++ boundary — UB).
    fn push_edit(&self, edit: crate::plugin::ParameterEdit) {
        self.edits
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .push(edit);
    }
}

impl Class for ComponentHandler {
    type Interfaces = (IComponentHandler, IComponentHandler2);
}

impl IComponentHandlerTrait for ComponentHandler {
    unsafe fn beginEdit(&self, id: u32) -> i32 {
        log::debug!("Host: Begin edit for parameter {}", id);
        self.push_edit(crate::plugin::ParameterEdit {
            id,
            kind: crate::plugin::ParameterEditKind::BeginGesture,
            value: None,
        });
        kResultOk
    }

    unsafe fn performEdit(&self, id: u32, value_normalized: f64) -> i32 {
        log::debug!(
            "Host: Perform edit for parameter {} = {}",
            id,
            value_normalized
        );
        // Store the parameter change for the DSP-feeding drain...
        if let Ok(mut changes) = self.parameter_changes.lock() {
            changes.push((id, value_normalized));
        }
        // ...and as an ordered gesture event for the richer `take_parameter_edits` drain.
        self.push_edit(crate::plugin::ParameterEdit {
            id,
            kind: crate::plugin::ParameterEditKind::ValueChange,
            value: Some(value_normalized),
        });
        kResultOk
    }

    unsafe fn endEdit(&self, id: u32) -> i32 {
        log::debug!("Host: End edit for parameter {}", id);
        self.push_edit(crate::plugin::ParameterEdit {
            id,
            kind: crate::plugin::ParameterEditKind::EndGesture,
            value: None,
        });
        kResultOk
    }

    unsafe fn restartComponent(&self, flags: i32) -> i32 {
        log::debug!("Host: Restart component requested with flags: {}", flags);
        kResultOk
    }
}

impl IComponentHandler2Trait for ComponentHandler {
    unsafe fn setDirty(&self, _state: u8) -> i32 {
        log::debug!("Host: Plugin marked state as dirty (state: {})", _state);
        kResultOk
    }

    unsafe fn requestOpenEditor(&self, _name: *const std::os::raw::c_char) -> i32 {
        log::debug!("Host: Plugin requested editor open");
        kResultOk
    }

    unsafe fn startGroupEdit(&self) -> i32 {
        log::debug!("Host: Plugin started group edit");
        kResultOk
    }

    unsafe fn finishGroupEdit(&self) -> i32 {
        log::debug!("Host: Plugin finished group edit");
        kResultOk
    }
}

// Event List implementation
pub struct HostEventList {
    pub events: Mutex<Vec<Event>>,
}

impl HostEventList {
    pub fn new() -> Self {
        Self {
            events: Mutex::new(Vec::new()),
        }
    }

    pub fn clear(&self) {
        match self.events.lock() {
            Ok(mut events) => {
                events.clear();
                log::trace!("HostEventList: Cleared all events");
            }
            Err(_) => {
                log::error!("HostEventList: Failed to lock events for clear");
            }
        }
    }

    /// Clamp every queued event's `sampleOffset` into `[0, max_offset]`, so an event scheduled
    /// beyond a (possibly smaller-than-nominal) processed block lands at the block edge rather
    /// than past it. Called at the start of `process()` once the real frame count is known.
    pub fn clamp_offsets(&self, max_offset: i32) {
        if let Ok(mut events) = self.events.lock() {
            for e in events.iter_mut() {
                e.sampleOffset = e.sampleOffset.clamp(0, max_offset);
            }
        }
    }

    /// True if the list currently holds no events.
    pub fn is_empty(&self) -> bool {
        self.events
            .lock()
            .map(|events| events.is_empty())
            .unwrap_or(true)
    }

    /// Visit each event in order, then clear the list in place (retaining its capacity).
    /// The allocation-free equivalent of [`drain`](Self::drain) — `drain` returns an owned
    /// `Vec` via `mem::take`, leaving a zero-capacity buffer the plugin then reallocates; this
    /// keeps the buffer, so reading the plugin's per-block output events allocates nothing.
    pub fn for_each_then_clear(&self, mut f: impl FnMut(&Event)) {
        if let Ok(mut events) = self.events.lock() {
            for e in events.iter() {
                f(e);
            }
            events.clear();
        }
    }

    pub fn add_event(&self, event: Event) {
        match self.events.lock() {
            Ok(mut events) => {
                events.push(event);
                log::trace!(
                    "HostEventList: Added event via add_event, total count: {}",
                    events.len()
                );
            }
            Err(_) => {
                log::error!("HostEventList: Failed to lock events for add_event");
            }
        }
    }
}

impl Default for HostEventList {
    fn default() -> Self {
        Self::new()
    }
}

impl Class for HostEventList {
    type Interfaces = (IEventList,);
}

impl IEventListTrait for HostEventList {
    unsafe fn getEventCount(&self) -> i32 {
        match self.events.lock() {
            Ok(events) => events.len() as i32,
            Err(_) => {
                log::error!("HostEventList: Failed to lock events for getEventCount");
                0
            }
        }
    }

    unsafe fn getEvent(&self, index: i32, event: *mut Event) -> i32 {
        if event.is_null() {
            log::warn!("HostEventList: getEvent called with null event pointer");
            return kResultFalse;
        }

        if index < 0 {
            log::warn!(
                "HostEventList: getEvent called with negative index: {}",
                index
            );
            return kResultFalse;
        }

        match self.events.lock() {
            Ok(events) => {
                if let Some(e) = events.get(index as usize) {
                    *event = *e;
                    kResultOk
                } else {
                    log::warn!(
                        "HostEventList: getEvent index {} out of bounds (count: {})",
                        index,
                        events.len()
                    );
                    kResultFalse
                }
            }
            Err(_) => {
                log::error!("HostEventList: Failed to lock events for getEvent");
                kResultFalse
            }
        }
    }

    unsafe fn addEvent(&self, event: *mut Event) -> i32 {
        if event.is_null() {
            log::warn!("HostEventList: addEvent called with null event pointer");
            return kResultFalse;
        }

        match self.events.lock() {
            Ok(mut events) => {
                events.push(*event);
                log::trace!("HostEventList: Added event, total count: {}", events.len());
                kResultOk
            }
            Err(_) => {
                log::error!("HostEventList: Failed to lock events for addEvent");
                kResultFalse
            }
        }
    }
}

pub fn create_event_list() -> ComWrapper<HostEventList> {
    ComWrapper::new(HostEventList::new())
}

// Parameter Changes implementation
pub struct ParameterChanges {
    /// A pool of queue objects. Entries `[0, used)` are active this block; entries `[used, len)`
    /// are recycled — kept allocated and reused across blocks rather than dropped, so the
    /// steady-state audio path never allocates a `ComWrapper`. The pool only ever grows, bounded
    /// by the number of distinct parameters changed within a single block.
    pub queues: Mutex<Vec<ComWrapper<ParameterValueQueue>>>,
    /// Number of active queues this block (`<= queues.len()`). Mutated only under the `queues`
    /// lock, so the pair stays consistent.
    used: AtomicUsize,
}

impl Default for ParameterChanges {
    fn default() -> Self {
        Self {
            queues: Mutex::new(Vec::new()),
            used: AtomicUsize::new(0),
        }
    }
}

impl ParameterChanges {
    /// Host-side: queue a parameter change point for the next process block. The processor
    /// reads these from `inputParameterChanges` during `process()`. Points for the same id
    /// share one queue and are kept ordered by sample offset. Reuses a pooled queue object
    /// rather than allocating, so this is allocation-free in steady state once the pool has
    /// grown to the per-block working set.
    pub fn enqueue(&self, id: u32, sample_offset: i32, value: f64) {
        if let Ok(mut queues) = self.queues.lock() {
            let used = self.used.load(Ordering::Relaxed);
            // Merge into an already-active queue for this id (e.g. several offsets in one block).
            if let Some(q) = queues[..used].iter().find(|q| q.param_id() == id) {
                q.insert_point(sample_offset, value);
                return;
            }
            // Otherwise activate a slot: recycle a pooled queue if one exists, else grow once.
            if used < queues.len() {
                queues[used].reset(id);
                queues[used].insert_point(sample_offset, value);
            } else {
                let q = ComWrapper::new(ParameterValueQueue::new(id));
                q.insert_point(sample_offset, value);
                queues.push(q);
            }
            self.used.store(used + 1, Ordering::Relaxed);
        }
    }

    /// Forget all queued changes. Call after each `process()` block so values don't re-stick.
    /// Only resets the active count — the queue objects are retained for reuse (their points are
    /// cleared when a slot is recycled), so this allocates and drops nothing.
    pub fn clear_all(&self) {
        self.used.store(0, Ordering::Relaxed);
    }
}

impl Class for ParameterChanges {
    type Interfaces = (IParameterChanges,);
}

impl IParameterChangesTrait for ParameterChanges {
    unsafe fn getParameterCount(&self) -> i32 {
        match self.queues.lock() {
            Ok(_queues) => {
                // Only the active slots, not the recycled pool capacity.
                let count = self.used.load(Ordering::Relaxed) as i32;
                log::trace!(
                    "Internal ParameterChanges: getParameterCount returning {}",
                    count
                );
                count
            }
            Err(_) => {
                log::error!(
                    "Internal ParameterChanges: Failed to lock queues for getParameterCount"
                );
                0
            }
        }
    }

    unsafe fn getParameterData(&self, index: i32) -> *mut IParamValueQueue {
        if index < 0 {
            log::warn!(
                "Internal ParameterChanges: getParameterData called with negative index: {}",
                index
            );
            return ptr::null_mut();
        }

        match self.queues.lock() {
            Ok(queues) => {
                let used = self.used.load(Ordering::Relaxed);
                if (index as usize) < used {
                    let queue = &queues[index as usize];
                    match queue.as_com_ref::<IParamValueQueue>() {
                        Some(ptr) => {
                            log::trace!("Internal ParameterChanges: getParameterData returning queue for index {}", index);
                            ptr.as_ptr()
                        }
                        None => {
                            log::error!("Internal ParameterChanges: Failed to convert queue to COM pointer for index {}", index);
                            ptr::null_mut()
                        }
                    }
                } else {
                    log::warn!("Internal ParameterChanges: getParameterData index {} out of bounds (count: {})", index, used);
                    ptr::null_mut()
                }
            }
            Err(_) => {
                log::error!(
                    "Internal ParameterChanges: Failed to lock queues for getParameterData"
                );
                ptr::null_mut()
            }
        }
    }

    unsafe fn addParameterData(&self, id: *const u32, index: *mut i32) -> *mut IParamValueQueue {
        if id.is_null() {
            log::warn!("Internal ParameterChanges: addParameterData called with null id pointer");
            return ptr::null_mut();
        }

        let param_id = *id;

        match self.queues.lock() {
            Ok(mut queues) => {
                let used = self.used.load(Ordering::Relaxed);
                // Reuse an already-active queue for this parameter if present.
                for (i, queue) in queues[..used].iter().enumerate() {
                    if queue.param_id() == param_id {
                        if !index.is_null() {
                            *index = i as i32;
                        }
                        log::trace!(
                            "Internal ParameterChanges: Found existing queue for parameter {}",
                            param_id
                        );
                        return queue
                            .as_com_ref::<IParamValueQueue>()
                            .map(|ptr| ptr.as_ptr())
                            .unwrap_or_else(|| {
                                log::error!("Internal ParameterChanges: Failed to convert existing queue to COM pointer");
                                ptr::null_mut()
                            });
                    }
                }

                // Activate a slot: recycle a pooled queue if one exists, else grow once.
                if used == queues.len() {
                    queues.push(ComWrapper::new(ParameterValueQueue::new(param_id)));
                } else {
                    queues[used].reset(param_id);
                }
                let queue_ptr = queues[used]
                    .as_com_ref::<IParamValueQueue>()
                    .map(|ptr| ptr.as_ptr())
                    .unwrap_or_else(|| {
                        log::error!(
                            "Internal ParameterChanges: Failed to convert new queue to COM pointer"
                        );
                        ptr::null_mut()
                    });

                if !index.is_null() {
                    *index = used as i32;
                }

                self.used.store(used + 1, Ordering::Relaxed);
                log::trace!(
                    "Internal ParameterChanges: Activated queue for parameter {}, active count: {}",
                    param_id,
                    used + 1
                );
                queue_ptr
            }
            Err(_) => {
                log::error!(
                    "Internal ParameterChanges: Failed to lock queues for addParameterData"
                );
                ptr::null_mut()
            }
        }
    }
}

// Parameter Value Queue implementation
pub struct ParameterValueQueue {
    // Atomic so a pooled queue can be re-targeted to a different parameter (see `reset`) without
    // dropping and reallocating the ComWrapper each block.
    pub param_id: AtomicU32,
    pub points: Mutex<Vec<(i32, f64)>>, // sample offset, value
}

impl ParameterValueQueue {
    pub fn new(param_id: u32) -> Self {
        Self {
            param_id: AtomicU32::new(param_id),
            points: Mutex::new(Vec::new()),
        }
    }

    /// This queue's current parameter id.
    pub fn param_id(&self) -> u32 {
        self.param_id.load(Ordering::Relaxed)
    }

    /// Re-target a pooled queue to a new parameter, clearing its points in place (keeping the
    /// `points` Vec's capacity). Used when recycling a queue object for a different parameter so
    /// the steady-state path allocates nothing.
    fn reset(&self, param_id: u32) {
        self.param_id.store(param_id, Ordering::Relaxed);
        if let Ok(mut points) = self.points.lock() {
            points.clear();
        }
    }

    /// Insert a point keeping sample-offset order (safe host-side population, mirroring the
    /// COM `addPoint`).
    fn insert_point(&self, sample_offset: i32, value: f64) {
        if let Ok(mut points) = self.points.lock() {
            let pos = points
                .iter()
                .position(|(off, _)| *off > sample_offset)
                .unwrap_or(points.len());
            points.insert(pos, (sample_offset, value));
        }
    }
}

impl Class for ParameterValueQueue {
    type Interfaces = (IParamValueQueue,);
}

impl IParamValueQueueTrait for ParameterValueQueue {
    unsafe fn getParameterId(&self) -> u32 {
        self.param_id.load(Ordering::Relaxed)
    }

    unsafe fn getPointCount(&self) -> i32 {
        // These run as COM FFI callbacks; a panic (e.g. from `.unwrap()` on a poisoned
        // lock) would unwind across the C++ boundary — UB. Recover the lock instead.
        self.points.lock().unwrap_or_else(|p| p.into_inner()).len() as i32
    }

    unsafe fn getPoint(&self, index: i32, sample_offset: *mut i32, value: *mut f64) -> i32 {
        if let Some((offset, val)) = self
            .points
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .get(index as usize)
        {
            if !sample_offset.is_null() {
                *sample_offset = *offset;
            }
            if !value.is_null() {
                *value = *val;
            }
            kResultOk
        } else {
            kResultFalse
        }
    }

    unsafe fn addPoint(&self, sample_offset: i32, value: f64, index: *mut i32) -> i32 {
        let mut points = self.points.lock().unwrap_or_else(|p| p.into_inner());

        // Find insertion point
        let insert_pos = points
            .iter()
            .position(|(offset, _)| *offset > sample_offset)
            .unwrap_or(points.len());

        points.insert(insert_pos, (sample_offset, value));

        if !index.is_null() {
            *index = insert_pos as i32;
        }

        kResultOk
    }
}

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

    #[test]
    fn attribute_list_round_trips_each_type() {
        let list = HostAttributeList::new();
        list.put("i".into(), AttrValue::Int(42));
        list.put("f".into(), AttrValue::Float(1.5));
        list.put("s".into(), AttrValue::Str(vec![72, 105])); // "Hi"
        list.put("b".into(), AttrValue::Bin(vec![1, 2, 3]));

        assert_eq!(list.get_value("i"), Some(AttrValue::Int(42)));
        assert_eq!(list.get_value("f"), Some(AttrValue::Float(1.5)));
        assert_eq!(list.get_value("s"), Some(AttrValue::Str(vec![72, 105])));
        assert_eq!(list.get_value("b"), Some(AttrValue::Bin(vec![1, 2, 3])));
        assert_eq!(list.get_value("missing"), None);
    }
}

#[cfg(test)]
mod component_handler_tests {
    use super::*;
    use crate::plugin::{ParameterEdit, ParameterEditKind};

    #[test]
    fn captures_begin_perform_end_in_order_and_drains() {
        let handler = ComponentHandler::new(Arc::new(Mutex::new(Vec::new())));

        // Drive a full gesture: mouse-down, two drag values, mouse-up.
        unsafe {
            handler.beginEdit(5);
            handler.performEdit(5, 0.25);
            handler.performEdit(5, 0.5);
            handler.endEdit(5);
        }

        let edits = handler.take_parameter_edits();
        assert_eq!(
            edits,
            vec![
                ParameterEdit {
                    id: 5,
                    kind: ParameterEditKind::BeginGesture,
                    value: None,
                },
                ParameterEdit {
                    id: 5,
                    kind: ParameterEditKind::ValueChange,
                    value: Some(0.25),
                },
                ParameterEdit {
                    id: 5,
                    kind: ParameterEditKind::ValueChange,
                    value: Some(0.5),
                },
                ParameterEdit {
                    id: 5,
                    kind: ParameterEditKind::EndGesture,
                    value: None,
                },
            ]
        );

        // The drain empties the buffer; the value-change sink still mirrors the performEdits.
        assert!(handler.take_parameter_edits().is_empty());
        assert_eq!(
            *handler.parameter_changes.lock().unwrap(),
            vec![(5, 0.25), (5, 0.5)]
        );
    }
}

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

    #[test]
    fn records_requested_size_from_view_rect() {
        let slot = Arc::new(Mutex::new(None));
        let frame = HostPlugFrame::new(slot.clone());
        let mut rect = ViewRect {
            left: 0,
            top: 0,
            right: 640,
            bottom: 480,
        };
        let r = unsafe { frame.resizeView(std::ptr::null_mut(), &mut rect) };
        assert_eq!(r, kResultOk);
        assert_eq!(*slot.lock().unwrap(), Some((640, 480)));

        // Null size is rejected and leaves the slot unchanged.
        let r = unsafe { frame.resizeView(std::ptr::null_mut(), std::ptr::null_mut()) };
        assert_eq!(r, kResultFalse);
        assert_eq!(*slot.lock().unwrap(), Some((640, 480)));
    }
}

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

    #[test]
    fn enqueue_groups_by_id_orders_by_offset_and_clears() {
        let pc = ParameterChanges::default();
        pc.enqueue(7, 64, 0.9);
        pc.enqueue(7, 0, 0.5); // earlier offset, same id → must sort before the 64 point
        pc.enqueue(3, 0, 0.1);

        // Two distinct parameter ids → two queues; the processor reads this count.
        assert_eq!(unsafe { pc.getParameterCount() }, 2);
        {
            let queues = pc.queues.lock().unwrap();
            let q7 = queues.iter().find(|q| q.param_id() == 7).unwrap();
            assert_eq!(*q7.points.lock().unwrap(), vec![(0, 0.5), (64, 0.9)]);
            let q3 = queues.iter().find(|q| q.param_id() == 3).unwrap();
            assert_eq!(*q3.points.lock().unwrap(), vec![(0, 0.1)]);
        }

        // After a block the host clears it so values don't re-stick.
        pc.clear_all();
        assert_eq!(unsafe { pc.getParameterCount() }, 0);
    }

    #[test]
    fn enqueue_with_nan_value_orders_by_offset_without_panicking() {
        // The queue is ordered by `sample_offset` (an i32 — total order), never by the f64
        // value, so a NaN value can never reach a comparator and can never panic or corrupt
        // ordering. This pins that property: the points sort by offset and the NaN survives
        // verbatim in its offset slot.
        let pc = ParameterChanges::default();
        pc.enqueue(1, 128, f64::NAN);
        pc.enqueue(1, 0, 0.25);
        pc.enqueue(1, 64, f64::NAN);

        let queues = pc.queues.lock().unwrap();
        let q = queues.iter().find(|q| q.param_id() == 1).unwrap();
        let points = q.points.lock().unwrap();
        let offsets: Vec<i32> = points.iter().map(|(off, _)| *off).collect();
        assert_eq!(offsets, vec![0, 64, 128]);
        // The finite point is intact and the two NaN-valued points are still NaN.
        assert_eq!(points[0].1, 0.25);
        assert!(points[1].1.is_nan());
        assert!(points[2].1.is_nan());
    }
}

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

    #[test]
    fn write_then_read_round_trips_from_start() {
        let s = MemoryStream::new(Vec::new());
        assert_eq!(s.write_at_cursor(&[1, 2, 3, 4]), 4);
        assert_eq!(s.position(), 4);
        assert_eq!(s.to_vec(), vec![1, 2, 3, 4]);

        // Rewind (mode 0 = SEEK_SET) and read it all back.
        assert_eq!(s.seek_to(0, 0), 0);
        assert_eq!(s.read_at_cursor(4), vec![1, 2, 3, 4]);
    }

    #[test]
    fn read_past_end_is_clamped() {
        let s = MemoryStream::new(vec![9, 8]);
        assert_eq!(s.read_at_cursor(10), vec![9, 8]);
        // Cursor now at end; further reads yield nothing.
        assert_eq!(s.read_at_cursor(10), Vec::<u8>::new());
    }

    #[test]
    fn seek_modes_and_overwrite() {
        let s = MemoryStream::new(vec![0, 0, 0, 0]);
        // SEEK_END then write appends.
        assert_eq!(s.seek_to(0, SEEK_END), 4);
        s.write_at_cursor(&[5]);
        assert_eq!(s.to_vec(), vec![0, 0, 0, 0, 5]);
        // SEEK_SET to 1 then overwrite in place.
        assert_eq!(s.seek_to(1, 0), 1);
        s.write_at_cursor(&[7, 7]);
        assert_eq!(s.to_vec(), vec![0, 7, 7, 0, 5]);
        // SEEK_CUR is relative.
        assert_eq!(s.seek_to(-3, SEEK_CUR), 0);
    }
}