vst3-host 0.6.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
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
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
//! VST3 plugin wrapper with safe API

use crate::{
    audio::{AudioBuffers, AudioLevels},
    error::{Error, Result},
    midi::{MidiChannel, MidiEvent},
    parameters::{Parameter, ParameterUpdate},
};
use crossbeam_queue::ArrayQueue;
use std::sync::{Arc, Mutex};

/// A `Send` + `Sync` handle for draining the MIDI a plugin emits (arpeggiators, MPE, MIDI
/// thru, …) without locking the audio thread.
///
/// Obtain one from [`Plugin::output_midi_handle`]. The plugin's audio thread pushes emitted
/// events into a lock-free bounded queue; this handle pops them from any other thread (e.g. a
/// UI poll loop) with no lock on either side — the lock-free counterpart to the audio-thread
/// drain in [`Plugin::take_output_midi`]. When the queue is full the oldest event is dropped,
/// so a host that stops polling can't grow it without bound.
///
/// Available for in-process plugins; the process-isolation path returns `None` (output MIDI
/// crosses the boundary in the IPC responses instead).
#[derive(Clone)]
pub struct OutputMidiConsumer {
    queue: Arc<ArrayQueue<MidiEvent>>,
}

impl OutputMidiConsumer {
    pub(crate) fn from_queue(queue: Arc<ArrayQueue<MidiEvent>>) -> Self {
        Self { queue }
    }

    /// Pop the oldest emitted event, or `None` if none are queued. Lock-free.
    pub fn pop(&self) -> Option<MidiEvent> {
        self.queue.pop()
    }

    /// Drain all currently queued events in emission order into a `Vec`. Lock-free pops; the
    /// returned `Vec` allocates on the calling thread (intended for a UI/control thread, not
    /// the audio thread — use [`pop`](Self::pop) in a loop to stay allocation-free).
    pub fn drain(&self) -> Vec<MidiEvent> {
        let mut out = Vec::new();
        while let Some(event) = self.queue.pop() {
            out.push(event);
        }
        out
    }
}

/// Information about a VST3 plugin
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PluginInfo {
    /// Full path to the VST3 bundle/file
    pub path: std::path::PathBuf,
    /// Plugin name
    pub name: String,
    /// Vendor/manufacturer name
    pub vendor: String,
    /// Plugin version
    pub version: String,
    /// Plugin category (e.g., "Fx", "Instrument")
    pub category: String,
    /// Unique plugin ID
    pub uid: String,
    /// Number of audio input buses
    pub audio_inputs: u32,
    /// Number of audio output buses
    pub audio_outputs: u32,
    /// Whether the plugin accepts MIDI input
    pub has_midi_input: bool,
    /// Whether the plugin produces MIDI output
    pub has_midi_output: bool,
    /// Whether the plugin has a GUI
    pub has_gui: bool,
}

/// A saved plugin preset: the plugin's identity plus its opaque state blob.
///
/// Written/read by [`Plugin::save_preset`] / [`Plugin::load_preset`]. The `uid` lets a
/// loader reject a preset that belongs to a different plugin (whose state bytes would be
/// meaningless or harmful).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PluginPreset {
    /// The originating plugin's unique class id ([`PluginInfo::uid`]).
    pub uid: String,
    /// The originating plugin's display name (for friendly mismatch messages).
    pub plugin_name: String,
    /// The plugin's opaque serialized state (from [`Plugin::save_state`]).
    pub state: Vec<u8>,
}

/// A plugin unit (from `IUnitInfo`) and its program list, if any.
///
/// Units form a hierarchy (via [`parent_id`](Self::parent_id)); a unit may carry a named
/// program list (e.g. a synth's factory patches). Query with [`Plugin::get_units`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PluginUnit {
    /// Unit id (unique within the plugin; the root unit is conventionally `0`).
    pub id: i32,
    /// Parent unit id, or `-1` for the root.
    pub parent_id: i32,
    /// Unit display name.
    pub name: String,
    /// Program names in this unit's program list (empty if the unit has none).
    pub programs: Vec<String>,
}

/// What kind of parameter-edit gesture event a plugin's editor reported.
///
/// VST3 editors bracket a user gesture with `beginEdit`/`endEdit` (e.g. mouse-down /
/// mouse-up on a knob) and report the values in between with `performEdit`. Capturing the
/// brackets — not just the value changes — lets a host distinguish a deliberate, completed
/// edit from intermediate drag values, coalesce automation into one undo step, or know when a
/// gesture is in progress.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ParameterEditKind {
    /// The user started editing this parameter (`IComponentHandler::beginEdit`).
    BeginGesture,
    /// The parameter's value changed (`IComponentHandler::performEdit`); carries the new
    /// normalized value in [`ParameterEdit::value`].
    ValueChange,
    /// The user finished editing this parameter (`IComponentHandler::endEdit`).
    EndGesture,
}

/// A single parameter-edit gesture event reported by a plugin's own editor.
///
/// Drained in order via [`Plugin::take_parameter_edits`]. This is the richer superset of
/// [`Plugin::get_parameter_changes`]: where that drains only the value changes, this preserves
/// the begin/change/end ordering so a host can reconstruct each gesture.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ParameterEdit {
    /// Parameter id the gesture targets.
    pub id: u32,
    /// Which gesture phase this event is.
    pub kind: ParameterEditKind,
    /// The new normalized value (`0.0..=1.0`), present only for
    /// [`ParameterEditKind::ValueChange`]; `None` for begin/end brackets.
    pub value: Option<f64>,
}

/// How the plugin should run: real-time (live playback) or offline (faster-than-real-time
/// bounce/render). Maps to VST3 `kRealtime` / `kOffline`; plugins may switch quality or
/// look-ahead accordingly. Defaults to [`ProcessMode::Realtime`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum ProcessMode {
    /// Real-time / live processing (the default; `kRealtime`).
    #[default]
    Realtime,
    /// Offline / non-real-time processing such as a render or bounce (`kOffline`).
    Offline,
}

/// VST3 plugin instance
#[allow(clippy::type_complexity)] // callback fields are Box<dyn Fn...>; intrinsic to the API
pub struct Plugin {
    // Internal state is hidden from public API
    pub(crate) info: PluginInfo,
    pub(crate) is_processing: bool,
    /// Configured sample rate (exposed via [`Plugin::sample_rate`]).
    pub(crate) sample_rate: f64,
    /// Configured max block size (exposed via [`Plugin::block_size`]).
    pub(crate) block_size: usize,
    pub(crate) audio_levels: Arc<Mutex<AudioLevels>>,
    pub(crate) parameter_change_callback: Option<Box<dyn Fn(u32, f64) + Send + 'static>>,
    pub(crate) audio_callback: Option<Box<dyn Fn(&AudioLevels) + Send + 'static>>,

    // These will be populated by the actual implementation
    pub(crate) internal: Option<Box<dyn PluginInternal>>,
}

