truce-au 0.58.0

Audio Unit v3 format wrapper for truce
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
//! Audio Unit v3 format wrapper for truce.
//!
//! Uses an Objective-C shim compiled via `cc` that implements the
//! `AUAudioUnit` subclass. The shim calls back into Rust for all
//! plugin logic via C FFI.

pub mod ffi;

use std::ffi::CString;
use std::os::raw::c_char;
use std::slice;

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, OnceLock};

// `Float::from_f64` is only invoked from the macOS-only `set_param`
// closure in `cb_gui_open` (the AU v2 host notifier path). Gate the
// import so iOS builds, which take a `_id`-no-op branch instead,
// don't flag it as unused.
#[cfg(target_os = "macos")]
use truce_core::Float;
use truce_core::SYSEX_POOL_PREALLOC;
use truce_core::cast::{len_u32, sample_pos_i64};
use truce_core::editor::Editor;
// `ClosureBridge`, `PluginContext`, `SendPtr`, `RawWindowHandle` are
// consumed only inside the apple-gated body of `cb_gui_open` - the
// AppKit/UiKit variants don't exist on Linux/Windows. Importing them
// from a non-apple module would also trigger the unused-import lint
// there.
use truce_core::chunked_process::{ChunkedProcess, process_chunked};
#[cfg(any(target_os = "macos", target_os = "ios"))]
use truce_core::editor::{ClosureBridge, PluginContext, RawWindowHandle, SendPtr};
use truce_core::events::{EVENT_LIST_PREALLOC, Event, EventBody, EventList, TransportInfo};
use truce_core::export::PluginExport;
use truce_core::info::PluginCategory;
use truce_core::midi::{decode_short_message, pitch_bend_to_bytes};
use truce_core::state;
use truce_core::ump::{SysExAssembler, SysExFeed, decode_ump_channel_voice_2};
use truce_core::wrapper::{
    default_io_channels, log_missing_bus_layout, run_audio_block, run_extern_callback_with,
    run_register,
};
use truce_params::{ParamFlags, ParamInfo, Params};

use ffi::{
    AuCallbacks, AuMidi2Event, AuMidiEvent, AuParamDescriptor, AuParamEvent, AuPluginDescriptor,
    AuTransportSnapshot,
};

// ---------------------------------------------------------------------------
// Instance wrapper - one per plugin instance, stored as the opaque ctx
// ---------------------------------------------------------------------------

/// Bounded handoff slot for state loads. Capacity 1: presets don't
/// arrive faster than the audio thread completes a block, and on
/// overflow we want most-recent-wins (`force_push`) so a rapid
/// double-recall doesn't get the audio thread to apply a stale state
/// after the host already moved on.
type StateLoadQueue = crossbeam_queue::ArrayQueue<state::DeserializedState>;

struct AuInstance<P: PluginExport> {
    plugin: P,
    /// Stable handle to the params Arc, set once at instance creation.
    /// Host-thread callbacks (`cb_param_*`, `cb_state_save`) read params
    /// through this handle so they never form a `&inst.plugin`
    /// reference. Params are atomic-backed and `Sync`.
    params_arc: Arc<P::Params>,
    /// Atomic snapshots of the plugin's most recent `latency()` /
    /// `tail()`. Updated by the audio thread (or `cb_reset`).
    latency_cache: AtomicU32,
    tail_cache: AtomicU32,
    event_list: EventList,
    output_events: EventList,
    /// Per-sub-block scratch for `chunked_process::process_chunked`.
    sub_event_scratch: EventList,
    /// Cached param-info table for the chunker's split predicate.
    param_infos: Vec<ParamInfo>,
    /// `min_subblock_samples` from `truce.toml`'s `[automation]`.
    min_subblock_samples: u32,
    /// Per-instance UMP `SysEx` reassembler. AU v3 hosts deliver
    /// long `SysEx` payloads as a chain of `SysEx`-7 (6-byte) or
    /// `SysEx`-8 (13-byte) UMPs; the assembler concatenates them
    /// into one logical [`EventBody::SysEx`] before pushing to the
    /// plugin's `event_list`. Holds
    /// [`truce_core::ump::SYSEX_ASSEMBLER_SLOTS`] ×
    /// [`SYSEX_POOL_PREALLOC`] (4 × 128 KiB = 512 KiB) of buffer
    /// space so concurrent streams across UMP groups don't bleed
    /// into each other. Cleared at the top of `cb_process` so a
    /// partial message can't bleed across blocks.
    sysex_assembler: SysExAssembler,
    plugin_id_hash: u64,
    sample_rate: f64,
    /// Max block size declared by the host via
    /// `kAudioUnitProperty_MaximumFramesPerSlice` (delivered through
    /// `cb_reset`'s `max_frames`). A generous default keeps the
    /// contract assert in `cb_process` from tripping for hosts that
    /// send process before declaring a max.
    max_block_size: usize,
    /// `true` once `cb_reset` has run. `cb_process` early-returns and
    /// zeros outputs while false so DSP doesn't run with un-snapped
    /// smoothers / unset sample rate.
    prepared: bool,
    /// Reused per-block scratch for `RawBufferScratch::build`. Lives
    /// on the instance so the audio thread doesn't heap-allocate.
    ///
    /// Parameterised by `P::Sample`; widens/narrows host-`f32`
    /// buffers around `plugin.process()` for plugins on `prelude64`.
    scratch: truce_core::buffer::RawBufferScratch<<P as truce_core::plugin::PluginRuntime>::Sample>,
    editor: Option<Box<dyn Editor>>,
    /// Shared transport slot: audio thread writes each block, editor reads.
    transport_slot: Arc<truce_core::TransportSlot>,
    /// Bounded SPSC handoff for state loads. Host (`cb_state_load`)
    /// and editor (`set_state` callback) deserialize on their thread
    /// and push the result; the audio thread pops at the top of
    /// `cb_process` and calls [`state::apply_state`]
    /// under its exclusive `&mut plugin`.
    pending_state: Arc<StateLoadQueue>,
}

