atome 0.8.8

An async, `cpal`-based audio engine for Rust. `atome` gives you a small, composable API for building real-time audio applications — sample playback, mixing, routing, and DSP graphs — without wrestling with platform audio callbacks, device enumeration, or buffer management yourself.
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
//! Plugin hosting, one module per format.
//!
//! | Format   | Module       | Feature | Availability     |
//! |----------|--------------|---------|------------------|
//! | Internal | [`internal`] | —       | always           |
//! | VST 2.4  | [`vst`]      | `vst`   | no backend yet   |
//! | VST 3    | [`vst3`]     | `vst3`  | all platforms    |
//! | AU v2    | [`au`]       | `au`    | macOS / iOS only |
//! | AU v3    | [`au3`]      | `au3`   | macOS / iOS only |
//!
//! `plugins` turns on all of them at once.
//!
//! ```toml
//! atome = { version = "0.8.0", features = ["vst3", "au3"] }
//! ```
//!
//! [Internal plugins](internal) are behind no feature because there is nothing
//! to link against: they are Rust functions compiled into the host, and the
//! shortest path to a working chain. [`atome`] has a set already written —
//! compressor, delay, reverb, EQ, and the rest:
//!
//! ```
//! use ::atome::plugins::{atome, ParamError};
//!
//! let compressor = atome::compressor(48_000)
//!     .with_params("threshold_db: -18, ratio: 4, attack_ms: 5")?;
//! # Ok::<(), ParamError>(())
//! ```
//!
//! Or write one, when none of those is the thing:
//!
//! ```
//! use atome::plugins::Plugin;
//!
//! let quieter = Plugin::internal("-6 dB", |buffer: &mut [f32], _channels| {
//!     for sample in buffer {
//!         *sample *= 0.5;
//!     }
//! });
//! ```
//!
//! The hosted formats all take the same route: describe the plugin with
//! [`Plugin::new`], call [`Plugin::load`] once off the audio thread, then
//! [`Plugin::apply`] per block.
//!
//! # Parameters
//!
//! One vocabulary for every format — see [`params`]. A built-in matches names
//! against its own fields, a VST3 or AU against the parameter names the plugin
//! reports, and the call is the same either way:
//!
//! ```
//! use ::atome::plugins::{atome, ParamError};
//!
//! let mut reverb = atome::reverb(48_000);
//! reverb.set_params_str(r#"{ "room_size": 0.8, "mix": 0.25 }"#)?;
//!
//! // And back out again, in a form `set_params_str` reads.
//! let saved = reverb.params().to_string();
//! # Ok::<(), ParamError>(())
//! ```
//!
//! Which means a whole chain can be described by data rather than by code:
//! [`Plugin::new`] takes a parameter string, and [`Plugin::load`] applies it.
//!
//! # Where a plugin runs
//!
//! Attaching is separate from loading — see
//! [`AtomeDevice`](crate::device::AtomeDevice) and
//! [`AudioEngine`](crate::AudioEngine) for the three levels a chain can hang
//! off, and what each one hears.

use std::fmt;
use std::path::PathBuf;

use cpal::{Error, ErrorKind};

use crate::output::SampleType;

pub mod atome;
pub mod internal;
pub mod params;

#[cfg(all(feature = "au", target_vendor = "apple"))]
pub mod au;
#[cfg(all(feature = "au3", target_vendor = "apple"))]
pub mod au3;
#[cfg(feature = "vst")]
pub mod vst;
#[cfg(feature = "vst3")]
pub mod vst3;

// The shared hosting machinery — only worth compiling when there is a hosted
// format to use it.
#[cfg(any(
    feature = "vst3",
    all(any(feature = "au", feature = "au3"), target_vendor = "apple")
))]
mod host;

pub use atome::Effect;
pub use internal::InternalPlugin;
pub use params::{ParamError, ParamKind, ParamSpec, Params, Value};

/// Whether a hosted format is compiled into this build.
///
/// A feature can be on while the format is still unavailable — the AU features
/// resolve to nothing off Apple — so the module gates have to ask about the
/// platform too. This keeps that question phrased one way, in one place.
macro_rules! have {
    (au) => {
        cfg!(all(feature = "au", target_vendor = "apple"))
    };
    (au3) => {
        cfg!(all(feature = "au3", target_vendor = "apple"))
    };
    (vst3) => {
        cfg!(feature = "vst3")
    };
}

// -----------------------------------------------------------------------------
//  Plugin format
// -----------------------------------------------------------------------------