// Internal trait for hiding implementation details
pub(crate) trait PluginInternal: Send {
    fn set_parameter(&mut self, id: u32, value: f64) -> Result<()>;
    /// Schedule a parameter change at a sample offset within the next process block.
    /// Defaults to a block-start change (ignores the offset) for implementations that don't
    /// support sample-accurate scheduling (e.g. process isolation).
    fn set_parameter_at(&mut self, id: u32, value: f64, _sample_offset: i32) -> Result<()> {
        self.set_parameter(id, value)
    }
    fn get_parameter(&self, id: u32) -> Result<f64>;
    fn get_all_parameters(&self) -> Result<Vec<Parameter>>;
    fn format_parameter(&self, id: u32, normalized: f64) -> Result<String>;
    fn process(&mut self, buffers: &mut AudioBuffers) -> Result<()>;
    /// Re-run `setupProcessing` for a new sample rate / block size. Defaults to unsupported
    /// (e.g. process isolation, where reconfigure isn't marshalled across the boundary).
    fn reconfigure(&mut self, _sample_rate: f64, _block_size: usize) -> Result<()> {
        Err(Error::Other(
            "runtime reconfigure is not supported for this plugin".to_string(),
        ))
    }
    /// Switch the plugin's process mode (real-time vs offline), re-running `setupProcessing`.
    /// Defaults to unsupported (e.g. process isolation, where it isn't marshalled).
    fn set_process_mode(&mut self, _mode: crate::plugin::ProcessMode) -> Result<()> {
        Err(Error::Other(
            "process mode switching is not supported for this plugin".to_string(),
        ))
    }
    /// Query each audio bus's current speaker arrangement. Defaults to unsupported.
    fn bus_arrangements(&self) -> Result<crate::audio::BusArrangements> {
        Err(Error::Other(
            "bus arrangement query is not supported for this plugin".to_string(),
        ))
    }
    /// Request specific speaker arrangements for the audio buses (re-runs `setupProcessing`).
    /// Defaults to unsupported (e.g. process isolation, where it isn't marshalled).
    fn set_bus_arrangements(
        &mut self,
        _inputs: &[crate::audio::SpeakerArrangement],
        _outputs: &[crate::audio::SpeakerArrangement],
    ) -> Result<()> {
        Err(Error::Other(
            "bus arrangement negotiation is not supported for this plugin".to_string(),
        ))
    }
    /// Activate or deactivate a single bus (`IComponent::activateBus`). Defaults to
    /// unsupported.
    fn set_bus_active(
        &mut self,
        _media_type: crate::audio::MediaType,
        _direction: crate::audio::BusDirection,
        _bus_index: i32,
        _active: bool,
    ) -> Result<()> {
        Err(Error::Other(
            "bus activation is not supported for this plugin".to_string(),
        ))
    }
    /// Update the transport tempo (BPM) advertised in the host `ProcessContext`, taking effect
    /// on the next processed block. The caller validates `bpm > 0`. Defaults to unsupported
    /// (overridden by the in-process and isolated implementations).
    fn set_tempo(&mut self, _bpm: f64) -> Result<()> {
        Err(Error::Other(
            "runtime transport mutation is not supported for this plugin".to_string(),
        ))
    }
    /// Update the transport time signature advertised in the host `ProcessContext`, taking
    /// effect on the next processed block. The caller validates the numerator/denominator.
    /// Defaults to unsupported.
    fn set_time_signature(&mut self, _numerator: i32, _denominator: i32) -> Result<()> {
        Err(Error::Other(
            "runtime transport mutation is not supported for this plugin".to_string(),
        ))
    }
    /// Toggle the transport playing state (`kPlaying`) in the host `ProcessContext`, taking
    /// effect on the next processed block. Defaults to unsupported.
    fn set_playing(&mut self, _playing: bool) -> Result<()> {
        Err(Error::Other(
            "runtime transport mutation is not supported for this plugin".to_string(),
        ))
    }
    fn send_midi_event(&mut self, event: MidiEvent) -> Result<()>;
    /// Schedule a MIDI event at a sample offset within the next process block.
    /// Defaults to a block-start event (ignores the offset) for implementations that don't
    /// support sample-accurate scheduling (e.g. process isolation).
    fn send_midi_event_at(&mut self, event: MidiEvent, _sample_offset: i32) -> Result<()> {
        self.send_midi_event(event)
    }
    /// Start a note and return a per-voice [`NoteId`] for targeting note-expression. Default:
    /// unsupported (process isolation does not yet marshal note expression, so it errors).
    fn note_on(
        &mut self,
        _channel: MidiChannel,
        _note: u8,
        _velocity: u8,
        _sample_offset: i32,
    ) -> Result<crate::midi::NoteId> {
        Err(Error::Other(
            "per-note expression is not supported for this plugin".to_string(),
        ))
    }
    /// Release a note started with [`Self::note_on`]. Default: unsupported.
    fn note_off(&mut self, _id: crate::midi::NoteId, _sample_offset: i32) -> Result<()> {
        Err(Error::Other(
            "per-note expression is not supported for this plugin".to_string(),
        ))
    }
    /// Send a per-note expression value (normalized 0..1) for a voice. Default: unsupported.
    fn send_note_expression(
        &mut self,
        _id: crate::midi::NoteId,
        _kind: crate::midi::NoteExpressionType,
        _value: f64,
        _sample_offset: i32,
    ) -> Result<()> {
        Err(Error::Other(
            "per-note expression is not supported for this plugin".to_string(),
        ))
    }
    /// Enumerate the per-note expressions the plugin advertises (`INoteExpressionController`).
    /// Defaults to empty.
    fn note_expressions(
        &self,
        _bus: i32,
        _channel: i16,
    ) -> Result<Vec<crate::midi::NoteExpressionInfo>> {
        Ok(Vec::new())
    }
    fn start_processing(&mut self) -> Result<()>;
    fn stop_processing(&mut self) -> Result<()>;
    fn has_editor(&self) -> bool;
    fn open_editor(&mut self, parent: *mut std::ffi::c_void) -> Result<()>;
    fn close_editor(&mut self) -> Result<()>;
    fn get_editor_size(&self) -> Result<(i32, i32)>;
    fn get_parameter_changes(&self) -> Vec<(u32, f64)>;
    /// Drain the ordered parameter-edit gesture log (begin/change/end) the plugin's editor
    /// reported since the last call. Defaults to empty for implementations that don't capture
    /// gestures.
    fn take_parameter_edits(&mut self) -> Vec<ParameterEdit> {
        Vec::new()
    }
    /// Take the MIDI events the plugin has emitted since the last call. Defaults to empty
    /// for implementations that don't capture output MIDI (e.g. process isolation).
    fn take_output_events(&self) -> Vec<MidiEvent> {
        Vec::new()
    }
    /// A lock-free handle for draining emitted MIDI from another thread. Defaults to `None`
    /// for implementations without a shared in-process queue (e.g. process isolation).
    fn output_midi_handle(&self) -> Option<OutputMidiConsumer> {
        None
    }
    /// Enumerate the plugin's units and their program lists (`IUnitInfo`). Defaults to empty
    /// for implementations that don't query it yet (e.g. process isolation).
    fn get_units(&self) -> Result<Vec<PluginUnit>> {
        Ok(Vec::new())
    }
    /// Select a program in a unit's program list. Defaults to unsupported (e.g. plugins
    /// without `IUnitInfo`); implementations resolve the unit's program-change parameter and
    /// set it to the index's normalized value.
    fn select_program(&mut self, _unit_id: i32, _program_index: i32) -> Result<()> {
        Err(Error::Other(
            "program selection is not supported for this plugin".to_string(),
        ))
    }
    /// Processing latency in samples (`IAudioProcessor::getLatencySamples`). Defaults to 0.
    fn latency_samples(&self) -> u32 {
        0
    }
    /// Tail length in samples (`IAudioProcessor::getTailSamples`). Defaults to 0.
    fn tail_samples(&self) -> u32 {
        0
    }
    /// Resolve a MIDI controller `(bus, channel, cc)` to a parameter id via `IMidiMapping`.
    /// Defaults to `None` (plugin doesn't implement the interface, or no mapping / isolation).
    fn midi_cc_to_parameter(&self, _bus: i32, _channel: i16, _cc: u16) -> Option<u32> {
        None
    }
    /// Serialize the plugin's current state to an opaque byte blob.
    fn save_state(&self) -> Result<Vec<u8>> {
        Err(Error::Other(
            "state save/restore is not supported".to_string(),
        ))
    }
    /// Restore the plugin's state from a blob previously returned by [`Self::save_state`].
    fn load_state(&mut self, _data: &[u8]) -> Result<()> {
        Err(Error::Other(
            "state save/restore is not supported".to_string(),
        ))
    }
    /// OS process id of the isolated helper, if this plugin runs out-of-process.
    fn helper_pid(&self) -> Option<u32> {
        None
    }
    /// Number of times this plugin has been recovered (respawned + reloaded). Defaults to 0
    /// for non-isolated plugins.
    fn recovery_count(&self) -> u64 {
        0
    }
    /// Recover from a crashed isolated helper by respawning and reloading. Only meaningful
    /// for process-isolated plugins.
    fn recover(&mut self) -> Result<()> {
        Err(Error::Other(
            "recovery is only supported for process-isolated plugins".to_string(),
        ))
    }
    /// The size the plugin's editor has requested (via `IPlugFrame`) since the last poll.
    fn take_editor_resize_request(&self) -> Option<(i32, i32)> {
        None
    }
    /// Total output audio channels across the plugin's output buses. Defaults to 2.
    fn output_channel_count(&self) -> usize {
        2
    }
}