// ---------------------------------------------------------------------------
// Intentional leaks
//
// Every `CString::into_raw()` and `Vec::leak()` / `param_descs.leak()`
// in this file feeds a `*const c_char` (or `*const SomeDesc`) into a
// descriptor that the AU host caches for the process lifetime. Hosts
// re-read these pointers on demand (display, parameter sweeps,
// validation) - there's no signal back to Rust saying "you may free
// this now". Freeing is therefore unsound.
//
// The leak is bounded: O(plugin_count × (param_count + a few strings))
// per process, allocated once at registration time. No leak per audio
// callback, per render, per editor open. AU bundles get unloaded with
// the host process, which reclaims the allocation.
//
// `Box::into_raw(boxed_instance)` in `cb_create` follows the same
// pattern but is *paired* with `cb_destroy` reconstituting the Box -
// so it isn't a leak, just a C-lifetime handoff.
//
// ---------------------------------------------------------------------------
// C callback implementations (generic over P)
//
// SAFETY for all unsafe extern "C" fn below:
// - `ctx` is a *mut c_void created by Box::into_raw in cb_create().
//   Valid until cb_destroy() (called exactly once by the AU shim).
// - The AU v2 shim (au_v2_shim.c) and v3 shim (au_shim.m) own the
//   Rust context. The AU host guarantees: render callback on the
//   audio thread with exclusive access; all other callbacks on the
//   main thread, serialized.
// - Audio buffer pointers come from the host's AudioBufferList and
//   are valid for the declared channel count × frame count.
// - MIDI events come from MusicDeviceMIDIEvent (v2) or
//   AURenderEvent linked list (v3).
// ---------------------------------------------------------------------------

unsafe extern "C" fn cb_create<P: PluginExport>() -> *mut std::ffi::c_void {
    let mut plugin = P::create();
    plugin.init();
    let info = P::info();
    let param_infos = plugin.params().param_infos();
    let params_arc = plugin.params_arc();
    let latency_cache = AtomicU32::new(plugin.latency());
    let tail_cache = AtomicU32::new(plugin.tail());
    let instance = Box::new(AuInstance::<P> {
        plugin,
        params_arc,
        latency_cache,
        tail_cache,
        event_list: EventList::with_capacity(EVENT_LIST_PREALLOC),
        output_events: EventList::with_capacity(EVENT_LIST_PREALLOC),
        sub_event_scratch: EventList::with_capacity(EVENT_LIST_PREALLOC),
        param_infos,
        min_subblock_samples: info.automation.min_subblock_samples,
        sysex_assembler: SysExAssembler::with_capacity(SYSEX_POOL_PREALLOC),
        plugin_id_hash: state::shared_plugin_state_hash(&info),
        sample_rate: 44100.0,
        max_block_size: 8192,
        prepared: false,
        scratch: truce_core::buffer::RawBufferScratch::default(),
        editor: None,
        transport_slot: truce_core::TransportSlot::new(),
        pending_state: Arc::new(StateLoadQueue::new(1)),
    });
    Box::into_raw(instance).cast::<std::ffi::c_void>()
}

unsafe extern "C" fn cb_destroy<P: PluginExport>(ctx: *mut std::ffi::c_void) {
    unsafe {
        if !ctx.is_null() {
            // Wrap the drop in `catch_unwind`: dropping the
            // `AuInstance` cascades into the editor's `Drop`,
            // which tears down wgpu surfaces / `NSView` /
            // baseview / runloop timers. A panic anywhere in
            // that chain propagates across this `extern "C"`
            // boundary as UB - in practice the host catches it
            // as an Objective-C exception, `objc_exception_rethrow`
            // can't recover, and `std::terminate` aborts the host
            // (the REAPER / Cubase quit-time SIGABRT pattern).
            // Catching here keeps the host alive; the process is
            // going away anyway so swallowing is fine.
            let raw = ctx.cast::<AuInstance<P>>();
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                drop(Box::from_raw(raw));
            }));
        }
    }
}

unsafe extern "C" fn cb_reset<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    sample_rate: f64,
    max_frames: u32,
) {
    unsafe {
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        // Clamp host-supplied max_frames to a sane minimum.
        let max_frames = (max_frames as usize).max(1024);
        inst.sample_rate = sample_rate;
        inst.max_block_size = max_frames;
        let (num_in, num_out) = default_io_channels::<P>().unwrap_or((2, 2));
        inst.scratch
            .ensure_capacity(num_in as usize, num_out as usize, max_frames);
        inst.plugin.reset(sample_rate, max_frames);
        inst.plugin.params().set_sample_rate(sample_rate);
        inst.plugin.params().snap_smoothers();
        inst.latency_cache
            .store(inst.plugin.latency(), Ordering::Relaxed);
        inst.tail_cache.store(inst.plugin.tail(), Ordering::Relaxed);
        inst.prepared = true;
    }
}