/// Which kind of plugin a [`Plugin`] describes.
///
/// Every variant exists in every build, whatever features are on. A format
/// this build cannot host is refused by [`Plugin::load`] with a message naming
/// the feature that would fix it — a better place to find out than a missing
/// enum variant at the call site, and it lets a configuration file name a
/// format the binary happens not to carry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PluginFormat {
    /// A Rust function compiled into the host. See [`internal`].
    Internal,
    /// Apple Audio Unit v2. Needs `au`, on macOS or iOS.
    Au,
    /// Apple Audio Unit v3 App Extension. Needs `au3`, on macOS or iOS.
    Au3,
    /// Steinberg VST 2.4. No backend — see [`vst`].
    Vst,
    /// Steinberg VST 3. Needs `vst3`.
    Vst3,
}

impl PluginFormat {
    /// Whether this build can actually load this format.
    ///
    /// [`Internal`](Self::Internal) is always true; the rest depend on the
    /// features the crate was built with and the platform it was built for.
    pub fn is_available(self) -> bool {
        match self {
            Self::Internal => true,
            Self::Au => have!(au),
            Self::Au3 => have!(au3),
            Self::Vst => false,
            Self::Vst3 => have!(vst3),
        }
    }

    /// Why this build cannot load this format, for the error message.
    fn unavailable(self) -> String {
        match self {
            Self::Internal => unreachable!("internal plugins are always available"),
            Self::Au => "AU v2 hosting needs the 'au' feature, on macOS or iOS".into(),
            Self::Au3 => "AU v3 hosting needs the 'au3' feature, on macOS or iOS".into(),
            Self::Vst => "VST 2.4 hosting is not implemented — there is no backend behind the \
                          'vst' feature. Use VST 3 ('vst3') instead."
                .into(),
            Self::Vst3 => "VST 3 hosting needs the 'vst3' feature".into(),
        }
    }
}

// -----------------------------------------------------------------------------
//  Loaded instance
// -----------------------------------------------------------------------------

/// The loaded plugin itself, once [`Plugin::load`] has been through.
enum PluginInner {
    Internal(InternalPlugin),
    #[cfg(all(feature = "au", target_vendor = "apple"))]
    Au(au::Loaded),
    // v3 loads into the same `AuPlugin` v2 does — see `au3`'s documentation —
    // so it needs a variant of its own only when `au` is not also on.
    #[cfg(all(feature = "au3", target_vendor = "apple", not(feature = "au")))]
    Au3(au3::Loaded),
    #[cfg(feature = "vst3")]
    Vst3(vst3::Loaded),
}

// -----------------------------------------------------------------------------
//  Plugin
// -----------------------------------------------------------------------------

/// A plugin, and the configuration it was prepared with.
///
/// Two halves: a descriptor you can build, store, and compare freely, and —
/// after [`load`](Self::load) — the loaded instance behind it. Where one is
/// attached decides what it hears; see
/// [`AtomeDevice`](crate::device::AtomeDevice) and
/// [`AudioEngine`](crate::AudioEngine).
pub struct Plugin {
    pub name: String,
    pub path: PathBuf,
    pub buffer_size: usize,
    pub sample_rate: usize,
    pub channels: usize,
    pub params: String,
    pub format: PluginFormat,
    /// `None` until [`Plugin::load`].
    inner: Option<PluginInner>,
}

impl Plugin {
    /// Describes a plugin without loading it.
    ///
    /// Nothing is opened, scanned, or instantiated here — call
    /// [`load`](Self::load) for that. `buffer_size`, `sample_rate`, and
    /// `channels` are what the plugin will be activated for, so they should
    /// match the stream it is going to sit in.
    pub fn new(
        name: String,
        path: PathBuf,
        buffer_size: usize,
        sample_rate: usize,
        channels: usize,
        params: String,
        format: PluginFormat,
    ) -> Self {
        Self {
            name,
            path,
            buffer_size,
            sample_rate,
            channels,
            params,
            format,
            inner: None,
        }
    }

    /// An [internal plugin](internal), already loaded.
    ///
    /// The direct route: there is nothing to scan for, so the function is the
    /// plugin and this is the whole of loading it.
    ///
    /// ```
    /// use atome::plugins::Plugin;
    ///
    /// let mut invert = Plugin::internal("invert", |buffer: &mut [f32], _channels| {
    ///     for sample in buffer {
    ///         *sample = -*sample;
    ///     }
    /// });
    ///
    /// let mut block = [0.5_f32, -0.25];
    /// invert.apply(&mut block, 2).unwrap();
    /// assert_eq!(block, [-0.5, 0.25]);
    /// ```
    pub fn internal<F>(name: impl Into<String>, process: F) -> Self
    where
        F: Fn(&mut [f32], u16) + Send + Sync + 'static,
    {
        Self::from_internal(InternalPlugin::new(name, process))
    }

    /// An [internal plugin](internal) built elsewhere — one that declares a
    /// latency through [`InternalPlugin::with_latency`], or one pulled out of
    /// the registry with [`internal::get`].
    pub fn from_internal(plugin: InternalPlugin) -> Self {
        Self {
            name: plugin.name().to_string(),
            path: PathBuf::new(),
            buffer_size: 0,
            sample_rate: 0,
            channels: 0,
            params: String::new(),
            format: PluginFormat::Internal,
            inner: Some(PluginInner::Internal(plugin)),
        }
    }