impl Plugin {
    /// Get plugin information
    pub fn info(&self) -> &PluginInfo {
        &self.info
    }

    /// The sample rate (Hz) this plugin was configured with at load.
    pub fn sample_rate(&self) -> f64 {
        self.sample_rate
    }

    /// The maximum block size (frames per `process_audio` call) configured at load.
    pub fn block_size(&self) -> usize {
        self.block_size
    }

    /// Reconfigure the plugin for a new sample rate and/or maximum block size, re-running the
    /// plugin's `setupProcessing` and rebuilding its audio buffers.
    ///
    /// Use this when the audio device's sample rate changes mid-session instead of reloading.
    /// The plugin must **not** be processing: call [`Self::stop_processing`] first, reconfigure,
    /// then [`Self::start_processing`] again. Returns an error if called while processing, on an
    /// invalid sample rate / zero block size, or under process isolation (not yet marshalled).
    pub fn reconfigure(&mut self, sample_rate: f64, block_size: usize) -> Result<()> {
        if self.is_processing {
            return Err(Error::Other(
                "cannot reconfigure while processing; call stop_processing() first".to_string(),
            ));
        }
        if !(sample_rate.is_finite() && sample_rate > 0.0) {
            return Err(Error::InvalidParameter(format!(
                "sample rate must be finite and positive, got {sample_rate}"
            )));
        }
        if block_size == 0 {
            return Err(Error::InvalidParameter(
                "block size must be greater than 0".to_string(),
            ));
        }

        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .reconfigure(sample_rate, block_size)?;

        self.sample_rate = sample_rate;
        self.block_size = block_size;
        Ok(())
    }

    /// Switch the plugin between real-time and offline processing, re-running the plugin's
    /// `setupProcessing` so it can adjust quality / look-ahead for a faster-than-real-time
    /// bounce.
    ///
    /// Like [`Self::reconfigure`], the plugin must **not** be processing: call
    /// [`Self::stop_processing`] first. Returns an error if called while processing, or under
    /// process isolation (not marshalled across the boundary).
    pub fn set_process_mode(&mut self, mode: ProcessMode) -> Result<()> {
        if self.is_processing {
            return Err(Error::Other(
                "cannot set process mode while processing; call stop_processing() first"
                    .to_string(),
            ));
        }
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_process_mode(mode)
    }