#[allow(clippy::too_many_lines)] // step-by-step block processing reads top-to-bottom
unsafe extern "C" fn cb_process<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    inputs: *const *const f32,
    outputs: *mut *mut f32,
    num_input_channels: u32,
    num_output_channels: u32,
    num_frames: u32,
    events: *const AuMidiEvent,
    num_events: u32,
    events2: *const AuMidi2Event,
    num_events2: u32,
    param_events: *const AuParamEvent,
    num_param_events: u32,
    transport_ptr: *const AuTransportSnapshot,
) {
    let nf = num_frames as usize;
    let ok = run_audio_block::<P>("AU", || unsafe {
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        let num_frames = nf;

        // Host called render before AU initialized us - sample rate
        // and smoothers haven't been primed. Zero outputs and bail.
        if !inst.prepared {
            for ch in 0..num_output_channels as usize {
                let ptr = *outputs.add(ch);
                if !ptr.is_null() {
                    std::ptr::write_bytes(ptr, 0, num_frames);
                }
            }
            return;
        }

        // Apply any pending state-load before per-block work so the
        // plugin sees consistent params and extra state for the
        // entire block. See `pending_state` field comment for the
        // queue-overflow policy.
        if let Some(state) = inst.pending_state.pop() {
            state::apply_state(&mut inst.plugin, &state);
        }

        // Convert MIDI events
        inst.event_list.clear();
        if !events.is_null() && num_events > 0 {
            let event_slice = slice::from_raw_parts(events, num_events as usize);
            for ev in event_slice {
                if let Some(body) = decode_short_message(ev.status, ev.data1, ev.data2) {
                    inst.event_list.push(Event {
                        sample_offset: ev.sample_offset,
                        body,
                    });
                }
            }
        }
        // MIDI 2.0 UMP decode. AU v3 hosts on iOS 17+ / macOS 14+
        // deliver per-note expression + 32-bit-resolution channel
        // voice messages through `AURenderEvent.MIDIEventList`; the
        // Swift shim hands them here as 64-bit UMPs (MIDI 2.0 CV
        // message type 0x4) plus the SysEx-7 (mt 0x3) / SysEx-8
        // (mt 0x5) variable-length streams that the assembler
        // reconstitutes into one `EventBody::SysEx` per logical
        // message. Utility / system / data UMPs are still skipped.
        inst.sysex_assembler.reset();
        if !events2.is_null() && num_events2 > 0 {
            let slice2 = slice::from_raw_parts(events2, num_events2 as usize);
            for ev in slice2 {
                let mt = ((ev.words[0] >> 28) & 0xF) as u8;
                match mt {
                    0x4 => {
                        if let Some(body) = decode_ump_channel_voice_2(ev.words) {
                            inst.event_list.push(Event {
                                sample_offset: ev.sample_offset,
                                body,
                            });
                        }
                    }
                    0x3 => {
                        let feed = inst
                            .sysex_assembler
                            .push_sysex7_packet([ev.words[0], ev.words[1]]);
                        if let SysExFeed::Complete(p) = feed {
                            // `push_sysex` failure here would mean the
                            // pool is full mid-block; drop the
                            // message rather than corrupt-splitting it.
                            let _ = inst.event_list.push_sysex(ev.sample_offset, p.bytes);
                        }
                    }
                    0x5 => {
                        let feed = inst.sysex_assembler.push_sysex8_packet(ev.words);
                        if let SysExFeed::Complete(p) = feed {
                            let _ = inst.event_list.push_sysex(ev.sample_offset, p.bytes);
                        }
                    }
                    _ => {
                        // mt 0x0 (utility), 0x1 (system real-time),
                        // 0x2 (MIDI 1 CV, already arrived via the
                        // legacy `events` slice above), 0xD / 0xF
                        // (flex / stream): not decoded.
                    }
                }
            }
        }

        // Host-side parameter automation. The AU v3 Swift shim
        // decodes `AURenderEvent.parameter` / `.parameterRamp`
        // entries into `AuParamEvent` rows with within-block
        // sample offsets; convert each into an
        // `EventBody::ParamChange` so the chunker
        // (`process_chunked` below) splits the audio block at the
        // automation point. Ramps are treated as a step at the
        // ramp's start - the plugin's own smoother handles the
        // actual interpolation, matching truce-vst3's treatment of
        // VST3 parameter queues. The v2 path passes
        // `param_events = NULL, num_param_events = 0` because AU v2
        // has no per-sample automation API at the format boundary.
        if !param_events.is_null() && num_param_events > 0 {
            let pe_slice = slice::from_raw_parts(param_events, num_param_events as usize);
            for pe in pe_slice {
                inst.event_list.push(Event {
                    sample_offset: pe.sample_offset,
                    body: EventBody::ParamChange {
                        id: pe.param_id,
                        value: f64::from(pe.value),
                    },
                });
            }
        }

        inst.event_list.sort();

        // Build AudioBuffer from raw pointers, reusing the per-instance scratch.
        debug_assert!(
            num_frames <= inst.max_block_size,
            "host violated AU contract: render() got {num_frames} frames \
             but kAudioUnitProperty_MaximumFramesPerSlice declared max {}",
            inst.max_block_size
        );
        let mut audio_buffer = inst.scratch.build(
            inputs,
            outputs,
            num_input_channels,
            num_output_channels,
            len_u32(num_frames),
            P::supports_in_place(),
        );

        let transport = if !transport_ptr.is_null() && (*transport_ptr).valid != 0 {
            let t = &*transport_ptr;
            TransportInfo {
                playing: t.playing != 0,
                recording: t.recording != 0,
                tempo: t.tempo,
                // The two `as u8` casts are post-clamped to `0..=255`.
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                time_sig_num: t.time_sig_num.clamp(0, i32::from(u8::MAX)) as u8,
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                time_sig_den: t.time_sig_den.clamp(0, i32::from(u8::MAX)) as u8,
                position_samples: sample_pos_i64(t.position_samples),
                position_seconds: 0.0,
                position_beats: t.position_beats,
                bar_start_beats: t.bar_start_beats,
                loop_active: t.loop_active != 0,
                loop_start_beats: t.loop_start_beats,
                loop_end_beats: t.loop_end_beats,
            }
        } else {
            TransportInfo::default()
        };
        inst.output_events.clear();
        inst.transport_slot.write(&transport);

        let mut transport_snap = transport;
        let chunk_args = ChunkedProcess {
            events: &inst.event_list,
            sub_event_scratch: &mut inst.sub_event_scratch,
            transport: &mut transport_snap,
            sample_rate: inst.sample_rate,
            output_events: &mut inst.output_events,
            params_fn: None,
            meters_fn: None,
            param_infos: &inst.param_infos,
            min_subblock_samples: inst.min_subblock_samples,
        };
        process_chunked(
            &mut inst.plugin,
            inst.params_arc.as_ref() as &dyn Params,
            &mut audio_buffer,
            chunk_args,
        );
        let _ = audio_buffer;
        // Narrow rendered f64 output back to host f32 when needed.
        // No-op for `f32` plugins.
        inst.scratch
            .finish_widening_f32(outputs, num_output_channels, len_u32(num_frames));

        // Refresh latency / tail caches so the host's main-thread
        // queries don't have to call into `inst.plugin`.
        inst.latency_cache
            .store(inst.plugin.latency(), Ordering::Relaxed);
        inst.tail_cache.store(inst.plugin.tail(), Ordering::Relaxed);
    });
    if !ok {
        unsafe {
            for ch in 0..num_output_channels as usize {
                let ptr = *outputs.add(ch);
                if !ptr.is_null() {
                    std::ptr::write_bytes(ptr, 0, nf);
                }
            }
        }
    }
}

unsafe extern "C" fn cb_param_count<P: PluginExport>(ctx: *mut std::ffi::c_void) -> u32 {
    unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        len_u32(inst.params_arc.count())
    }
}

unsafe extern "C" fn cb_param_get_value<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    id: u32,
) -> f64 {
    unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        inst.params_arc.get_plain(id).unwrap_or(0.0)
    }
}

unsafe extern "C" fn cb_param_set_value<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    id: u32,
    value: f64,
) {
    unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        inst.params_arc.set_plain(id, value);
    }
}

unsafe extern "C" fn cb_param_format_value<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    id: u32,
    value: f64,
    out: *mut c_char,
    out_len: u32,
) -> u32 {
    unsafe {
        // `out_len == 0` would underflow on `out_len as usize - 1`
        // and let `copy_nonoverlapping` write past the host-supplied
        // buffer. Treat zero capacity as "host wants nothing".
        if out_len == 0 || out.is_null() {
            return 0;
        }
        let inst = &*ctx.cast::<AuInstance<P>>();
        match inst.params_arc.format_value(id, value) {
            Some(text) => {
                let bytes = text.as_bytes();
                let len = bytes.len().min((out_len as usize) - 1);
                std::ptr::copy_nonoverlapping(bytes.as_ptr().cast::<c_char>(), out, len);
                *out.add(len) = 0;
                len_u32(len)
            }
            None => 0,
        }
    }
}