    /// Whether [`load`](Self::load) has been through successfully.
    ///
    /// An unloaded plugin is not an error to [`apply`](Self::apply) — it
    /// passes audio through untouched — so this is how you check that a chain
    /// is doing what you think it is.
    pub fn is_loaded(&self) -> bool {
        self.inner.is_some()
    }

    /// Loads the plugin.
    ///
    /// For an internal plugin this resolves `name` against [`internal`]'s
    /// registry. For the hosted formats it scans `path`, instantiates what it
    /// finds, and activates it for this descriptor's `channels`,
    /// `sample_rate`, and `buffer_size`.
    ///
    /// Does nothing if the plugin is already loaded.
    ///
    /// **Not for the audio thread.** Scanning walks the filesystem, loading
    /// opens dylibs, and activation allocates — seconds, in the worst case.
    ///
    /// # Errors
    ///
    /// - The format is not one this build can host — see
    ///   [`PluginFormat::is_available`]
    /// - [`PluginFormat::Internal`] and nothing is registered under `name`
    /// - No plugin of that format at `path`, or it will not load
    /// - The plugin has no bus layout carrying `channels` channels in and out
    pub fn load(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if self.inner.is_some() {
            return Ok(());
        }

        let format = self.detect_format();

        if !format.is_available() {
            return Err(format.unavailable().into());
        }

        self.inner = Some(match format {
            // The registry first, so registering a name shadows a built-in of
            // the same one rather than the other way round: a caller who
            // registers "compressor" meant theirs.
            PluginFormat::Internal => {
                let plugin = match internal::get(&self.name) {
                    Some(plugin) => plugin,
                    None => {
                        let built_in = atome::create(
                            &self.name,
                            self.sample_rate as u32,
                            &Params::new(),
                        )
                        .map_err(|_| {
                            format!(
                                "'{}' is neither a registered internal plugin nor one of the \
                                 built-ins ({}). Register one with \
                                 atome::plugins::internal::register, or build it directly with \
                                 Plugin::internal",
                                self.name,
                                atome::kinds().join(", "),
                            )
                        })?;

                        // `create` hands back a loaded `Plugin`; this needs the
                        // instance out of it.
                        match built_in.inner {
                            Some(PluginInner::Internal(plugin)) => plugin,
                            _ => unreachable!("a built-in is always an internal plugin"),
                        }
                    }
                };

                PluginInner::Internal(plugin)
            }

            #[cfg(all(feature = "au", target_vendor = "apple"))]
            PluginFormat::Au => PluginInner::Au(au::load(
                &self.path,
                self.channels,
                self.sample_rate as f64,
                self.buffer_size,
            )?),

            // With `au` on, a v3 load produces the same `AuPlugin` and so goes
            // into the same variant.
            #[cfg(all(feature = "au3", target_vendor = "apple", feature = "au"))]
            PluginFormat::Au3 => PluginInner::Au(au3::load(
                &self.path,
                self.channels,
                self.sample_rate as f64,
                self.buffer_size,
            )?),
            #[cfg(all(feature = "au3", target_vendor = "apple", not(feature = "au")))]
            PluginFormat::Au3 => PluginInner::Au3(au3::load(
                &self.path,
                self.channels,
                self.sample_rate as f64,
                self.buffer_size,
            )?),

            #[cfg(feature = "vst3")]
            PluginFormat::Vst3 => PluginInner::Vst3(vst3::load(
                &self.path,
                self.channels,
                self.sample_rate as f64,
                self.buffer_size,
            )?),

            // Everything `is_available` lets through is handled above. This
            // arm catches the formats it does not, which the check has already
            // returned for — so reaching it would be a bug in that pairing.
            #[allow(unreachable_patterns)]
            other => return Err(other.unavailable().into()),
        });

        // The descriptor's own parameters, now that there is something to
        // apply them to. Last, so a plugin that loads but will not take its
        // parameters reports that rather than a loading failure.
        if !self.params.trim().is_empty() {
            let params = Params::parse(&self.params)?;
            self.set_params(&params)?;
        }

        Ok(())
    }