    /// Query the current speaker arrangement of each audio input/output bus.
    pub fn bus_arrangements(&self) -> Result<crate::audio::BusArrangements> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .bus_arrangements()
    }

    /// Request specific speaker arrangements for the audio buses (e.g. force stereo, or a
    /// surround layout). The slices give one [`SpeakerArrangement`](crate::audio::SpeakerArrangement)
    /// per input bus and per output bus, in bus-index order.
    ///
    /// Re-runs the plugin's `setupProcessing`, so the plugin must **not** be processing (call
    /// [`Self::stop_processing`] first). A plugin may decline a requested layout and keep its
    /// own; re-query with [`Self::bus_arrangements`] to see what was actually applied. Errors
    /// while processing or under process isolation (not marshalled).
    pub fn set_bus_arrangements(
        &mut self,
        inputs: &[crate::audio::SpeakerArrangement],
        outputs: &[crate::audio::SpeakerArrangement],
    ) -> Result<()> {
        if self.is_processing {
            return Err(Error::Other(
                "cannot set bus arrangements while processing; call stop_processing() first"
                    .to_string(),
            ));
        }
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_bus_arrangements(inputs, outputs)
    }

    /// Activate or deactivate a single bus on the plugin (`IComponent::activateBus`).
    ///
    /// Hosts must explicitly activate the buses they intend to use; a plugin's secondary
    /// buses (sidechain / aux inputs, extra outputs) commonly start **inactive** and only
    /// receive/produce audio once activated. (The load sequence already activates the main
    /// audio and event buses, so call this to enable the rest.)
    ///
    /// `media_type` selects audio vs event buses and `direction` selects input vs output;
    /// `bus_index` is the 0-based index within that `(media_type, direction)` group (the
    /// same indexing as [`crate::discovery::BusLayout`]). `active` true activates, false
    /// deactivates.
    ///
    /// VST3 requires bus activation to happen while the component is **inactive** — i.e.
    /// before processing starts. This therefore returns an error if called while the plugin
    /// is processing; call [`Self::stop_processing`] first, activate the bus, then
    /// [`Self::start_processing`] again. Returns an error for an out-of-range `bus_index`,
    /// and under process isolation activation marshals across the boundary.
    pub fn set_bus_active(
        &mut self,
        media_type: crate::audio::MediaType,
        direction: crate::audio::BusDirection,
        bus_index: i32,
        active: bool,
    ) -> Result<()> {
        if self.is_processing {
            return Err(Error::Other(
                "cannot activate a bus while processing; call stop_processing() first".to_string(),
            ));
        }
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_bus_active(media_type, direction, bus_index, active)
    }

    /// Get all parameters
    pub fn get_parameters(&self) -> Result<Vec<Parameter>> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .get_all_parameters()
    }

    /// Set a parameter value by ID
    pub fn set_parameter(&mut self, id: u32, value: f64) -> Result<()> {
        if !(0.0..=1.0).contains(&value) {
            return Err(Error::InvalidParameter(format!(
                "Value {} is out of range [0.0, 1.0]",
                value
            )));
        }

        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_parameter(id, value)?;

        // Trigger callback if set
        if let Some(ref callback) = self.parameter_change_callback {
            callback(id, value);
        }

        Ok(())
    }

    /// Set a parameter value at a specific sample offset within the next process block.
    ///
    /// This is the sample-accurate building block for automation: call it once per
    /// sub-block point (e.g. from [`ParameterAutomation::points_for_block`]) and the plugin
    /// receives the changes at their offsets in the next `process_audio`. Like
    /// [`Self::set_parameter`], `value` is normalized `0.0..=1.0`.
    ///
    /// `sample_offset` is clamped to the block. Under process isolation the offset **is** now
    /// carried across the boundary and applied by the helper's in-process plugin.
    ///
    /// [`ParameterAutomation::points_for_block`]: crate::parameters::ParameterAutomation::points_for_block
    pub fn set_parameter_at(&mut self, id: u32, value: f64, sample_offset: i32) -> Result<()> {
        if !(0.0..=1.0).contains(&value) {
            return Err(Error::InvalidParameter(format!(
                "Value {} is out of range [0.0, 1.0]",
                value
            )));
        }
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_parameter_at(id, value, sample_offset)
    }

    /// Change the transport tempo (beats per minute) advertised to the plugin in the host
    /// `ProcessContext`, taking effect on the **next** processed block — even while the plugin
    /// is actively processing. Drives tempo-synced DSP (LFOs, synced delays, arpeggiators).
    ///
    /// `bpm` must be finite and greater than `0` (a non-positive tempo would freeze or reverse
    /// the derived musical playhead). Works both in-process and across process isolation.
    pub fn set_tempo(&mut self, bpm: f64) -> Result<()> {
        if !(bpm.is_finite() && bpm > 0.0) {
            return Err(Error::InvalidParameter(format!(
                "tempo must be finite and positive, got {bpm}"
            )));
        }
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_tempo(bpm)
    }

    /// Change the transport time signature advertised to the plugin in the host
    /// `ProcessContext` (`numerator`/`denominator`, e.g. `7, 8`), taking effect on the
    /// **next** processed block — even while the plugin is actively processing.
    ///
    /// `numerator` must be greater than `0` and `denominator` must be a power of two between
    /// `1` and `16` (`1`, `2`, `4`, `8`, or `16`) — the standard note values a time signature
    /// can denominate. Works both in-process and across process isolation.
    pub fn set_time_signature(&mut self, numerator: i32, denominator: i32) -> Result<()> {
        if numerator <= 0 {
            return Err(Error::InvalidParameter(format!(
                "time signature numerator must be positive, got {numerator}"
            )));
        }
        if !matches!(denominator, 1 | 2 | 4 | 8 | 16) {
            return Err(Error::InvalidParameter(format!(
                "time signature denominator must be one of 1, 2, 4, 8, 16, got {denominator}"
            )));
        }
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_time_signature(numerator, denominator)
    }

    /// Toggle the transport playing state advertised to the plugin in the host
    /// `ProcessContext` (the `kPlaying` flag), taking effect on the **next** processed block —
    /// even while the plugin is actively processing.
    ///
    /// While playing, the host advances the continuous and musical playhead each block; while
    /// stopped, the playhead still advances but the plugin sees the transport as not playing
    /// (so tempo-synced effects can react to a paused transport). Works both in-process and
    /// across process isolation.
    pub fn set_playing(&mut self, playing: bool) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .set_playing(playing)
    }

    /// Enumerate the plugin's units and their program lists (`IUnitInfo`).
    ///
    /// Returns an empty list for plugins that don't implement `IUnitInfo`, and (for now) for
    /// plugins running under process isolation. The root unit (id `0`) is typically present.
    pub fn get_units(&self) -> Result<Vec<PluginUnit>> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .get_units()
    }

    /// Select a program (preset) in a unit's program list (`IUnitInfo`).
    ///
    /// `unit_id` is a [`PluginUnit::id`] from [`get_units`](Self::get_units) (the root unit is
    /// `0`); `program_index` is a 0-based index into that unit's [`PluginUnit::programs`].
    /// Internally this locates the unit's program-change parameter (the controller parameter
    /// tied to the unit with the VST3 `kIsProgramChange` flag) and sets it to the normalized
    /// value `program_index / max(1, program_count - 1)`, driving both the controller (for the
    /// editor/display) and the processor (for the audio DSP).
    ///
    /// Returns an error for an unknown unit, a unit with no program list, an out-of-range
    /// index, a plugin that doesn't implement `IUnitInfo`, or a plugin running under process
    /// isolation only if the helper cannot resolve the unit. Works both in-process and across
    /// the isolation boundary.
    pub fn select_program(&mut self, unit_id: i32, program_index: i32) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .select_program(unit_id, program_index)
    }

    /// The plugin's reported processing latency in samples (e.g. from look-ahead or
    /// oversampling), via `IAudioProcessor::getLatencySamples`. Use it to delay-compensate
    /// when aligning the plugin's output with other signals. `0` if it reports none, or for
    /// plugins running under process isolation (not bridged).
    pub fn latency_samples(&self) -> u32 {
        self.internal
            .as_ref()
            .map(|i| i.latency_samples())
            .unwrap_or(0)
    }

    /// The plugin's reported tail length in samples (how long it keeps producing output
    /// after input stops — e.g. reverb/delay), via `IAudioProcessor::getTailSamples`. `0`
    /// means no tail; `u32::MAX` means an infinite tail. `0` for isolated plugins (not
    /// bridged).
    pub fn tail_samples(&self) -> u32 {
        self.internal
            .as_ref()
            .map(|i| i.tail_samples())
            .unwrap_or(0)
    }

    /// Resolve a MIDI controller to the parameter it's mapped to, via the plugin's
    /// `IMidiMapping` (`getMidiControllerAssignment`).
    ///
    /// `bus` is the event input bus index (usually `0`), `channel` the 0-based MIDI channel,
    /// and `cc` the MIDI controller number (`0–127`, or the VST3 specials such as `128`
    /// aftertouch / `129` pitch-bend). Returns the parameter id the controller drives, or
    /// `None` if the plugin doesn't implement `IMidiMapping`, the controller is unmapped, or
    /// the plugin is process-isolated (not bridged).
    pub fn midi_cc_to_parameter(&self, bus: i32, channel: i16, cc: u16) -> Option<u32> {
        // VST3 controller numbers are 0..130 (0–127 MIDI CCs + the specials up to pitch-bend).
        // Reject out-of-range values rather than forwarding a meaningless controller number.
        if cc > 129 {
            return None;
        }
        self.internal
            .as_ref()?
            .midi_cc_to_parameter(bus, channel, cc)
    }

    /// Get a parameter value by ID
    pub fn get_parameter(&self, id: u32) -> Result<f64> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .get_parameter(id)
    }

    /// Format a parameter value as the plugin itself would display it.
    ///
    /// VST3 keeps all parameter values normalized (0.0–1.0) and delegates
    /// human-readable formatting to the plugin's controller. This asks the plugin to
    /// render `normalized` for parameter `id`, returning exactly what its own UI would
    /// show — e.g. `"440.00 Hz"`, `"-6.0 dB"`, `"Sine"`. Prefer this over
    /// [`Parameter::format_value`], which can only approximate without the plugin's
    /// internal mapping.
    pub fn format_parameter(&self, id: u32, normalized: f64) -> Result<String> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .format_parameter(id, normalized)
    }

    /// Set a parameter by name
    pub fn set_parameter_by_name(&mut self, name: &str, value: f64) -> Result<()> {
        let params = self.get_parameters()?;
        let param = params
            .iter()
            .find(|p| p.name == name)
            .ok_or_else(|| Error::InvalidParameter(format!("Parameter '{}' not found", name)))?;

        self.set_parameter(param.id, value)
    }

    /// Find a parameter by name
    pub fn find_parameter(&self, name: &str) -> Result<Parameter> {
        let params = self.get_parameters()?;
        params
            .into_iter()
            .find(|p| p.name == name)
            .ok_or_else(|| Error::InvalidParameter(format!("Parameter '{}' not found", name)))
    }

    /// Send a MIDI note on event
    pub fn send_midi_note(&mut self, note: u8, velocity: u8, channel: MidiChannel) -> Result<()> {
        if note > 127 {
            return Err(Error::MidiError(format!("Invalid note number: {}", note)));
        }
        if velocity > 127 {
            return Err(Error::MidiError(format!("Invalid velocity: {}", velocity)));
        }

        let event = MidiEvent::NoteOn {
            channel,
            note,
            velocity,
        };
        self.send_midi_event(event)
    }

    /// Send a MIDI note off event
    pub fn send_midi_note_off(&mut self, note: u8, channel: MidiChannel) -> Result<()> {
        if note > 127 {
            return Err(Error::MidiError(format!("Invalid note number: {}", note)));
        }

        let event = MidiEvent::NoteOff {
            channel,
            note,
            velocity: 0,
        };
        self.send_midi_event(event)
    }

    /// Send a MIDI control change event
    pub fn send_midi_cc(&mut self, controller: u8, value: u8, channel: MidiChannel) -> Result<()> {
        if controller > 127 {
            return Err(Error::MidiError(format!(
                "Invalid controller number: {}",
                controller
            )));
        }
        if value > 127 {
            return Err(Error::MidiError(format!("Invalid CC value: {}", value)));
        }

        let event = MidiEvent::ControlChange {
            channel,
            controller,
            value,
        };
        self.send_midi_event(event)
    }

    /// Send a generic MIDI event
    pub fn send_midi_event(&mut self, event: MidiEvent) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .send_midi_event(event)
    }

    /// Schedule a MIDI event at a sample offset within the **next** [`process_audio`] block.
    ///
    /// Use this for sample-accurate sequencing: an event sent with `sample_offset = N` takes
    /// effect `N` frames into the next processed block, rather than at its start. Keep the
    /// offset within the upcoming block's frame count ([`Plugin::block_size`] is the maximum);
    /// a negative offset is treated as 0, and an offset past the block end is plugin-defined.
    ///
    /// Under process isolation the offset is not marshalled across the boundary — the event is
    /// delivered at block start (offset 0), same as [`Self::send_midi_event`].
    ///
    /// [`process_audio`]: Self::process_audio
    pub fn send_midi_event_at(&mut self, event: MidiEvent, sample_offset: i32) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .send_midi_event_at(event, sample_offset)
    }

    /// Start a note and get a per-voice [`NoteId`](crate::midi::NoteId) handle for sending
    /// per-note (MPE-style) expression to that exact voice via
    /// [`send_note_expression`](Self::send_note_expression).
    ///
    /// Unlike [`send_midi_note`](Self::send_midi_note) (which uses a shared note id and can't be
    /// individually expressed), this allocates a unique voice id. Pair it with
    /// [`note_off`](Self::note_off). Per-note expression works both in-process and under
    /// process isolation — the calls marshal across the boundary.
    pub fn note_on(
        &mut self,
        channel: MidiChannel,
        note: u8,
        velocity: u8,
    ) -> Result<crate::midi::NoteId> {
        self.note_on_at(channel, note, velocity, 0)
    }

    /// [`note_on`](Self::note_on) scheduled at a sample offset within the next block.
    pub fn note_on_at(
        &mut self,
        channel: MidiChannel,
        note: u8,
        velocity: u8,
        sample_offset: i32,
    ) -> Result<crate::midi::NoteId> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .note_on(channel, note, velocity, sample_offset)
    }

    /// Release a note started with [`note_on`](Self::note_on).
    pub fn note_off(&mut self, id: crate::midi::NoteId) -> Result<()> {
        self.note_off_at(id, 0)
    }

    /// [`note_off`](Self::note_off) scheduled at a sample offset within the next block.
    pub fn note_off_at(&mut self, id: crate::midi::NoteId, sample_offset: i32) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .note_off(id, sample_offset)
    }

    /// Send a per-note expression value for a voice (normalized `0.0..=1.0`; bipolar dimensions
    /// like [`Tuning`](crate::midi::NoteExpressionType::Tuning) center at `0.5`). The plugin
    /// must implement `INoteExpressionController` and the dimension must be one it advertises
    /// (see [`note_expressions`](Self::note_expressions)).
    pub fn send_note_expression(
        &mut self,
        id: crate::midi::NoteId,
        kind: crate::midi::NoteExpressionType,
        value: f64,
    ) -> Result<()> {
        self.send_note_expression_at(id, kind, value, 0)
    }

    /// [`send_note_expression`](Self::send_note_expression) scheduled at a sample offset.
    pub fn send_note_expression_at(
        &mut self,
        id: crate::midi::NoteId,
        kind: crate::midi::NoteExpressionType,
        value: f64,
        sample_offset: i32,
    ) -> Result<()> {
        if !(0.0..=1.0).contains(&value) {
            return Err(Error::InvalidParameter(format!(
                "note-expression value {value} out of range [0.0, 1.0]"
            )));
        }
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .send_note_expression(id, kind, value, sample_offset)
    }

    /// Enumerate the per-note expression dimensions the plugin advertises for the given event
    /// bus / channel (defaults: bus 0, channel 0), via `INoteExpressionController`. Empty if the
    /// plugin doesn't implement it.
    pub fn note_expressions(&self) -> Result<Vec<crate::midi::NoteExpressionInfo>> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .note_expressions(0, 0)
    }

    /// Start audio processing
    pub fn start_processing(&mut self) -> Result<()> {
        if self.is_processing {
            return Ok(());
        }

        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .start_processing()?;

        self.is_processing = true;
        Ok(())
    }

    /// Stop audio processing
    pub fn stop_processing(&mut self) -> Result<()> {
        if !self.is_processing {
            return Ok(());
        }

        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .stop_processing()?;

        self.is_processing = false;
        Ok(())
    }

    /// Process audio buffers
    pub fn process_audio(&mut self, buffers: &mut AudioBuffers) -> Result<()> {
        if !self.is_processing {
            return Err(Error::Other("Plugin is not processing".to_string()));
        }

        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .process(buffers)?;

        // Update audio levels
        if let Ok(mut levels) = self.audio_levels.lock() {
            levels.update_from_buffers(&buffers.outputs);

            // Trigger audio callback if set
            if let Some(ref callback) = self.audio_callback {
                callback(&levels);
            }
        }

        Ok(())
    }

    /// Get current output levels.
    ///
    /// Recovers automatically if the audio thread panicked while holding the lock
    /// (poisoned mutex) rather than propagating the panic to the caller — metering
    /// must never take down a UI thread polling it.
    pub fn get_output_levels(&self) -> AudioLevels {
        self.audio_levels
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }

    /// Check if the plugin is currently processing
    pub fn is_processing(&self) -> bool {
        self.is_processing
    }

    /// Set a callback for parameter changes
    pub fn on_parameter_change<F>(&mut self, callback: F)
    where
        F: Fn(u32, f64) + Send + 'static,
    {
        self.parameter_change_callback = Some(Box::new(callback));
    }

    /// Set a callback for audio processing (called after each process cycle)
    pub fn on_audio_process<F>(&mut self, callback: F)
    where
        F: Fn(&AudioLevels) + Send + 'static,
    {
        self.audio_callback = Some(Box::new(callback));
    }

    /// Check if the plugin has an editor GUI
    pub fn has_editor(&self) -> bool {
        self.internal
            .as_ref()
            .map(|i| i.has_editor())
            .unwrap_or(false)
    }

    /// Open the plugin editor window
    pub fn open_editor(&mut self, parent: WindowHandle) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .open_editor(parent.0)
    }

    /// Close the plugin editor window
    pub fn close_editor(&mut self) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .close_editor()
    }

    /// Get the preferred editor size
    pub fn get_editor_size(&self) -> Result<(i32, i32)> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .get_editor_size()
    }

    /// Create a batch parameter update
    pub fn update_parameters<F>(&mut self, f: F) -> Result<()>
    where
        F: FnOnce(&mut ParameterUpdate) -> Result<()>,
    {
        let mut update = ParameterUpdate::new(self);
        f(&mut update)?;
        update.apply()
    }

    /// Send MIDI panic (all notes off, all sounds off, reset controllers)
    pub fn midi_panic(&mut self) -> Result<()> {
        for i in 0..16 {
            if let Some(channel) = MidiChannel::from_index(i) {
                // All Notes Off
                self.send_midi_cc(123, 0, channel)?;
                // All Sounds Off
                self.send_midi_cc(120, 0, channel)?;
                // Reset All Controllers
                self.send_midi_cc(121, 0, channel)?;
            }
        }
        Ok(())
    }

    /// Get parameter changes from plugin GUI
    /// Returns a vector of (parameter_id, normalized_value) pairs
    /// This should be called regularly to pick up parameter changes made through the plugin's GUI
    pub fn get_parameter_changes(&self) -> Vec<(u32, f64)> {
        self.internal
            .as_ref()
            .map(|i| i.get_parameter_changes())
            .unwrap_or_default()
    }

    /// Drain the ordered log of parameter-edit gestures the plugin's editor has reported since
    /// the last call.
    ///
    /// This is the richer superset of [`Self::get_parameter_changes`]: rather than just the
    /// value changes, it preserves the begin/change/end ordering of each gesture, so the host
    /// can tell a deliberate, completed edit (`BeginGesture` … `ValueChange`* … `EndGesture`)
    /// from a stream of intermediate drag values. Poll it regularly (e.g. each UI frame) while
    /// the editor is open; an empty vector means nothing was reported. Works across process
    /// isolation — gestures are marshalled back from the helper.
    ///
    /// See [`ParameterEdit`] / [`ParameterEditKind`].
    pub fn take_parameter_edits(&mut self) -> Vec<ParameterEdit> {
        self.internal
            .as_mut()
            .map(|i| i.take_parameter_edits())
            .unwrap_or_default()
    }

    /// Take the MIDI events the plugin has emitted (e.g. from an arpeggiator or MPE
    /// controller) since the last call, draining the internal buffer.
    ///
    /// Output MIDI is captured while the plugin processes audio, so poll this regularly
    /// (e.g. each UI frame) while the plugin is playing; an empty vector means the plugin
    /// emitted nothing. This works for process-isolated plugins too — emitted events are
    /// marshalled back alongside each processed block.
    ///
    /// The buffer is capped at 4096 events: if you never poll while a chatty plugin keeps
    /// emitting, the oldest events are dropped (silently) to bound memory.
    pub fn take_output_midi(&self) -> Vec<MidiEvent> {
        self.internal
            .as_ref()
            .map(|i| i.take_output_events())
            .unwrap_or_default()
    }

    /// Get a `Send` handle for draining emitted MIDI from another thread without locking the
    /// audio thread (see [`OutputMidiConsumer`]). Returns `None` for an unloaded plugin or the
    /// process-isolation path. Useful with [`RealtimePluginRunner`](crate::RealtimePluginRunner):
    /// take the handle, move the plugin into the runner, and poll it from your UI thread while
    /// the audio thread renders.
    pub fn output_midi_handle(&self) -> Option<OutputMidiConsumer> {
        self.internal.as_ref().and_then(|i| i.output_midi_handle())
    }

    /// Save the plugin's current state (parameters, internal settings, loaded preset) to
    /// an opaque byte blob.
    ///
    /// The bytes are the plugin's own serialized state — treat them as opaque and pair them
    /// with the plugin's identity ([`PluginInfo::uid`]); they only mean something to the
    /// same plugin. Persist them to restore a patch later with [`Self::load_state`], or to
    /// snapshot a session. Call this on the main thread (see the
    /// [threading model](https://docs.rs/vst3-host)).
    ///
    /// Works both in-process and across process isolation (the state blob is marshalled over
    /// the IPC boundary). Returns an error for plugins that don't implement state saving.
    pub fn save_state(&self) -> Result<Vec<u8>> {
        self.internal
            .as_ref()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .save_state()
    }

    /// Restore plugin state from a blob produced by [`Self::save_state`] on the *same*
    /// plugin. Applies to both the processor and the controller, so parameter values and
    /// the editor reflect the restored state.
    ///
    /// Passing bytes from a different plugin has undefined results (the plugin decides what
    /// to do with bytes it doesn't recognize). Call this on the main thread.
    pub fn load_state(&mut self, data: &[u8]) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .load_state(data)
    }

    /// Save this plugin's state to a file as a [`PluginPreset`] (JSON: the plugin's `uid`
    /// and name plus the opaque state blob). The embedded `uid` lets [`Self::load_preset`]
    /// reject a preset saved from a different plugin.
    pub fn save_preset<P: AsRef<std::path::Path>>(&self, path: P) -> Result<()> {
        let info = self.info();
        let preset = PluginPreset {
            uid: info.uid.clone(),
            plugin_name: info.name.clone(),
            state: self.save_state()?,
        };
        let json = serde_json::to_vec_pretty(&preset)
            .map_err(|e| Error::Other(format!("serialize preset: {e}")))?;
        std::fs::write(path, json).map_err(|e| Error::Other(format!("write preset: {e}")))?;
        Ok(())
    }

    /// Load a [`PluginPreset`] file written by [`Self::save_preset`] and apply its state.
    /// Returns an error if the preset's `uid` doesn't match this plugin (loading another
    /// plugin's state is undefined).
    pub fn load_preset<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<()> {
        let bytes = std::fs::read(path).map_err(|e| Error::Other(format!("read preset: {e}")))?;
        let preset: PluginPreset = serde_json::from_slice(&bytes)
            .map_err(|e| Error::Other(format!("parse preset: {e}")))?;
        if preset.uid != self.info().uid {
            return Err(Error::Other(format!(
                "preset is for a different plugin ({}, expected {})",
                preset.plugin_name,
                self.info().name
            )));
        }
        self.load_state(&preset.state)
    }

    /// Save this plugin's state to a standard Steinberg `.vstpreset` file.
    ///
    /// Unlike [`Self::save_preset`] (a JSON wrapper specific to this library), the
    /// `.vstpreset` container is the interchange format shared by VST3 hosts and plugins, so
    /// the file can be read by other hosts (and by the plugin's own preset browser). It wraps
    /// the same opaque bytes from [`Self::save_state`] in a single `"Comp"` (component state)
    /// chunk, tagged with this plugin's class id ([`PluginInfo::uid`]) so a loader can reject
    /// presets from a different plugin. Call this on the main thread.
    pub fn save_vstpreset<P: AsRef<std::path::Path>>(&self, path: P) -> Result<()> {
        let state = self.save_state()?;
        let bytes = vstpreset::build(&self.info().uid, &state)?;
        std::fs::write(path, bytes).map_err(|e| Error::Other(format!("write vstpreset: {e}")))?;
        Ok(())
    }

    /// Load a Steinberg `.vstpreset` file and apply its component state to this plugin.
    ///
    /// Parses the `.vstpreset` container written by [`Self::save_vstpreset`] (or another VST3
    /// host), extracts the `"Comp"` (component state) chunk and passes it to
    /// [`Self::load_state`]. Returns an error if the file's magic is invalid, or if its class
    /// id doesn't match this plugin (loading another plugin's state is undefined). Call this
    /// on the main thread.
    pub fn load_vstpreset<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<()> {
        let bytes =
            std::fs::read(path).map_err(|e| Error::Other(format!("read vstpreset: {e}")))?;
        let parsed = vstpreset::parse(&bytes)?;
        if parsed.class_id != self.info().uid {
            return Err(Error::Other(format!(
                "vstpreset is for a different plugin (class id {}, expected {})",
                parsed.class_id,
                self.info().uid
            )));
        }
        self.load_state(&parsed.component_state)
    }

    /// The OS process id of the isolated helper hosting this plugin, or `None` if it runs
    /// in-process. Useful for monitoring an isolated plugin's resource use.
    pub fn isolation_pid(&self) -> Option<u32> {
        self.internal.as_ref().and_then(|i| i.helper_pid())
    }

    /// How many times this plugin has been recovered (helper respawned + reloaded), via either
    /// [`Self::recover`] or automatic recovery ([`Vst3HostBuilder::auto_recover_plugins`]).
    ///
    /// A recovery reloads the plugin from defaults — parameter values and loaded state are NOT
    /// replayed. With auto-recover on, a crash is otherwise invisible (the call returns `Ok`),
    /// so poll this count to detect that a reset happened and re-apply a saved
    /// [`save_state`](Self::save_state) snapshot.
    ///
    /// [`Vst3HostBuilder::auto_recover_plugins`]: crate::Vst3HostBuilder::auto_recover_plugins
    pub fn recovery_count(&self) -> u64 {
        self.internal
            .as_ref()
            .map(|i| i.recovery_count())
            .unwrap_or(0)
    }

    /// Total number of output audio channels across the plugin's output buses.
    ///
    /// Reflects the plugin's actual bus layout (mono / stereo / surround / multi-bus), not a
    /// stereo assumption — useful for sizing meters or output buffers. Returns 2 if unknown.
    pub fn output_channel_count(&self) -> usize {
        self.internal
            .as_ref()
            .map(|i| i.output_channel_count())
            .unwrap_or(2)
    }

    /// Poll for an editor resize the plugin requested via VST3's `IPlugFrame` since the last
    /// call, as `(width, height)` in pixels, or `None`.
    ///
    /// Plugins with resizable editors call back to ask the host to resize the window hosting
    /// their view. Poll this on your UI thread (e.g. each frame) while the editor is open and
    /// resize your editor container to match. Only the in-process editor path reports this.
    pub fn take_editor_resize_request(&self) -> Option<(i32, i32)> {
        self.internal
            .as_ref()
            .and_then(|i| i.take_editor_resize_request())
    }

    /// Recover a process-isolated plugin whose helper has crashed.
    ///
    /// When an isolated plugin's helper process dies, calls return [`Error::PluginCrashed`]
    /// and the host itself stays alive. This respawns the helper and reloads the plugin
    /// from the same path and audio settings, restarting processing if it was running.
    ///
    /// **The reloaded plugin starts from its default state** — parameter values and any
    /// loaded preset are lost. Snapshot with [`Self::save_state`] beforehand and
    /// [`Self::load_state`] after recovering to preserve them. Returns an error for
    /// in-process plugins (an in-process crash takes down the whole host) and if the
    /// reload itself fails.
    pub fn recover(&mut self) -> Result<()> {
        self.internal
            .as_mut()
            .ok_or_else(|| Error::Other("Plugin not initialized".to_string()))?
            .recover()
    }
}