unsafe extern "C" fn cb_state_save<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    out_data: *mut *mut u8,
    out_len: *mut u32,
) {
    // Pre-zero the out pointers so a panic anywhere in the body below
    // leaves the host seeing an empty blob rather than a stale buffer
    // pointer paired with whatever length was last written.
    unsafe {
        *out_data = std::ptr::null_mut();
        *out_len = 0;
    }
    run_extern_callback_with::<P, ()>("au", "save_state", (), || unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        let (ids, values) = inst.params_arc.collect_values();
        // `plugin.save_state()` reads through the plugin reference: a
        // user impl that mutates non-atomic state from `process` while
        // also reading it from `save_state` races here. The contract
        // is "save_state must be safe to call concurrently with
        // process"; impls that copy from atomic params are fine.
        //
        // Allocator pin: this wrapper allocates with libc `malloc` and
        // the AU shim frees with libc `free`. The Rust global allocator
        // must not appear on either side; mixing allocators is UB.
        let extra = inst.plugin.save_state();
        let blob = state::serialize_state(inst.plugin_id_hash, &ids, &values, &extra);

        let len = blob.len();
        let ptr = malloc(len).cast::<u8>();
        if ptr.is_null() {
            // malloc failed - `*out_data` is already null and
            // `*out_len` already 0 from the pre-zero above.
            return;
        }
        std::ptr::copy_nonoverlapping(blob.as_ptr(), ptr, len);
        *out_data = ptr;
        *out_len = len_u32(len);
    });
}

unsafe extern "C" fn cb_state_load<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    data: *const u8,
    len: u32,
) {
    run_extern_callback_with::<P, ()>("au", "load_state", (), || unsafe {
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        // `slice::from_raw_parts(null, n)` for `n > 0` is UB. Treat
        // `(null, *)` and `(_, 0)` the same as "host gave us nothing".
        if data.is_null() || len == 0 {
            return;
        }
        let blob = slice::from_raw_parts(data, len as usize);
        if let Some(deserialized) = state::deserialize_state(blob, inst.plugin_id_hash) {
            // Apply params synchronously on the host thread (atomic-safe)
            // so host queries that read parameter values right after
            // `setFullState:` see the restored values without first
            // running a render block.
            state::apply_params(&*inst.params_arc, &deserialized);
            // Hand the deserialized state to the audio thread for
            // application. `force_push` overwrites any older pending
            // blob - see the `pending_state` field comment for why
            // newest-wins is the right policy.
            let _ = inst.pending_state.force_push(deserialized);
            if let Some(ref mut editor) = inst.editor {
                editor.state_changed();
            }
        }
    });
}

unsafe extern "C" fn cb_state_free(data: *mut u8, _len: u32) {
    unsafe {
        if !data.is_null() {
            free(data.cast::<std::ffi::c_void>());
        }
    }
}

// ---------------------------------------------------------------------------
// Factory presets (kAudioUnitProperty_FactoryPresets backing)
// ---------------------------------------------------------------------------

/// One bundled factory preset: the display name handed to the shim
/// (C-string, lives for the process) plus the file to load.
struct FactoryPresetEntry {
    name: CString,
    path: std::path::PathBuf,
}

/// Lazily-enumerated factory presets from the component bundle's
/// `Contents/Resources/Presets/`. One static per shared library, like
/// the registration statics: an AU dylib ships exactly one plugin
/// type, so the single `OnceLock` never sees a second
/// monomorphization. Empty when the bundle ships no presets (or when
/// the dylib isn't inside a component bundle, e.g. the AU v3 appex
/// layout - the shim then reports the property as invalid).
static FACTORY_PRESETS: OnceLock<Vec<FactoryPresetEntry>> = OnceLock::new();

fn factory_presets<P: PluginExport>() -> &'static [FactoryPresetEntry] {
    FACTORY_PRESETS.get_or_init(|| {
        let Some(root) = component_presets_root::<P>() else {
            return Vec::new();
        };
        let info = P::info();
        let mut refs = truce_core::presets::enumerate_scope(
            &root,
            truce_core::presets::PresetScope::Factory,
            info.vendor,
            info.name,
        );
        // The library's `default = true` preset leads the list: hosts
        // treat factory preset 0 as the de-facto initial sound. The
        // stable sort keeps the walk's alphabetical order behind it.
        refs.sort_by_key(|preset| !preset.default);
        refs.into_iter()
            .filter_map(|preset| {
                // Hosts show the factory list flat; keep the category
                // visible the way the LV2 labels do.
                let display = match &preset.category {
                    Some(category) => format!("{category}/{}", preset.name),
                    None => preset.name.clone(),
                };
                Some(FactoryPresetEntry {
                    name: CString::new(display).ok()?,
                    path: preset.path,
                })
            })
            .collect()
    })
}

/// Mirrors the layout `<libc/dlfcn.h>` defines; bound directly like
/// the `malloc` / `free` externs above to keep the crate free of a
/// libc dependency. Field names keep dlfcn's `dli_` prefix so they
/// line up with the C declaration they shadow.
#[repr(C)]
#[allow(clippy::struct_field_names)]
struct DlInfo {
    dli_fname: *const c_char,
    dli_fbase: *mut std::ffi::c_void,
    dli_sname: *const c_char,
    dli_saddr: *mut std::ffi::c_void,
}

unsafe extern "C" {
    fn dladdr(addr: *const std::ffi::c_void, info: *mut DlInfo) -> i32;
}

/// Resolve the `Resources/Presets/` directory of the bundle this
/// code lives in, via `dladdr` on one of our own functions. Two
/// layouts exist:
///
/// - AU v2 component: `<X>.component/Contents/MacOS/<X>` with presets
///   in `Contents/Resources/Presets/` (two levels up).
/// - AU v3 framework: `<F>.framework/Versions/A/<F>` with presets in
///   `Versions/A/Resources/Presets/` (one level up).
fn component_presets_root<P: PluginExport>() -> Option<std::path::PathBuf> {
    let mut info = DlInfo {
        dli_fname: std::ptr::null(),
        dli_fbase: std::ptr::null_mut(),
        dli_sname: std::ptr::null(),
        dli_saddr: std::ptr::null_mut(),
    };
    let probe = cb_factory_preset_count::<P> as *const std::ffi::c_void;
    // SAFETY: `probe` is a function in this image; `dladdr` only
    // writes into the out-struct on success.
    if unsafe { dladdr(probe, &raw mut info) } == 0 || info.dli_fname.is_null() {
        return None;
    }
    // SAFETY: `dli_fname` is a NUL-terminated path owned by dyld.
    let exe = unsafe { std::ffi::CStr::from_ptr(info.dli_fname) };
    let exe = std::path::Path::new(exe.to_str().ok()?);
    let parent = exe.parent()?;
    [parent.parent()?, parent]
        .into_iter()
        .map(|dir| dir.join("Resources/Presets"))
        .find(|root| root.is_dir())
}