    /// Works out what format to load, from the descriptor or from the path.
    ///
    /// A format stated explicitly is taken at its word. [`Internal`] is the
    /// one that gets second-guessed, since it is also the variant a caller
    /// falls into without meaning to: when the descriptor says `Internal` but
    /// carries a path that looks like a plugin bundle, the path wins.
    ///
    /// [`Internal`]: PluginFormat::Internal
    fn detect_format(&self) -> PluginFormat {
        if self.format != PluginFormat::Internal {
            return self.format;
        }

        // A bundle is a directory whose *name* ends in the suffix, so match on
        // the name rather than on `extension()` — which answers the same for a
        // file and for a directory, and is not what tells them apart.
        let name = self
            .path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();

        if name.ends_with(".vst3") {
            PluginFormat::Vst3
        } else if name.ends_with(".component") {
            PluginFormat::Au
        } else if name.ends_with(".appex") {
            PluginFormat::Au3
        } else {
            // Nothing bundle-shaped to go on, so the descriptor meant what it
            // said: an internal plugin, to be looked up by name.
            PluginFormat::Internal
        }
    }

    // -------------------------------------------------------------------------
    //  Audio processing
    // -------------------------------------------------------------------------

    /// Runs one block through the plugin, in place.
    ///
    /// `buffer` is interleaved by `channels`. An unloaded plugin passes the
    /// audio through untouched rather than failing — a chain holding a plugin
    /// that never loaded should be quiet about it in the callback, not stop
    /// the stream.
    ///
    /// # Errors
    ///
    /// - `buffer` is not a whole number of `channels`-wide frames
    /// - `channels` is not what the plugin was loaded and activated for
    /// - The plugin itself failed on the block
    pub fn apply<S: SampleType>(&mut self, buffer: &mut [S], channels: u16) -> Result<(), Error> {
        let Some(inner) = &mut self.inner else {
            return Ok(());
        };

        match inner {
            PluginInner::Internal(plugin) => apply_internal(plugin, buffer, channels),

            #[cfg(all(feature = "au", target_vendor = "apple"))]
            PluginInner::Au(plugin) => plugin.process(buffer, channels).map_err(host_error),
            #[cfg(all(feature = "au3", target_vendor = "apple", not(feature = "au")))]
            PluginInner::Au3(plugin) => plugin.process(buffer, channels).map_err(host_error),
            #[cfg(feature = "vst3")]
            PluginInner::Vst3(plugin) => plugin.process(buffer, channels).map_err(host_error),
        }
    }

    /// The delay this plugin introduces, in frames.
    ///
    /// Needed for delay compensation: a chain that delays one route and not
    /// another puts them out of phase with each other.
    ///
    /// Internal plugins report what they declared through
    /// [`InternalPlugin::with_latency`], or what their [`Effect`] reports. The
    /// hosted formats report zero — `truce-rack-core` exposes no latency on its
    /// plugin traits, so there is nothing to ask. Read a zero from a VST3 or an
    /// AU as "not implemented", not as "no delay".
    pub fn latency(&self) -> usize {
        match &self.inner {
            Some(PluginInner::Internal(plugin)) => plugin.latency(),
            _ => 0,
        }
    }

    // -------------------------------------------------------------------------
    //  Parameters
    // -------------------------------------------------------------------------

    /// What parameters this plugin has, and what they accept.
    ///
    /// Empty for a plugin that is not loaded, and for one built from a bare
    /// closure — a closure has no parameters to describe. A
    /// [built-in](atome) describes its own; a hosted plugin's comes from the
    /// format, with the names it uses in its own UI.
    ///
    /// Hosted ranges are the plugin's native units where the format reports
    /// them, so a VST3 that thinks in `0.0..=1.0` is described that way rather
    /// than being scaled to something more readable.
    pub fn param_schema(&self) -> Vec<ParamSpec> {
        match &self.inner {
            None => Vec::new(),
            Some(PluginInner::Internal(plugin)) => {
                plugin.effect().map(Effect::schema).unwrap_or_default()
            }

            #[cfg(all(feature = "au", target_vendor = "apple"))]
            Some(PluginInner::Au(plugin)) => plugin.param_schema(),
            #[cfg(all(feature = "au3", target_vendor = "apple", not(feature = "au")))]
            Some(PluginInner::Au3(plugin)) => plugin.param_schema(),
            #[cfg(feature = "vst3")]
            Some(PluginInner::Vst3(plugin)) => plugin.param_schema(),
        }
    }

    /// Every parameter's current value.
    ///
    /// The output round-trips: `plugin.set_params(&plugin.params())` is a no-op,
    /// and `plugin.params().to_string()` is a parameter string
    /// [`set_params_str`](Self::set_params_str) will read back. That is what
    /// makes saving a chain's settings to a file a two-line job.
    pub fn params(&self) -> Params {
        match &self.inner {
            None => Params::new(),
            Some(PluginInner::Internal(plugin)) => {
                plugin.effect().map(atome::params_of).unwrap_or_default()
            }

            #[cfg(all(feature = "au", target_vendor = "apple"))]
            Some(PluginInner::Au(plugin)) => plugin.params(),
            #[cfg(all(feature = "au3", target_vendor = "apple", not(feature = "au")))]
            Some(PluginInner::Au3(plugin)) => plugin.params(),
            #[cfg(feature = "vst3")]
            Some(PluginInner::Vst3(plugin)) => plugin.params(),
        }
    }