/// Platform-specific window handle
pub struct WindowHandle(pub(crate) *mut std::ffi::c_void);

impl WindowHandle {
    /// Create from a raw window handle
    ///
    /// # Safety
    /// The pointer must be a valid window handle for the platform
    pub unsafe fn from_raw(handle: *mut std::ffi::c_void) -> Self {
        Self(handle)
    }
}

// Safe Send implementation - the window handle is platform-specific
unsafe impl Send for WindowHandle {}

#[cfg(target_os = "macos")]
impl WindowHandle {
    /// Create from an NSView pointer on macOS
    pub fn from_nsview(view: *mut std::ffi::c_void) -> Self {
        Self(view)
    }
}

#[cfg(target_os = "windows")]
impl WindowHandle {
    /// Create from an HWND on Windows
    pub fn from_hwnd(hwnd: *mut std::ffi::c_void) -> Self {
        Self(hwnd)
    }
}

#[cfg(target_os = "linux")]
impl WindowHandle {
    /// Create from an X11 window id on Linux (for VST3 `X11EmbedWindowID`).
    ///
    /// The VST3 X11 platform type expects the window id itself as the handle value,
    /// not a pointer to it.
    pub fn from_x11(window_id: u32) -> Self {
        Self(window_id as usize as *mut std::ffi::c_void)
    }
}