unsafe extern "C" fn cb_factory_preset_count<P: PluginExport>(_ctx: *mut std::ffi::c_void) -> u32 {
    run_extern_callback_with::<P, u32>("au", "factory_preset_count", 0, || {
        len_u32(factory_presets::<P>().len())
    })
}

unsafe extern "C" fn cb_factory_preset_name<P: PluginExport>(
    _ctx: *mut std::ffi::c_void,
    index: u32,
) -> *const c_char {
    run_extern_callback_with::<P, *const c_char>(
        "au",
        "factory_preset_name",
        std::ptr::null(),
        || {
            factory_presets::<P>()
                .get(index as usize)
                .map_or(std::ptr::null(), |entry| entry.name.as_ptr())
        },
    )
}

unsafe extern "C" fn cb_factory_preset_load<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    index: u32,
) -> i32 {
    run_extern_callback_with::<P, i32>("au", "factory_preset_load", 0, || unsafe {
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        let Some(entry) = factory_presets::<P>().get(index as usize) else {
            return 0;
        };
        let Some(deserialized) =
            truce_core::presets::load_preset_file(&entry.path, inst.plugin_id_hash)
        else {
            return 0;
        };
        // Same apply path as cb_state_load: params synchronously on
        // the host thread, full state through the audio-thread
        // handoff, editor notified.
        state::apply_params(&*inst.params_arc, &deserialized);
        let _ = inst.pending_state.force_push(deserialized);
        if let Some(ref mut editor) = inst.editor {
            editor.state_changed();
        }
        1
    })
}

// ---------------------------------------------------------------------------
// Output event callbacks (plugin → host MIDI)
// ---------------------------------------------------------------------------

// UMP MIDI 2.0 CV decoder lives in `truce-core::ump` so the same
// codec backs CLAP's `CLAP_EVENT_MIDI2` path and AU's MIDIEventList
// path.

/// Map a truce `Event` body to a 3-byte AU MIDI packet. Returns
/// `None` for event types that don't fit (MIDI 2.0, `ParamChange`,
/// Transport, etc.).
fn try_encode_au_midi(event: &Event) -> Option<AuMidiEvent> {
    let (status, data1, data2) = match &event.body {
        EventBody::NoteOn {
            channel,
            note,
            velocity,
            ..
        } => (0x90 | (channel & 0x0F), *note, *velocity),
        EventBody::NoteOff {
            channel,
            note,
            velocity,
            ..
        } => (0x80 | (channel & 0x0F), *note, *velocity),
        EventBody::ControlChange {
            channel, cc, value, ..
        } => (0xB0 | (channel & 0x0F), *cc, *value),
        EventBody::Aftertouch {
            channel,
            note,
            pressure,
            ..
        } => (0xA0 | (channel & 0x0F), *note, *pressure),
        EventBody::ChannelPressure {
            channel, pressure, ..
        } => (0xD0 | (channel & 0x0F), *pressure, 0),
        EventBody::PitchBend { channel, value, .. } => {
            let (lsb, msb) = pitch_bend_to_bytes(*value);
            (0xE0 | (channel & 0x0F), lsb, msb)
        }
        EventBody::ProgramChange {
            channel, program, ..
        } => (0xC0 | (channel & 0x0F), *program, 0),
        _ => return None,
    };
    Some(AuMidiEvent {
        sample_offset: event.sample_offset,
        status,
        data1,
        data2,
        _pad: 0,
    })
}

unsafe extern "C" fn cb_output_event_count<P: PluginExport>(ctx: *mut std::ffi::c_void) -> u32 {
    unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        let n = inst
            .output_events
            .iter()
            .filter(|e| try_encode_au_midi(e).is_some())
            .count();
        len_u32(n)
    }
}

unsafe extern "C" fn cb_output_event_at<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    index: u32,
    out: *mut AuMidiEvent,
) {
    unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        if let Some(packet) = inst
            .output_events
            .iter()
            .filter_map(try_encode_au_midi)
            .nth(index as usize)
        {
            *out = packet;
        }
    }
}

unsafe extern "C" fn cb_output_sysex_count<P: PluginExport>(ctx: *mut std::ffi::c_void) -> u32 {
    unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        len_u32(
            inst.output_events
                .iter()
                .filter(|e| matches!(e.body, EventBody::SysEx { .. }))
                .count(),
        )
    }
}

unsafe extern "C" fn cb_output_sysex_at<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    index: u32,
    out_delta_frames: *mut u32,
    out_bytes: *mut *const u8,
    out_len: *mut u32,
) {
    unsafe {
        let inst = &*ctx.cast::<AuInstance<P>>();
        if let Some(event) = inst
            .output_events
            .iter()
            .filter(|e| matches!(e.body, EventBody::SysEx { .. }))
            .nth(index as usize)
        {
            let bytes = inst.output_events.sysex_bytes(&event.body);
            *out_delta_frames = event.sample_offset;
            *out_bytes = bytes.as_ptr();
            *out_len = len_u32(bytes.len());
        }
    }
}

// ---------------------------------------------------------------------------
// GUI callbacks
// ---------------------------------------------------------------------------

unsafe extern "C" fn cb_gui_has_editor<P: PluginExport>(ctx: *mut std::ffi::c_void) -> i32 {
    unsafe {
        if ctx.is_null() {
            return 0;
        }
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        if inst.editor.is_none() {
            inst.editor = inst.plugin.editor();
        }
        i32::from(inst.editor.is_some())
    }
}

/// Used by the AU v3 Swift shim in `viewDidLayoutSubviews` to
/// decide whether to forward host bounds changes to the editor,
/// and by the AU v2 `uiViewForAudioUnit:withSize:` path to pick
/// between the host's `preferredSize` and the editor's natural
/// size. Returns 1 / 0 mapping to "yes / no resizable".
unsafe extern "C" fn cb_gui_can_resize<P: PluginExport>(ctx: *mut std::ffi::c_void) -> i32 {
    unsafe {
        if ctx.is_null() {
            return 0;
        }
        let inst = &*ctx.cast::<AuInstance<P>>();
        i32::from(inst.editor.as_ref().is_some_and(|e| e.can_resize()))
    }
}

/// Host-driven `set_size`. The AU v2 Cocoa view's
/// `setFrameSize:` / superview-frame observer calls this when the
/// host resizes its outer container; the AU v3 Swift shim calls
/// it from `viewDidLayoutSubviews`. Clamps to the editor's
/// `min_size` / `max_size` / `aspect_ratio` so a host dragging
/// below the editor's floor doesn't clip widgets (mirrors the
/// CLAP and VST3 wrappers).
unsafe extern "C" fn cb_gui_set_size<P: PluginExport>(ctx: *mut std::ffi::c_void, w: u32, h: u32) {
    unsafe {
        if ctx.is_null() || w == 0 || h == 0 {
            return;
        }
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        if let Some(ref mut editor) = inst.editor
            && editor.can_resize()
        {
            let (cw, ch) = clamp_logical_to_editor(w, h, editor.as_ref());
            editor.set_size(cw, ch);
        }
    }
}