    /// Sets parameters by name.
    ///
    /// The same call whatever the plugin is: a [built-in](atome) matches the
    /// names against its own fields, a hosted plugin against the parameter
    /// names the format reports.
    ///
    /// Not for the audio thread — it is not slow, but nothing guarantees a
    /// hosted plugin's own `set_parameter` is lock-free.
    ///
    /// # Errors
    ///
    /// - [`ParamError::Unknown`] for a name the plugin does not have. The
    ///   message lists the names it does.
    /// - [`ParamError::Type`] or [`ParamError::Range`] for a value it will not
    ///   take.
    /// - [`ParamError::Unsupported`] if the plugin is not loaded — there is
    ///   nothing to set parameters on until it is.
    ///
    /// All or nothing: every name and value is checked before any of them is
    /// written, so a set naming one parameter the plugin does not have leaves
    /// the rest untouched rather than applying half of them.
    pub fn set_params(&mut self, params: &Params) -> Result<(), ParamError> {
        match &mut self.inner {
            None => {
                if params.is_empty() {
                    return Ok(());
                }
                Err(ParamError::Unsupported {
                    message: format!(
                        "'{}' is not loaded, so it has no parameters to set — call load() first",
                        self.name
                    ),
                })
            }

            Some(PluginInner::Internal(plugin)) => match plugin.effect_mut() {
                Some(effect) => atome::apply(effect, params),
                None if params.is_empty() => Ok(()),
                None => Err(ParamError::Unsupported {
                    message: format!(
                        "'{}' is a plain function, which has no parameters. Build it from an \
                         Effect — see atome::plugins::atome — if it needs them",
                        self.name
                    ),
                }),
            },

            #[cfg(all(feature = "au", target_vendor = "apple"))]
            Some(PluginInner::Au(plugin)) => plugin.set_params(params),
            #[cfg(all(feature = "au3", target_vendor = "apple", not(feature = "au")))]
            Some(PluginInner::Au3(plugin)) => plugin.set_params(params),
            #[cfg(feature = "vst3")]
            Some(PluginInner::Vst3(plugin)) => plugin.set_params(params),
        }
    }

    /// Sets one parameter.
    ///
    /// ```
    /// use ::atome::plugins::{atome, ParamError};
    ///
    /// let mut compressor = atome::compressor(48_000);
    /// compressor.set_param("ratio", 8.0)?;
    /// compressor.set_param("threshold_db", -24)?;
    /// # Ok::<(), ParamError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// As [`set_params`](Self::set_params).
    pub fn set_param(
        &mut self,
        key: &str,
        value: impl Into<Value>,
    ) -> Result<(), ParamError> {
        self.set_params(&Params::new().with(key, value))
    }

    /// Sets parameters from a [parameter string](params).
    ///
    /// ```
    /// use ::atome::plugins::{atome, ParamError};
    ///
    /// let mut delay = atome::delay(48_000);
    /// delay.set_params_str(r#"{ "time_ms": 375, "feedback": 0.4 }"#)?;
    /// # Ok::<(), ParamError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`ParamError::Syntax`] if the string will not parse, then as
    /// [`set_params`](Self::set_params).
    pub fn set_params_str(&mut self, params: &str) -> Result<(), ParamError> {
        self.set_params(&Params::parse(params)?)
    }

    /// Sets parameters and returns `self`, for building a chain inline.
    ///
    /// ```
    /// use ::atome::plugins::{atome, ParamError};
    ///
    /// let chain = vec![
    ///     atome::gate(48_000).with_params("threshold_db: -45")?,
    ///     atome::compressor(48_000).with_params("ratio: 4, threshold_db: -18")?,
    ///     atome::limiter(48_000).with_params("ceiling_db: -1")?,
    /// ];
    /// # Ok::<(), ParamError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// As [`set_params_str`](Self::set_params_str).
    pub fn with_params(mut self, params: &str) -> Result<Self, ParamError> {
        self.set_params_str(params)?;
        Ok(self)
    }

    /// Drops whatever state the plugin has built up, leaving its parameters.
    ///
    /// A delay's line, a filter's history, a compressor's envelope. Worth doing
    /// when a chain is reused for unrelated audio, so the last of the previous
    /// material does not ring into the new.
    ///
    /// Only [built-ins](atome) answer this. A plugin built from a closure keeps
    /// any state inside the closure where this cannot reach, and the hosted
    /// formats expose no reset short of deactivating.
    pub fn reset(&mut self) {
        if let Some(PluginInner::Internal(plugin)) = &mut self.inner {
            plugin.reset();
        }
    }
}