/// Build and parse the standard Steinberg `.vstpreset` container format.
///
/// Layout (all multi-byte integers little-endian, matching the SDK's `PresetFile`):
///
/// - Header (48 bytes): magic `b"VST3"` (4) + version `i32` = 1 (4) + 32-char ASCII class
///   id (the plugin's FUID hex) (32) + `i64` byte offset from the start of the file to the
///   chunk list (8).
/// - Body: the chunk payloads, written back to back after the header. We write a single
///   `"Comp"` (component state) chunk.
/// - Chunk list (at the header's list offset): magic `b"List"` (4) + entry count `i32` (4),
///   then per entry: 4-byte chunk id + `i64` absolute offset + `i64` size.
mod vstpreset {
    use crate::error::{Error, Result};

    const MAGIC: &[u8; 4] = b"VST3";
    const LIST_MAGIC: &[u8; 4] = b"List";
    const COMPONENT_CHUNK: &[u8; 4] = b"Comp";
    const VERSION: i32 = 1;
    const CLASS_ID_LEN: usize = 32;
    const HEADER_SIZE: usize = 4 + 4 + CLASS_ID_LEN + 8;

    /// A parsed `.vstpreset` container.
    pub(super) struct Parsed {
        /// The 32-char ASCII class id from the header.
        pub class_id: String,
        /// The bytes of the `"Comp"` (component state) chunk.
        pub component_state: Vec<u8>,
    }