/// Clamp a requested logical size to the editor's `min_size` /
/// `max_size` / `aspect_ratio`. Mirrors the helpers that live in
/// the CLAP and VST3 wrappers - kept local rather than in
/// truce-core because it's the wrapper's job to honour host-side
/// constraints, not the trait's.
fn clamp_logical_to_editor(w: u32, h: u32, editor: &dyn truce_core::editor::Editor) -> (u32, u32) {
    let (min_w, min_h) = editor.min_size();
    let (max_w, max_h) = editor.max_size();
    let mut w = w.clamp(min_w.max(1), max_w);
    let mut h = h.clamp(min_h.max(1), max_h);
    if let Some((num, denom)) = editor.aspect_ratio()
        && num > 0
        && denom > 0
    {
        let num64 = u64::from(num);
        let denom64 = u64::from(denom);
        let h_implied = (u64::from(w) * denom64 / num64).clamp(1, u64::from(u32::MAX));
        #[allow(clippy::cast_possible_truncation)]
        let h_implied_u32 = h_implied as u32;
        if h_implied_u32 >= min_h.max(1) && h_implied_u32 <= max_h {
            h = h_implied_u32;
        } else {
            let w_implied = (u64::from(h) * num64 / denom64).clamp(1, u64::from(u32::MAX));
            #[allow(clippy::cast_possible_truncation)]
            let w_implied_u32 = w_implied as u32;
            w = w_implied_u32.clamp(min_w.max(1), max_w);
            let h_final = (u64::from(w) * denom64 / num64).clamp(1, u64::from(u32::MAX));
            #[allow(clippy::cast_possible_truncation)]
            {
                h = (h_final as u32).clamp(min_h.max(1), max_h);
            }
        }
    }
    (w, h)
}

unsafe extern "C" fn cb_gui_get_size<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    w: *mut u32,
    h: *mut u32,
) {
    unsafe {
        if ctx.is_null() {
            return;
        }
        // Lazily install the editor here too. Some AU validators
        // (`auval`, Logic Pro's plugin validator) call `..._get_size`
        // before `..._has_editor`, which is the canonical install
        // site. Without the lazy install here those validators see
        // `inst.editor == None` and silently receive a 0x0 view,
        // which shows up as "plugin reports invalid size" in their
        // reports.
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        if inst.editor.is_none() {
            inst.editor = inst.plugin.editor();
        }
        if let Some(ref editor) = inst.editor {
            // AU is macOS-only; hosts embed our NSView inside a Cocoa
            // container at logical-point coordinates and AppKit handles
            // the Retina backing transparently. Report the editor size
            // as-is - no scaling.
            let (ew, eh) = editor.size();
            *w = ew;
            *h = eh;
        }
    }
}

unsafe extern "C" fn cb_gui_open<P: PluginExport>(
    ctx: *mut std::ffi::c_void,
    parent: *mut std::ffi::c_void,
) {
    // AU is macOS+iOS-only at runtime. Linux/Windows builds compile
    // the wrapper crate for completeness (it's part of the workspace
    // build matrix) but the body references AppKit / UIKit /
    // AUEventListener APIs that don't exist off-Apple. Stubbing the
    // body keeps the FFI table population in `register_au_inner`
    // type-checking on every platform.
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _ = ctx;
        let _ = parent;
        let _ = std::marker::PhantomData::<P>;
    }
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    unsafe {
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        if let Some(ref mut editor) = inst.editor {
            let params = inst.plugin.params_arc();
            let plugin_ptr = SendPtr::new(&raw const inst.plugin);
            let ctx_raw = SendPtr::new(ctx);
            let params_for_set = params.clone();
            let params_for_get = params.clone();
            let params_for_plain = params.clone();
            let params_for_fmt = params.clone();
            let params_for_ctx = params.clone();
            let pending_state_for_set = inst.pending_state.clone();
            let transport_slot = inst.transport_slot.clone();
            let ctx_for_begin = ctx_raw;
            let ctx_for_end = ctx_raw;
            // iOS AU v3 hosts the editor inside an .appex; v2's
            // `AUEventListener` doesn't exist there. Parameter
            // changes from the editor flow to the host directly
            // through the AUParameterTree's setter (handled by the
            // Swift shim). The begin/set/end closures are no-ops on
            // iOS so the plugin's editor code stays platform-agnostic.
            let context = PluginContext::from_closures(
                ClosureBridge {
                    #[cfg(target_os = "macos")]
                    begin_edit: Box::new(move |id| {
                        // Broadcasts kAudioUnitEvent_BeginParameterChangeGesture
                        // via AUEventListenerNotify so hosts (Logic, Live,
                        // Reaper) group subsequent set_param calls into one
                        // undo step and one automation gesture.
                        truce_au_v2_host_begin_param_gesture(ctx_for_begin.as_ptr().cast_mut(), id);
                    }),
                    #[cfg(target_os = "ios")]
                    begin_edit: Box::new(move |_id| {
                        let _ = ctx_for_begin;
                    }),
                    #[cfg(target_os = "macos")]
                    set_param: Box::new(move |id, value| {
                        // One combined trait dispatch (set_normalized
                        // + get_plain) instead of two - the
                        // `#[derive(Params)]` impl can compute both in
                        // a single match-arm walk.
                        let plain =
                            f32::from_f64(params_for_set.set_normalized_returning_plain(id, value));
                        truce_au_v2_host_set_param(ctx_raw.as_ptr().cast_mut(), id, plain);
                    }),
                    #[cfg(target_os = "ios")]
                    set_param: Box::new(move |id, value| {
                        // No host-notify on iOS; just write the
                        // normalised value through. The Swift shim
                        // polls the parameter tree.
                        let _ = ctx_raw;
                        let _ = params_for_set.set_normalized_returning_plain(id, value);
                    }),
                    #[cfg(target_os = "macos")]
                    end_edit: Box::new(move |id| {
                        // Closes the gesture started by begin_edit so the
                        // host commits the undo group / stops automation
                        // recording.
                        truce_au_v2_host_end_param_gesture(ctx_for_end.as_ptr().cast_mut(), id);
                    }),
                    #[cfg(target_os = "ios")]
                    end_edit: Box::new(move |_id| {
                        let _ = ctx_for_end;
                    }),
                    request_resize: Box::new(move |w, h| {
                        // AU v2 has no host-driven resize API: the
                        // host observes the plug-in's NSView frame
                        // via AppKit and updates its container in
                        // response. So `ctx.request_resize` here
                        // routes back into the editor's own
                        // `set_size`, which resizes the baseview
                        // NSView; AppKit propagates the frame
                        // change to the host as a notification.
                        //
                        // SAFETY: `ctx_raw` points at the live
                        // `AuInstance<P>`. The closure runs on the
                        // GUI thread, same as `cb_gui_open` which
                        // installed it. `editor.set_size` on the
                        // existing backends writes to an atomic
                        // cell only - no aliasing UB even if the
                        // editor's own `update()` holds a borrow
                        // higher up the stack.
                        if w == 0 || h == 0 {
                            return false;
                        }
                        let inst = &mut *ctx_raw.as_ptr().cast_mut().cast::<AuInstance<P>>();
                        inst.editor.as_mut().is_some_and(|e| e.set_size(w, h))
                    }),
                    get_param: Box::new(move |id| params_for_get.get_normalized(id).unwrap_or(0.0)),
                    get_param_plain: Box::new(move |id| {
                        params_for_plain.get_plain(id).unwrap_or(0.0)
                    }),
                    format_param: Box::new(move |id| {
                        let plain = params_for_fmt.get_plain(id).unwrap_or(0.0);
                        params_for_fmt
                            .format_value(id, plain)
                            .unwrap_or_else(|| format!("{plain:.1}"))
                    }),
                    get_meter: Box::new(move |id| {
                        let plugin = plugin_ptr.get();
                        plugin.get_meter(id)
                    }),
                    get_state: Box::new(move || {
                        let plugin = plugin_ptr.get();
                        plugin.save_state()
                    }),
                    set_state: Box::new(move |bytes| {
                        // The editor sends RAW custom-state bytes -
                        // exactly what `save_state()` emits and
                        // `get_state` above returns - NOT a full
                        // `serialize_state` envelope. Route them to the
                        // plugin's `load_state` on the audio thread via
                        // the same handoff queue the host load path uses
                        // (the queue is what avoids aliasing
                        // `process()`'s `&mut plugin`). No params ride
                        // along: the editor mutates params through
                        // `set_param`.
                        let _ = pending_state_for_set.force_push(state::DeserializedState {
                            params: Vec::new(),
                            extra: Some(bytes),
                        });
                    }),
                    transport: Box::new(move || transport_slot.read()),
                },
                params_for_ctx,
            );
            #[cfg(target_os = "macos")]
            let handle = RawWindowHandle::AppKit(parent);
            #[cfg(target_os = "ios")]
            let handle = RawWindowHandle::UiKit(parent);
            editor.open(handle, context);
        }
    }
}