/// Runs an internal plugin, converting to `f32` and back when the engine is
/// not already running in it.
///
/// The scratch buffer is the cost of the type erasure that lets one boxed
/// function serve every sample type — see [`internal::ProcessFn`]. It is
/// allocated per block, which is an allocation on the audio thread and the
/// one thing here that is not yet good enough for a small buffer.
fn apply_internal<S: SampleType>(
    plugin: &mut InternalPlugin,
    buffer: &mut [S],
    channels: u16,
) -> Result<(), Error> {
    if channels == 0 || buffer.len() % channels as usize != 0 {
        return Err(Error::with_message(
            ErrorKind::InvalidInput,
            format!(
                "{} samples is not a whole number of {channels}-channel frames",
                buffer.len()
            ),
        ));
    }

    let mut scratch: Vec<f32> = buffer.iter().map(|sample| sample.to_f32()).collect();
    plugin.process(&mut scratch, channels);

    for (sample, processed) in buffer.iter_mut().zip(scratch) {
        *sample = S::from_f32(processed);
    }

    Ok(())
}

/// Turns a backend error into the `cpal::Error` the engine speaks.
///
/// The chain runs inside the stream's own error type, so a plugin failure has
/// to arrive as one of those. The backend's own message is carried through
/// whole — it is the only part that says what actually went wrong.
#[cfg(any(
    feature = "vst3",
    all(any(feature = "au", feature = "au3"), target_vendor = "apple")
))]
fn host_error(error: truce_rack_core::error::Error) -> Error {
    Error::with_message(ErrorKind::BackendError, error.to_string())
}

// -----------------------------------------------------------------------------
//  Descriptor-only traits
// -----------------------------------------------------------------------------

/// Clones the descriptor. What happens to the loaded instance depends on what
/// it is, and the difference is not worth hiding:
///
/// - An [internal plugin](internal) is a shared function, so the clone comes
///   back loaded too, running that same function.
/// - A hosted plugin is a live handle on a dylib or an XPC connection. A
///   second one of those has no sound meaning, so the clone comes back
///   unloaded and needs its own [`load`](Plugin::load).
///
/// `Clone` exists at all because [`AtomeDevice`](crate::device::AtomeDevice)
/// derives it and carries a plugin chain.
impl Clone for Plugin {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            path: self.path.clone(),
            buffer_size: self.buffer_size,
            sample_rate: self.sample_rate,
            channels: self.channels,
            params: self.params.clone(),
            format: self.format,
            inner: match &self.inner {
                Some(PluginInner::Internal(plugin)) => Some(PluginInner::Internal(plugin.clone())),
                _ => None,
            },
        }
    }
}

impl fmt::Debug for Plugin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Plugin")
            .field("name", &self.name)
            .field("path", &self.path)
            .field("buffer_size", &self.buffer_size)
            .field("sample_rate", &self.sample_rate)
            .field("channels", &self.channels)
            .field("params", &self.params)
            .field("format", &self.format)
            .field("loaded", &self.is_loaded())
            .finish()
    }
}

/// Compares descriptors, not instances.
///
/// Two plugins are equal when they describe the same plugin. The loaded
/// instance is a consequence of the descriptor, and a `dyn Fn` has no equality
/// to offer in any case — so a plugin equals its freshly-loaded self, which is
/// what makes this useful for finding one in a chain.
impl PartialEq for Plugin {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.path == other.path
            && self.buffer_size == other.buffer_size
            && self.sample_rate == other.sample_rate
            && self.channels == other.channels
            && self.params == other.params
            && self.format == other.format
    }
}