    /// Build a `.vstpreset` file wrapping `component_state` in a single component chunk,
    /// tagged with `class_id` (a 32-char ASCII FUID hex string).
    pub(super) fn build(class_id: &str, component_state: &[u8]) -> Result<Vec<u8>> {
        let class_bytes = class_id.as_bytes();
        if class_bytes.len() != CLASS_ID_LEN || !class_id.is_ascii() {
            return Err(Error::Other(format!(
                "vstpreset class id must be {CLASS_ID_LEN} ASCII chars, got {:?}",
                class_id
            )));
        }

        let comp_offset = HEADER_SIZE as i64;
        let comp_size = component_state.len() as i64;
        let list_offset = HEADER_SIZE + component_state.len();

        let mut out = Vec::with_capacity(list_offset + 8 + 24);
        // Header.
        out.extend_from_slice(MAGIC);
        out.extend_from_slice(&VERSION.to_le_bytes());
        out.extend_from_slice(class_bytes);
        out.extend_from_slice(&(list_offset as i64).to_le_bytes());
        // Body.
        out.extend_from_slice(component_state);
        // Chunk list.
        out.extend_from_slice(LIST_MAGIC);
        out.extend_from_slice(&1i32.to_le_bytes());
        out.extend_from_slice(COMPONENT_CHUNK);
        out.extend_from_slice(&comp_offset.to_le_bytes());
        out.extend_from_slice(&comp_size.to_le_bytes());

        Ok(out)
    }