unsafe extern "C" fn cb_gui_close<P: PluginExport>(ctx: *mut std::ffi::c_void) {
    unsafe {
        let inst = &mut *ctx.cast::<AuInstance<P>>();
        if let Some(editor) = inst.editor.as_mut() {
            // Same boundary-protection as `cb_destroy`: any panic
            // during `editor.close()` (wgpu surface drop, baseview
            // window close, NSView removal) would otherwise cross
            // the FFI line and become an unhandled ObjC exception
            // in the host.
            let editor_ptr: *mut dyn truce_core::editor::Editor = editor.as_mut();
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                (*editor_ptr).close();
            }));
        }
        // Keep the editor alive - just closed, not dropped.
        //
        // Dropping the editor here would synchronously deallocate its
        // baseview NSWindow + content NSView. Logic / Pro Tools tend
        // to call `gui_close` from inside their own NSTimer fire or
        // a `[CALayer display]` callback, both of which run inside an
        // implicit autorelease pool that's about to pop. If
        // `[NSTimer invalidate]` (which baseview's drop chain calls
        // via `WindowHandle::drop`) re-enters that pool's pop
        // sequence, the host crashes inside `objc_release` on a
        // freed `NSAutoreleasePool*`. The editor's `close()` has
        // already released the NSView contents and Metal resources;
        // the lightweight Rust struct that survives is reopened
        // in-place by the next `gui_open` call.
    }
}

unsafe extern "C" {
    fn malloc(size: usize) -> *mut std::ffi::c_void;
    fn free(ptr: *mut std::ffi::c_void);
}

// AU v2 host-side automation notifiers: gated to macOS because v2 is
// macOS-only. iOS uses AU v3 exclusively, where host notification
// goes through the parameter tree directly.
#[cfg(target_os = "macos")]
unsafe extern "C" {
    fn truce_au_v2_host_set_param(ctx: *mut std::ffi::c_void, param_id: u32, value: f32);
    fn truce_au_v2_host_begin_param_gesture(ctx: *mut std::ffi::c_void, param_id: u32);
    fn truce_au_v2_host_end_param_gesture(ctx: *mut std::ffi::c_void, param_id: u32);
}

// ---------------------------------------------------------------------------
// Registration: called once from the export_au! macro
// ---------------------------------------------------------------------------

/// Register the plugin with the AU system. Must be called once at load time
/// (typically from a constructor function generated by `export_au!`).
/// Host-facing AU display name. Reads `truce.toml`'s `au_name`
/// (baked into `PluginInfo` by `truce::plugin_info!`), falling back
/// to `PluginInfo::name`. The v3 host gets its display name out of
/// the appex's `Info.plist` (`AUNAME`, populated by
/// `cargo truce install --au3` from `au3_name`), not from this
/// function - `g_descriptor->name` only feeds the v2 bridge's
/// internal scanning responses, so the same value works for both
/// build flavours.
fn resolved_plugin_name(info: &truce_core::info::PluginInfo) -> &'static str {
    truce_core::info::resolve_name_override(info.au_name, info.name)
}

pub fn register_au<P: PluginExport>() {
    // Called from the export macro's `extern "C" fn init()` static
    // initializer. Catch any panic so it doesn't cross the FFI
    // boundary and abort the host process.
    run_register::<P>("AU", || {
        let Some((num_inputs, num_outputs)) = default_io_channels::<P>() else {
            log_missing_bus_layout::<P>("AU");
            return;
        };
        register_au_inner::<P>(num_inputs, num_outputs);
    });
}