impl Eq for Plugin {}

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

    fn descriptor(name: &str, format: PluginFormat) -> Plugin {
        Plugin::new(
            name.into(),
            PathBuf::new(),
            512,
            48_000,
            2,
            String::new(),
            format,
        )
    }

    #[test]
    fn an_unloaded_plugin_passes_audio_through() {
        let mut plugin = descriptor("never loaded", PluginFormat::Vst3);
        let mut buffer = [0.25_f32, -0.5];

        plugin.apply(&mut buffer, 2).expect("pass-through");

        assert_eq!(buffer, [0.25, -0.5]);
        assert!(!plugin.is_loaded());
    }

    #[test]
    fn internal_plugins_are_loaded_on_construction() {
        let plugin = Plugin::internal("gain", |_: &mut [f32], _| {});
        assert!(plugin.is_loaded());
        assert_eq!(plugin.format, PluginFormat::Internal);
    }

    #[test]
    fn applies_to_a_non_float_engine() {
        // i16 in, i16 out, with the plugin seeing f32 in between.
        let mut plugin = Plugin::internal("silence", |buffer: &mut [f32], _| {
            buffer.fill(0.0);
        });

        let mut buffer = [i16::MAX, i16::MIN, 1234];
        plugin.apply(&mut buffer, 1).expect("processed");

        assert_eq!(buffer, [0, 0, 0]);
    }

    #[test]
    fn round_trips_a_float_engine_untouched() {
        let mut plugin = Plugin::internal("noop", |_: &mut [f32], _| {});

        let mut buffer = [0.123_f32, -0.789, 1.0, -1.0];
        let before = buffer;
        plugin.apply(&mut buffer, 2).expect("processed");

        assert_eq!(buffer, before);
    }

    #[test]
    fn the_plugin_sees_the_interleaving_it_was_told_about() {
        let mut plugin = Plugin::internal("right only", |buffer: &mut [f32], channels| {
            for frame in buffer.chunks_mut(channels as usize) {
                frame[0] = 0.0;
            }
        });

        let mut buffer = [1.0_f32, 1.0, 1.0, 1.0];
        plugin.apply(&mut buffer, 2).expect("processed");

        assert_eq!(buffer, [0.0, 1.0, 0.0, 1.0]);
    }

    #[test]
    fn refuses_a_partial_frame() {
        let mut plugin = Plugin::internal("noop", |_: &mut [f32], _| {});

        // Three samples cannot be a whole number of stereo frames.
        let mut buffer = [0.0_f32; 3];
        assert!(plugin.apply(&mut buffer, 2).is_err());
    }

    #[test]
    fn refuses_zero_channels() {
        let mut plugin = Plugin::internal("noop", |_: &mut [f32], _| {});
        let mut buffer = [0.0_f32; 4];
        assert!(plugin.apply(&mut buffer, 0).is_err());
    }

    #[test]
    fn loads_an_internal_plugin_by_name() {
        internal::register("load by name", |buffer: &mut [f32], _| buffer.fill(1.0));

        let mut plugin = descriptor("load by name", PluginFormat::Internal);
        assert!(!plugin.is_loaded());
        plugin.load().expect("registered");
        assert!(plugin.is_loaded());

        let mut buffer = [0.0_f32; 2];
        plugin.apply(&mut buffer, 2).expect("processed");
        assert_eq!(buffer, [1.0, 1.0]);

        internal::unregister("load by name");
    }

    #[test]
    fn an_unregistered_name_is_an_error() {
        let mut plugin = descriptor("nothing registered under this", PluginFormat::Internal);
        let error = plugin.load().expect_err("not registered");
        let message = error.to_string();

        assert!(message.contains("nothing registered under this"), "{message}");
        // And it says what the built-ins are, since one of them is the likely
        // thing that was meant.
        assert!(message.contains("compressor"), "{message}");
    }

    #[test]
    fn a_built_in_loads_by_name() {
        let mut plugin = descriptor("compressor", PluginFormat::Internal);
        plugin.load().expect("compressor is a built-in");

        assert!(plugin.is_loaded());
        assert_eq!(plugin.params().number("ratio"), Some(4.0));
    }

    #[test]
    fn a_registered_name_shadows_a_built_in() {
        internal::register("reverb", |buffer: &mut [f32], _| buffer.fill(0.25));

        let mut plugin = descriptor("reverb", PluginFormat::Internal);
        plugin.load().expect("registered");

        // The registered function, not the built-in reverb.
        let mut buffer = [0.0_f32; 4];
        plugin.apply(&mut buffer, 2).expect("processes");
        assert_eq!(buffer, [0.25; 4]);

        internal::unregister("reverb");
    }

    #[test]
    fn the_descriptors_parameters_are_applied_on_load() {
        let mut plugin = Plugin::new(
            "delay".into(),
            PathBuf::new(),
            512,
            48_000,
            2,
            r#"{ "time_ms": 375, "feedback": 0.6 }"#.into(),
            PluginFormat::Internal,
        );

        plugin.load().expect("a built-in with parameters");

        assert_eq!(plugin.params().number("time_ms"), Some(375.0));
    }

    #[test]
    fn bad_parameters_in_the_descriptor_fail_the_load() {
        let mut plugin = Plugin::new(
            "delay".into(),
            PathBuf::new(),
            512,
            48_000,
            2,
            "time_ms: 999999".into(),
            PluginFormat::Internal,
        );

        let error = plugin.load().expect_err("999999 ms is outside the range");
        assert!(error.to_string().contains("time_ms"), "{error}");
    }

    #[test]
    fn a_plain_function_has_no_parameters_to_set() {
        let mut plugin = Plugin::internal("noop", |_: &mut [f32], _| {});

        assert!(plugin.params().is_empty());
        assert!(plugin.param_schema().is_empty());

        // Setting none of them is fine; setting one is not.
        assert!(plugin.set_params(&Params::new()).is_ok());
        assert!(matches!(
            plugin.set_param("anything", 1.0),
            Err(ParamError::Unsupported { .. })
        ));
    }

    #[test]
    fn an_unloaded_plugin_has_nothing_to_set_parameters_on() {
        let mut plugin = descriptor("not loaded", PluginFormat::Vst3);

        assert!(plugin.params().is_empty());
        assert!(matches!(
            plugin.set_param("ratio", 4.0),
            Err(ParamError::Unsupported { .. })
        ));
    }

    #[test]
    fn parameters_round_trip_through_a_string() {
        let mut original = atome::reverb(48_000);
        original
            .set_params_str("room_size: 0.8, damping: 0.3, mix: 0.45")
            .expect("valid");

        // What `params()` prints is what `set_params_str` reads, which is what
        // makes saving a chain to a file a two-line job.
        let saved = original.params().to_string();

        let mut restored = atome::reverb(48_000);
        restored.set_params_str(&saved).expect("its own output");

        assert_eq!(restored.params(), original.params(), "saved as {saved}");
    }

    #[test]
    fn loading_twice_is_a_no_op() {
        internal::register("loaded twice", |_: &mut [f32], _| {});

        let mut plugin = descriptor("loaded twice", PluginFormat::Internal);
        plugin.load().expect("first");
        plugin.load().expect("second");

        internal::unregister("loaded twice");
    }

    #[test]
    fn a_declared_latency_reaches_the_engine() {
        let lookahead = InternalPlugin::new("lookahead", |_: &mut [f32], _| {}).with_latency(128);
        assert_eq!(Plugin::from_internal(lookahead).latency(), 128);

        // Nothing loaded means nothing delayed.
        assert_eq!(descriptor("unloaded", PluginFormat::Vst3).latency(), 0);
    }

    #[test]
    fn cloning_keeps_an_internal_plugin_working() {
        let plugin = Plugin::internal("shared", |buffer: &mut [f32], _| buffer.fill(0.5));
        let mut clone = plugin.clone();

        assert!(clone.is_loaded());

        let mut buffer = [0.0_f32; 2];
        clone.apply(&mut buffer, 2).expect("processed");
        assert_eq!(buffer, [0.5, 0.5]);
    }

    #[test]
    fn equality_ignores_whether_a_plugin_is_loaded() {
        internal::register("compared", |_: &mut [f32], _| {});

        let unloaded = descriptor("compared", PluginFormat::Internal);
        let mut loaded = unloaded.clone();
        loaded.load().expect("registered");

        assert_eq!(unloaded, loaded);

        internal::unregister("compared");
    }

    #[test]
    fn a_path_overrides_a_defaulted_internal_format() {
        let plugin = Plugin::new(
            "Pro-Q".into(),
            "/Library/Audio/Plug-Ins/VST3/Pro-Q 3.vst3".into(),
            512,
            48_000,
            2,
            String::new(),
            PluginFormat::Internal,
        );

        assert_eq!(plugin.detect_format(), PluginFormat::Vst3);
    }

    #[test]
    fn bundle_suffixes_map_to_their_formats() {
        for (path, expected) in [
            ("/x/Thing.vst3", PluginFormat::Vst3),
            ("/x/Thing.component", PluginFormat::Au),
            ("/x/Thing.appex", PluginFormat::Au3),
            ("/x/Thing", PluginFormat::Internal),
        ] {
            let plugin = Plugin::new(
                "Thing".into(),
                path.into(),
                512,
                48_000,
                2,
                String::new(),
                PluginFormat::Internal,
            );
            assert_eq!(plugin.detect_format(), expected, "{path}");
        }
    }

    #[test]
    fn an_explicit_format_is_taken_at_its_word() {
        // A `.vst3` path does not make this anything other than the AU it says
        // it is.
        let plugin = Plugin::new(
            "Thing".into(),
            "/x/Thing.vst3".into(),
            512,
            48_000,
            2,
            String::new(),
            PluginFormat::Au,
        );

        assert_eq!(plugin.detect_format(), PluginFormat::Au);
    }

    #[test]
    fn internal_is_available_everywhere() {
        assert!(PluginFormat::Internal.is_available());
    }

    #[test]
    fn vst2_is_never_available() {
        // The feature exists; the backend does not. Loading says so, rather
        // than failing somewhere less obvious.
        assert!(!PluginFormat::Vst.is_available());

        let mut plugin = descriptor("some vst2", PluginFormat::Vst);
        let error = plugin.load().expect_err("no VST2 backend");
        assert!(error.to_string().contains("not implemented"));
    }

    #[test]
    fn an_unavailable_format_names_its_feature() {
        for format in [PluginFormat::Au, PluginFormat::Au3, PluginFormat::Vst3] {
            if format.is_available() {
                continue;
            }

            let mut plugin = descriptor("absent", format);
            let error = plugin.load().expect_err("feature is off");
            let message = error.to_string();

            assert!(
                message.contains("feature"),
                "{format:?} should say which feature is missing, said: {message}"
            );
        }
    }
}