    /// Parse a `.vstpreset` file, extracting the class id and the component-state chunk.
    pub(super) fn parse(bytes: &[u8]) -> Result<Parsed> {
        if bytes.len() < HEADER_SIZE {
            return Err(Error::Other("vstpreset too short for header".to_string()));
        }
        if &bytes[0..4] != MAGIC {
            return Err(Error::Other(format!(
                "bad vstpreset magic: expected {:?}, got {:?}",
                MAGIC,
                &bytes[0..4]
            )));
        }
        let version = read_i32(&bytes[4..8]);
        if version != VERSION {
            return Err(Error::Other(format!(
                "unsupported vstpreset version {version} (expected {VERSION})"
            )));
        }
        let class_id = String::from_utf8(bytes[8..8 + CLASS_ID_LEN].to_vec())
            .map_err(|e| Error::Other(format!("vstpreset class id not UTF-8: {e}")))?;
        let list_offset = read_i64(&bytes[8 + CLASS_ID_LEN..HEADER_SIZE]);
        if list_offset < HEADER_SIZE as i64 || list_offset as usize > bytes.len() {
            return Err(Error::Other(format!(
                "vstpreset chunk-list offset {list_offset} out of bounds (len {})",
                bytes.len()
            )));
        }
        let list = &bytes[list_offset as usize..];
        if list.len() < 8 || &list[0..4] != LIST_MAGIC {
            return Err(Error::Other(
                "vstpreset chunk list missing or malformed".to_string(),
            ));
        }
        let count = read_i32(&list[4..8]);
        if count < 0 {
            return Err(Error::Other("vstpreset negative entry count".to_string()));
        }
        let mut cursor = 8;
        for _ in 0..count {
            if list.len() < cursor + 20 {
                return Err(Error::Other(
                    "vstpreset chunk-list entry truncated".to_string(),
                ));
            }
            let id = &list[cursor..cursor + 4];
            let offset = read_i64(&list[cursor + 4..cursor + 12]);
            let size = read_i64(&list[cursor + 12..cursor + 20]);
            cursor += 20;
            if id == COMPONENT_CHUNK {
                if offset < 0 || size < 0 {
                    return Err(Error::Other(
                        "vstpreset component chunk has negative offset/size".to_string(),
                    ));
                }
                let start = offset as usize;
                let end = start
                    .checked_add(size as usize)
                    .ok_or_else(|| Error::Other("vstpreset chunk size overflow".to_string()))?;
                if end > bytes.len() {
                    return Err(Error::Other(format!(
                        "vstpreset component chunk [{start}..{end}] out of bounds (len {})",
                        bytes.len()
                    )));
                }
                return Ok(Parsed {
                    class_id,
                    component_state: bytes[start..end].to_vec(),
                });
            }
        }
        Err(Error::Other(
            "vstpreset has no component (\"Comp\") chunk".to_string(),
        ))
    }

    fn read_i32(b: &[u8]) -> i32 {
        i32::from_le_bytes([b[0], b[1], b[2], b[3]])
    }

    fn read_i64(b: &[u8]) -> i64 {
        i64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
    }
}

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

    fn note(n: u8) -> MidiEvent {
        MidiEvent::NoteOn {
            channel: MidiChannel::Ch1,
            note: n,
            velocity: 100,
        }
    }

    #[test]
    fn drains_in_order_and_drops_oldest_when_full() {
        let q = Arc::new(ArrayQueue::new(2));
        let consumer = OutputMidiConsumer::from_queue(q.clone());

        // force_push mirrors what process() does: when full, the oldest is dropped.
        q.force_push(note(60));
        q.force_push(note(61));
        q.force_push(note(62)); // capacity 2 → drops note 60

        assert_eq!(consumer.drain(), vec![note(61), note(62)]);
        // Drained: now empty.
        assert_eq!(consumer.pop(), None);
        assert_eq!(consumer.drain(), vec![]);
    }

    #[test]
    fn handle_is_send_and_shares_the_queue_across_threads() {
        let q = Arc::new(ArrayQueue::new(8));
        let consumer = OutputMidiConsumer::from_queue(q.clone());
        // Push from another thread (the audio side is a different thread in practice).
        let producer = q.clone();
        std::thread::spawn(move || {
            producer.force_push(note(64));
        })
        .join()
        .unwrap();
        assert_eq!(consumer.pop(), Some(note(64)));
    }
}

#[cfg(test)]
mod vstpreset_tests {
    use super::vstpreset;

    const TEST_CLASS_ID: &str = "0123456789ABCDEF0123456789ABCDEF";

    #[test]
    fn build_parse_round_trip() {
        let state = b"opaque plugin state \x00\x01\x02\xff bytes".to_vec();
        let bytes = vstpreset::build(TEST_CLASS_ID, &state).expect("build");

        // Sanity-check the header layout.
        assert_eq!(&bytes[0..4], b"VST3");
        assert_eq!(
            i32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]),
            1
        );
        assert_eq!(&bytes[8..40], TEST_CLASS_ID.as_bytes());

        let parsed = vstpreset::parse(&bytes).expect("parse");
        assert_eq!(parsed.class_id, TEST_CLASS_ID);
        assert_eq!(parsed.component_state, state);
    }

    #[test]
    fn round_trip_empty_state() {
        let bytes = vstpreset::build(TEST_CLASS_ID, &[]).expect("build");
        let parsed = vstpreset::parse(&bytes).expect("parse");
        assert_eq!(parsed.class_id, TEST_CLASS_ID);
        assert!(parsed.component_state.is_empty());
    }

    #[test]
    fn build_rejects_wrong_length_class_id() {
        assert!(vstpreset::build("short", b"x").is_err());
    }

    #[test]
    fn parse_rejects_bad_magic() {
        let mut bytes = vstpreset::build(TEST_CLASS_ID, b"x").expect("build");
        bytes[0] = b'X';
        assert!(vstpreset::parse(&bytes).is_err());
    }

    #[test]
    fn parse_rejects_truncated_header() {
        assert!(vstpreset::parse(b"VST3").is_err());
    }

    #[test]
    fn parse_rejects_out_of_bounds_list_offset() {
        let mut bytes = vstpreset::build(TEST_CLASS_ID, b"hello").expect("build");
        // Corrupt the list offset (bytes 40..48) to point past the end.
        let bad = (bytes.len() as i64 + 100).to_le_bytes();
        bytes[40..48].copy_from_slice(&bad);
        assert!(vstpreset::parse(&bytes).is_err());
    }
}