fn register_au_inner<P: PluginExport>(num_inputs: u32, num_outputs: u32) {
    let info = P::info();

    // Static metadata path: derive emits a `LazyLock`-cached
    // `Vec<ParamInfo>` so registration doesn't construct a plugin
    // instance just to read parameter shape. Hand-written
    // `PluginExport` impls without a `Params::param_infos_static`
    // override fall back to the historical
    // `Self::create().params().param_infos()` walk inside the trait
    // default - see `PluginExport::param_infos_static`.
    let param_infos = P::param_infos_static();
    let mut param_descs: Vec<AuParamDescriptor> = Vec::with_capacity(param_infos.len());

    for pi in &param_infos {
        let cs = truce_core::wrapper::ParamCStrings::from_info(pi);
        param_descs.push(AuParamDescriptor {
            id: pi.id,
            name: cs.name.into_raw(),
            min: pi.range.min(),
            max: pi.range.max(),
            default_value: pi.default_plain,
            step_count: pi.range.step_count().map_or(0, std::num::NonZero::get),
            unit: cs.unit.into_raw(),
            group: cs.group.into_raw(),
        });
    }

    let name = CString::new(resolved_plugin_name(&info)).unwrap_or_default();
    let vendor = CString::new(info.vendor).unwrap_or_default();

    let bypass_param_id = param_infos
        .iter()
        .find(|pi| pi.flags.contains(ParamFlags::IS_BYPASS))
        .map_or(u32::MAX, |pi| pi.id);

    // NoteEffect plugins (arpeggiators, chord generators) emit MIDI
    // back to the host. Instruments could in theory too but it's rare
    // and we don't want to advertise a "MIDI Out" port in every synth's
    // host UI without an explicit opt-in. Effects and analyzers never do.
    let has_midi_output = i32::from(matches!(info.category, PluginCategory::NoteEffect));

    let descriptor = Box::leak(Box::new(AuPluginDescriptor {
        component_type: info.au_type,
        component_subtype: info.fourcc,
        component_manufacturer: info.au_manufacturer,
        name: name.into_raw(),
        vendor: vendor.into_raw(),
        version: 0x0001_0000, // 1.0.0
        num_inputs,
        num_outputs,
        bypass_param_id,
        has_midi_output,
    }));

    let callbacks = Box::leak(Box::new(AuCallbacks {
        create: cb_create::<P>,
        destroy: cb_destroy::<P>,
        reset: cb_reset::<P>,
        process: cb_process::<P>,
        param_count: cb_param_count::<P>,
        param_get_value: cb_param_get_value::<P>,
        param_set_value: cb_param_set_value::<P>,
        param_format_value: cb_param_format_value::<P>,
        state_save: cb_state_save::<P>,
        state_load: cb_state_load::<P>,
        state_free: cb_state_free,
        output_event_count: cb_output_event_count::<P>,
        output_event_at: cb_output_event_at::<P>,
        output_sysex_count: cb_output_sysex_count::<P>,
        output_sysex_at: cb_output_sysex_at::<P>,
        gui_has_editor: cb_gui_has_editor::<P>,
        gui_get_size: cb_gui_get_size::<P>,
        gui_open: cb_gui_open::<P>,
        gui_close: cb_gui_close::<P>,
        gui_can_resize: cb_gui_can_resize::<P>,
        gui_set_size: cb_gui_set_size::<P>,
        factory_preset_count: cb_factory_preset_count::<P>,
        factory_preset_name: cb_factory_preset_name::<P>,
        factory_preset_load: cb_factory_preset_load::<P>,
    }));

    let param_descs = param_descs.leak();

    unsafe {
        ffi::truce_au_register(
            std::ptr::from_ref::<AuPluginDescriptor>(descriptor),
            std::ptr::from_ref::<AuCallbacks>(callbacks),
            param_descs.as_ptr(),
            len_u32(param_descs.len()),
        );
    }
}

// ---------------------------------------------------------------------------
// export_au! macro
// ---------------------------------------------------------------------------

/// Export an Audio Unit v3 plugin entry point.
///
/// Usage:
/// ```ignore
/// export_au!(MyPlugin);
/// ```
///
/// Where `MyPlugin` implements `PluginExport`.
#[macro_export]
macro_rules! export_au {
    ($plugin_type:ty) => {
        // macOS: register both AU v2 (`.component`) and AU v3 (`.appex`)
        // entry points. AU v2's factory delegates to the C shim.
        #[cfg(target_os = "macos")]
        mod _au_entry {
            use super::*;

            /// Called by the constructor to init the plugin.
            #[unsafe(no_mangle)]
            pub extern "C" fn truce_au_init() {
                ::truce_au::register_au::<$plugin_type>();
            }

            // AU v2 factory: delegates to au_v2_shim.c. The whole
            // `_au_entry` module is gated on `target_os = "macos"`
            // because v2 only exists on macOS, matching `build.rs`'s
            // `is_macos` gate on compiling au_v2_shim.c.
            unsafe extern "C" {
                fn truce_au_v2_factory_bridge(
                    desc: *const ::std::ffi::c_void,
                ) -> *mut ::std::ffi::c_void;
            }

            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn TruceAUFactory(
                desc: *const ::std::ffi::c_void,
            ) -> *mut ::std::ffi::c_void {
                truce_au_v2_factory_bridge(desc)
            }
        }
        // iOS: AU v3 only. The Swift `AudioUnitFactory` /
        // `TruceAUAudioUnit` in the .appex bundle reads our exported
        // globals (g_callbacks / g_descriptor / ...) at runtime via
        // the dynamic symbol table; we just need `truce_au_init` to
        // run from the dylib constructor.
        #[cfg(target_os = "ios")]
        mod _au_entry {
            use super::*;

            #[unsafe(no_mangle)]
            pub extern "C" fn truce_au_init() {
                ::truce_au::register_au::<$plugin_type>();
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use truce_core::SYSEX_POOL_PREALLOC;
    use truce_shim_types::AU_SHIM_TYPES_H;

    #[test]
    fn sysex_pool_prealloc_matches_header() {
        // The Swift AU v3 template (`AudioUnitFactory.swift`)
        // reads `TRUCE_SYSEX_POOL_PREALLOC` from `au_shim_types.h`
        // to size its per-render `sysexOutScratch`. Confirm the C
        // macro still expands to the same value as the Rust const
        // - otherwise the scratch is either undersized (event
        // drops) or wasteful (memory bloat per AU instance).
        let needle = format!("#define TRUCE_SYSEX_POOL_PREALLOC ({SYSEX_POOL_PREALLOC})");
        let needle_paren = format!(
            "#define TRUCE_SYSEX_POOL_PREALLOC ({} * 1024)",
            SYSEX_POOL_PREALLOC / 1024,
        );
        assert!(
            AU_SHIM_TYPES_H.contains(&needle) || AU_SHIM_TYPES_H.contains(&needle_paren),
            "au_shim_types.h::TRUCE_SYSEX_POOL_PREALLOC must equal \
             truce_core::SYSEX_POOL_PREALLOC ({} bytes / {} KiB). \
             Looked for `{}` or `{}` in the header.",
            SYSEX_POOL_PREALLOC,
            SYSEX_POOL_PREALLOC / 1024,
            needle,
            needle_paren,
        );
    }
}