quiver-dsp 0.1.0

A modular audio synthesis library using Arrow-style combinators and graph-based patching
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
//! Preset Library
//!
//! This module provides a collection of ready-to-use patch presets:
//! - Classic synth patches (bass, lead, pad, etc.)
//! - Sound design examples
//! - Tutorial patches for learning
//!
//! # Example
//!
//! ```
//! use quiver::prelude::*;
//!
//! let library = PresetLibrary::new();
//!
//! // List all presets
//! for preset in PresetLibrary::list() {
//!     println!("{}: {}", preset.name, preset.description);
//! }
//!
//! // Search by tags
//! let acid = library.search_tags(&["acid"]);
//! assert!(!acid.is_empty());
//!
//! // Get and build a preset
//! let patch = library.get("Moog Bass").unwrap().build(44100.0).unwrap();
//! assert!(patch.node_count() > 0);
//! ```

use crate::graph::Patch;
use crate::serialize::{CableDef, ModuleDef, ModuleRegistry, PatchDef};
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

/// Preset category for organization
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PresetCategory {
    /// Classic synthesizer sounds
    Classic,
    /// Sound design and experimental
    SoundDesign,
    /// Educational/tutorial patches
    Tutorial,
    /// Bass sounds
    Bass,
    /// Lead sounds
    Lead,
    /// Pad/ambient sounds
    Pad,
    /// Percussion/drums
    Percussion,
    /// Effects and processing
    Effect,
}

/// Preset metadata
#[derive(Debug, Clone)]
pub struct PresetInfo {
    /// Preset name
    pub name: String,
    /// Category
    pub category: PresetCategory,
    /// Description
    pub description: String,
    /// Tags for searching
    pub tags: Vec<String>,
    /// Difficulty level (1-5, for tutorials)
    pub difficulty: Option<u8>,
}

impl PresetInfo {
    pub fn new(name: impl Into<String>, category: PresetCategory) -> Self {
        Self {
            name: name.into(),
            category,
            description: String::new(),
            tags: Vec::new(),
            difficulty: None,
        }
    }

    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    pub fn with_difficulty(mut self, level: u8) -> Self {
        self.difficulty = Some(level.min(5));
        self
    }
}

/// Error type for preset operations
#[derive(Debug, Clone)]
pub enum PresetError {
    /// Preset not found
    NotFound(String),
    /// Failed to build patch from preset
    BuildError(String),
}

impl core::fmt::Display for PresetError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            PresetError::NotFound(name) => write!(f, "Preset not found: {}", name),
            PresetError::BuildError(msg) => write!(f, "Failed to build preset: {}", msg),
        }
    }
}

/// A buildable preset that can be converted into a Patch
#[derive(Debug, Clone)]
pub struct Preset {
    /// Preset metadata
    pub info: PresetInfo,
    /// Patch definition
    pub def: PatchDef,
}

impl Preset {
    /// Build the preset into a ready-to-use Patch
    ///
    /// # Arguments
    /// * `sample_rate` - The sample rate for the patch (e.g., 44100.0)
    ///
    /// # Returns
    /// A compiled Patch ready for audio processing
    ///
    /// # Example
    /// ```
    /// use quiver::prelude::*;
    ///
    /// let library = PresetLibrary::new();
    /// let preset = library.get("Moog Bass").unwrap();
    /// let patch = preset.build(44100.0).unwrap();
    /// assert!(patch.node_count() > 0);
    /// ```
    pub fn build(self, sample_rate: f64) -> Result<Patch, PresetError> {
        let registry = ModuleRegistry::new();
        Patch::from_def(&self.def, &registry, sample_rate)
            .map_err(|e| PresetError::BuildError(e.to_string()))
    }

    /// Build the preset with a custom module registry
    ///
    /// Use this when you have custom modules registered.
    pub fn build_with_registry(
        self,
        sample_rate: f64,
        registry: &ModuleRegistry,
    ) -> Result<Patch, PresetError> {
        Patch::from_def(&self.def, registry, sample_rate)
            .map_err(|e| PresetError::BuildError(e.to_string()))
    }

    /// Get the patch definition without building
    pub fn into_def(self) -> PatchDef {
        self.def
    }
}

/// Preset library containing all available presets
#[derive(Debug, Clone, Default)]
pub struct PresetLibrary {
    _private: (),
}

impl PresetLibrary {
    /// Create a new preset library instance
    ///
    /// # Example
    /// ```
    /// use quiver::prelude::*;
    ///
    /// let _library = PresetLibrary::new();
    /// for preset in PresetLibrary::list() {
    ///     println!("{}", preset.name);
    /// }
    /// ```
    pub fn new() -> Self {
        Self { _private: () }
    }

    /// Get a preset by name, ready to build
    ///
    /// # Example
    /// ```
    /// use quiver::prelude::*;
    ///
    /// let library = PresetLibrary::new();
    /// if let Some(preset) = library.get("Moog Bass") {
    ///     let patch = preset.build(44100.0).unwrap();
    ///     assert!(patch.node_count() > 0);
    /// }
    /// ```
    pub fn get(&self, name: &str) -> Option<Preset> {
        let info = Self::all_presets().into_iter().find(|p| p.name == name)?;
        let def = Self::load(name)?;
        Some(Preset { info, def })
    }

    /// Search presets by multiple tags (matches any)
    ///
    /// Returns presets that match ANY of the provided tags.
    ///
    /// # Example
    /// ```
    /// use quiver::prelude::*;
    ///
    /// let library = PresetLibrary::new();
    /// let acid_or_bass = library.search_tags(&["acid", "bass"]);
    /// assert!(!acid_or_bass.is_empty());
    /// ```
    pub fn search_tags(&self, tags: &[&str]) -> Vec<PresetInfo> {
        Self::all_presets()
            .into_iter()
            .filter(|p| {
                tags.iter().any(|search_tag| {
                    let search_lower = search_tag.to_lowercase();
                    p.tags
                        .iter()
                        .any(|t| t.to_lowercase().contains(&search_lower))
                })
            })
            .collect()
    }

    // Internal helper to get all preset infos
    fn all_presets() -> Vec<PresetInfo> {
        vec![
            // Classic patches
            PresetInfo::new("Moog Bass", PresetCategory::Bass)
                .with_description("Classic Moog-style monophonic bass")
                .with_tag("analog")
                .with_tag("mono")
                .with_tag("fat"),
            PresetInfo::new("303 Acid", PresetCategory::Bass)
                .with_description("Roland TB-303 style acid bass")
                .with_tag("acid")
                .with_tag("resonant")
                .with_tag("squelchy"),
            PresetInfo::new("Juno Pad", PresetCategory::Pad)
                .with_description("Warm Roland Juno-style pad")
                .with_tag("analog")
                .with_tag("warm")
                .with_tag("lush"),
            PresetInfo::new("Sync Lead", PresetCategory::Lead)
                .with_description("Aggressive sync lead sound")
                .with_tag("sync")
                .with_tag("aggressive")
                .with_tag("bright"),
            PresetInfo::new("PWM Strings", PresetCategory::Pad)
                .with_description("Pulse width modulated string-like pad")
                .with_tag("pwm")
                .with_tag("strings")
                .with_tag("ensemble"),
            // Sound design
            PresetInfo::new("Metallic Ring", PresetCategory::SoundDesign)
                .with_description("Ring modulation metallic texture")
                .with_tag("ring-mod")
                .with_tag("metallic")
                .with_tag("experimental"),
            PresetInfo::new("Noise Sweep", PresetCategory::SoundDesign)
                .with_description("Filtered noise with resonant sweep")
                .with_tag("noise")
                .with_tag("sweep")
                .with_tag("fx"),
            PresetInfo::new("Wavefold Growl", PresetCategory::SoundDesign)
                .with_description("Aggressive wavefolding distortion")
                .with_tag("wavefolder")
                .with_tag("distortion")
                .with_tag("aggressive"),
            // Tutorial patches
            PresetInfo::new("Basic Subtractive", PresetCategory::Tutorial)
                .with_description("Simple VCO -> VCF -> VCA patch")
                .with_tag("beginner")
                .with_tag("subtractive")
                .with_difficulty(1),
            PresetInfo::new("Envelope Basics", PresetCategory::Tutorial)
                .with_description("Learn ADSR envelope shaping")
                .with_tag("beginner")
                .with_tag("envelope")
                .with_difficulty(1),
            PresetInfo::new("Filter Modulation", PresetCategory::Tutorial)
                .with_description("LFO modulating filter cutoff")
                .with_tag("beginner")
                .with_tag("modulation")
                .with_difficulty(2),
            PresetInfo::new("FM Basics", PresetCategory::Tutorial)
                .with_description("Introduction to FM synthesis")
                .with_tag("intermediate")
                .with_tag("fm")
                .with_difficulty(3),
        ]
    }

    /// Get all available preset infos (static method for backwards compatibility)
    pub fn list() -> Vec<PresetInfo> {
        Self::all_presets()
    }

    /// Get presets by category
    pub fn by_category(category: PresetCategory) -> Vec<PresetInfo> {
        Self::all_presets()
            .into_iter()
            .filter(|p| p.category == category)
            .collect()
    }

    /// Search presets by tag (single tag)
    pub fn by_tag(tag: &str) -> Vec<PresetInfo> {
        let tag_lower = tag.to_lowercase();
        Self::all_presets()
            .into_iter()
            .filter(|p| p.tags.iter().any(|t| t.to_lowercase().contains(&tag_lower)))
            .collect()
    }

    /// Load a preset by name (static method for backwards compatibility)
    pub fn load(name: &str) -> Option<PatchDef> {
        match name {
            // Classic patches
            "Moog Bass" => Some(ClassicPresets::moog_bass()),
            "303 Acid" => Some(ClassicPresets::acid_303()),
            "Juno Pad" => Some(ClassicPresets::juno_pad()),
            "Sync Lead" => Some(ClassicPresets::sync_lead()),
            "PWM Strings" => Some(ClassicPresets::pwm_strings()),
            // Sound design
            "Metallic Ring" => Some(SoundDesignPresets::metallic_ring()),
            "Noise Sweep" => Some(SoundDesignPresets::noise_sweep()),
            "Wavefold Growl" => Some(SoundDesignPresets::wavefold_growl()),
            // Tutorials
            "Basic Subtractive" => Some(TutorialPresets::basic_subtractive()),
            "Envelope Basics" => Some(TutorialPresets::envelope_basics()),
            "Filter Modulation" => Some(TutorialPresets::filter_modulation()),
            "FM Basics" => Some(TutorialPresets::fm_basics()),
            _ => None,
        }
    }
}

// =============================================================================
// Classic Synth Presets
// =============================================================================

/// Classic synthesizer patch presets
pub struct ClassicPresets;

impl ClassicPresets {
    /// Moog-style monophonic bass
    ///
    /// Classic fat bass sound using:
    /// - Two detuned oscillators (saw waves)
    /// - Low-pass filter with envelope
    /// - VCA with envelope
    pub fn moog_bass() -> PatchDef {
        let mut patch = PatchDef::new("Moog Bass")
            .with_author("Quiver")
            .with_description("Classic Moog-style monophonic bass with two detuned oscillators")
            .with_tag("bass")
            .with_tag("analog")
            .with_tag("classic");

        // Modules
        patch.modules = vec![
            ModuleDef::new("vco1", "vco").with_position(100.0, 100.0),
            ModuleDef::new("vco2", "vco").with_position(100.0, 200.0),
            ModuleDef::new("mixer", "mixer").with_position(250.0, 150.0),
            ModuleDef::new("vcf", "svf").with_position(400.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(550.0, 150.0),
            ModuleDef::new("env_filter", "adsr").with_position(400.0, 300.0),
            ModuleDef::new("env_amp", "adsr").with_position(550.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(700.0, 150.0),
        ];

        // Cables
        patch.cables = vec![
            // VCO1 saw -> mixer ch1
            CableDef::new("vco1.saw", "mixer.ch0"),
            // VCO2 saw -> mixer ch2 (slightly detuned via offset)
            CableDef::new("vco2.saw", "mixer.ch1"),
            // Mixer -> filter
            CableDef::new("mixer.out", "vcf.in"),
            // Filter LP -> VCA
            CableDef::new("vcf.lp", "vca.in"),
            // VCA -> output
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            // Filter envelope -> cutoff (with attenuation)
            CableDef::new("env_filter.env", "vcf.cutoff").with_attenuation(0.6),
            // Amp envelope -> VCA
            CableDef::new("env_amp.env", "vca.cv"),
        ];

        // Parameters
        patch.parameters.insert("vcf.cutoff".into(), 0.3);
        patch.parameters.insert("vcf.resonance".into(), 0.4);
        patch.parameters.insert("env_filter.attack".into(), 0.01);
        patch.parameters.insert("env_filter.decay".into(), 0.3);
        patch.parameters.insert("env_filter.sustain".into(), 0.2);
        patch.parameters.insert("env_filter.release".into(), 0.2);
        patch.parameters.insert("env_amp.attack".into(), 0.01);
        patch.parameters.insert("env_amp.decay".into(), 0.1);
        patch.parameters.insert("env_amp.sustain".into(), 0.8);
        patch.parameters.insert("env_amp.release".into(), 0.3);

        patch
    }

    /// TB-303 style acid bass
    ///
    /// Squelchy resonant bass using:
    /// - Single square wave oscillator
    /// - Highly resonant low-pass filter
    /// - Accent via envelope depth
    pub fn acid_303() -> PatchDef {
        let mut patch = PatchDef::new("303 Acid")
            .with_author("Quiver")
            .with_description("Roland TB-303 style acid bass with squelchy resonance")
            .with_tag("bass")
            .with_tag("acid")
            .with_tag("303");

        patch.modules = vec![
            ModuleDef::new("vco", "vco").with_position(100.0, 150.0),
            ModuleDef::new("vcf", "diode_ladder").with_position(250.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 150.0),
            ModuleDef::new("env", "adsr").with_position(250.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(550.0, 150.0),
        ];

        patch.cables = vec![
            CableDef::new("vco.sqr", "vcf.in"),
            CableDef::new("vcf.out", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            CableDef::new("env.env", "vcf.cutoff").with_attenuation(0.8),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("vcf.cutoff".into(), 0.2);
        patch.parameters.insert("vcf.resonance".into(), 0.85);
        patch.parameters.insert("env.attack".into(), 0.001);
        patch.parameters.insert("env.decay".into(), 0.2);
        patch.parameters.insert("env.sustain".into(), 0.0);
        patch.parameters.insert("env.release".into(), 0.1);

        patch
    }

    /// Juno-style warm pad
    ///
    /// Lush pad sound using:
    /// - PWM oscillator with slow LFO
    /// - Gentle filtering
    /// - Slow attack envelope
    /// - Chorus for width and movement
    pub fn juno_pad() -> PatchDef {
        let mut patch = PatchDef::new("Juno Pad")
            .with_author("Quiver")
            .with_description("Warm Roland Juno-style pad with PWM and chorus")
            .with_tag("pad")
            .with_tag("analog")
            .with_tag("warm")
            .with_tag("chorus");

        patch.modules = vec![
            ModuleDef::new("lfo", "lfo").with_position(100.0, 50.0),
            ModuleDef::new("vco", "vco").with_position(100.0, 150.0),
            ModuleDef::new("vcf", "svf").with_position(250.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 150.0),
            ModuleDef::new("chorus", "chorus").with_position(550.0, 150.0),
            ModuleDef::new("env", "adsr").with_position(250.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(700.0, 150.0),
        ];

        patch.cables = vec![
            // LFO -> pulse width for PWM
            CableDef::new("lfo.tri", "vco.pw")
                .with_attenuation(0.3)
                .with_offset(0.5),
            // Square wave (PWM) -> filter
            CableDef::new("vco.sqr", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            // VCA -> Chorus for that classic Juno sound
            CableDef::new("vca.out", "chorus.in"),
            // Chorus stereo outputs to stereo output
            CableDef::new("chorus.left", "output.left"),
            CableDef::new("chorus.right", "output.right"),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("lfo.rate".into(), 0.2);
        patch.parameters.insert("vcf.cutoff".into(), 0.6);
        patch.parameters.insert("vcf.resonance".into(), 0.1);
        patch.parameters.insert("env.attack".into(), 0.5);
        patch.parameters.insert("env.decay".into(), 0.3);
        patch.parameters.insert("env.sustain".into(), 0.7);
        patch.parameters.insert("env.release".into(), 1.0);
        // Classic Juno chorus settings
        patch.parameters.insert("chorus.rate".into(), 0.4);
        patch.parameters.insert("chorus.depth".into(), 0.6);
        patch.parameters.insert("chorus.mix".into(), 0.5);

        patch
    }

    /// Hard sync lead
    ///
    /// Aggressive lead using oscillator sync:
    /// - Master and slave oscillators
    /// - Slave frequency swept by envelope
    /// - Bright, cutting sound
    pub fn sync_lead() -> PatchDef {
        let mut patch = PatchDef::new("Sync Lead")
            .with_author("Quiver")
            .with_description("Aggressive oscillator sync lead sound")
            .with_tag("lead")
            .with_tag("sync")
            .with_tag("bright");

        patch.modules = vec![
            ModuleDef::new("vco_master", "vco").with_position(100.0, 100.0),
            ModuleDef::new("vco_slave", "vco").with_position(100.0, 200.0),
            ModuleDef::new("vcf", "svf").with_position(250.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 150.0),
            ModuleDef::new("env_sync", "adsr").with_position(100.0, 350.0),
            ModuleDef::new("env_amp", "adsr").with_position(400.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(550.0, 150.0),
        ];

        patch.cables = vec![
            // Master sync output to slave
            CableDef::new("vco_master.sqr", "vco_slave.sync"),
            // Slave saw -> filter (the synced output)
            CableDef::new("vco_slave.saw", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            // Envelope sweeps slave pitch for sync sweep
            CableDef::new("env_sync.env", "vco_slave.fm").with_attenuation(0.5),
            CableDef::new("env_amp.env", "vca.cv"),
        ];

        patch.parameters.insert("vcf.cutoff".into(), 0.7);
        patch.parameters.insert("vcf.resonance".into(), 0.2);
        patch.parameters.insert("env_sync.attack".into(), 0.01);
        patch.parameters.insert("env_sync.decay".into(), 0.4);
        patch.parameters.insert("env_sync.sustain".into(), 0.3);
        patch.parameters.insert("env_sync.release".into(), 0.2);
        patch.parameters.insert("env_amp.attack".into(), 0.01);
        patch.parameters.insert("env_amp.decay".into(), 0.1);
        patch.parameters.insert("env_amp.sustain".into(), 0.8);
        patch.parameters.insert("env_amp.release".into(), 0.3);

        patch
    }

    /// PWM string ensemble
    ///
    /// String-like pad using:
    /// - Multiple PWM oscillators
    /// - Chorus-like detuning
    /// - Slow attack for bowed effect
    pub fn pwm_strings() -> PatchDef {
        let mut patch = PatchDef::new("PWM Strings")
            .with_author("Quiver")
            .with_description("Lush PWM string ensemble sound")
            .with_tag("pad")
            .with_tag("strings")
            .with_tag("ensemble");

        patch.modules = vec![
            ModuleDef::new("lfo1", "lfo").with_position(50.0, 50.0),
            ModuleDef::new("lfo2", "lfo").with_position(150.0, 50.0),
            ModuleDef::new("vco1", "vco").with_position(100.0, 150.0),
            ModuleDef::new("vco2", "vco").with_position(100.0, 250.0),
            ModuleDef::new("mixer", "mixer").with_position(250.0, 200.0),
            ModuleDef::new("vcf", "svf").with_position(400.0, 200.0),
            ModuleDef::new("vca", "vca").with_position(550.0, 200.0),
            ModuleDef::new("env", "adsr").with_position(400.0, 350.0),
            ModuleDef::new("output", "stereo_output").with_position(700.0, 200.0),
        ];

        patch.cables = vec![
            // LFOs modulate pulse widths at different rates
            CableDef::new("lfo1.tri", "vco1.pw")
                .with_attenuation(0.25)
                .with_offset(0.5),
            CableDef::new("lfo2.tri", "vco2.pw")
                .with_attenuation(0.25)
                .with_offset(0.5),
            // Mix oscillators
            CableDef::new("vco1.sqr", "mixer.ch0"),
            CableDef::new("vco2.sqr", "mixer.ch1"),
            CableDef::new("mixer.out", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("lfo1.rate".into(), 0.15);
        patch.parameters.insert("lfo2.rate".into(), 0.22);
        patch.parameters.insert("vcf.cutoff".into(), 0.5);
        patch.parameters.insert("vcf.resonance".into(), 0.05);
        patch.parameters.insert("env.attack".into(), 0.8);
        patch.parameters.insert("env.decay".into(), 0.2);
        patch.parameters.insert("env.sustain".into(), 0.9);
        patch.parameters.insert("env.release".into(), 1.5);

        patch
    }
}

// =============================================================================
// Sound Design Presets
// =============================================================================

/// Sound design and experimental presets
pub struct SoundDesignPresets;

impl SoundDesignPresets {
    /// Metallic ring modulation texture
    pub fn metallic_ring() -> PatchDef {
        let mut patch = PatchDef::new("Metallic Ring")
            .with_author("Quiver")
            .with_description("Ring modulation creating metallic, bell-like textures")
            .with_tag("ring-mod")
            .with_tag("metallic")
            .with_tag("experimental");

        patch.modules = vec![
            ModuleDef::new("vco1", "vco").with_position(100.0, 100.0),
            ModuleDef::new("vco2", "vco").with_position(100.0, 200.0),
            ModuleDef::new("ring", "ring_mod").with_position(250.0, 150.0),
            ModuleDef::new("vcf", "svf").with_position(400.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(550.0, 150.0),
            ModuleDef::new("env", "adsr").with_position(400.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(700.0, 150.0),
        ];

        patch.cables = vec![
            CableDef::new("vco1.sin", "ring.carrier"),
            CableDef::new("vco2.sin", "ring.modulator"),
            CableDef::new("ring.out", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("vcf.cutoff".into(), 0.8);
        patch.parameters.insert("vcf.resonance".into(), 0.1);
        patch.parameters.insert("env.attack".into(), 0.01);
        patch.parameters.insert("env.decay".into(), 1.0);
        patch.parameters.insert("env.sustain".into(), 0.3);
        patch.parameters.insert("env.release".into(), 0.5);

        patch
    }

    /// Filtered noise sweep
    pub fn noise_sweep() -> PatchDef {
        let mut patch = PatchDef::new("Noise Sweep")
            .with_author("Quiver")
            .with_description("Resonant filter sweep on noise for FX and transitions")
            .with_tag("noise")
            .with_tag("sweep")
            .with_tag("fx");

        patch.modules = vec![
            ModuleDef::new("noise", "noise").with_position(100.0, 150.0),
            ModuleDef::new("vcf", "svf").with_position(250.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 150.0),
            ModuleDef::new("lfo", "lfo").with_position(250.0, 300.0),
            ModuleDef::new("env", "adsr").with_position(400.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(550.0, 150.0),
        ];

        patch.cables = vec![
            CableDef::new("noise.white", "vcf.in"),
            CableDef::new("vcf.bp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            CableDef::new("lfo.tri", "vcf.cutoff").with_attenuation(0.4),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("lfo.rate".into(), 0.1);
        patch.parameters.insert("vcf.cutoff".into(), 0.5);
        patch.parameters.insert("vcf.resonance".into(), 0.8);
        patch.parameters.insert("env.attack".into(), 0.5);
        patch.parameters.insert("env.decay".into(), 0.0);
        patch.parameters.insert("env.sustain".into(), 1.0);
        patch.parameters.insert("env.release".into(), 0.5);

        patch
    }

    /// Wavefolding distortion
    pub fn wavefold_growl() -> PatchDef {
        let mut patch = PatchDef::new("Wavefold Growl")
            .with_author("Quiver")
            .with_description("Aggressive wavefolding distortion for bass and leads")
            .with_tag("wavefolder")
            .with_tag("distortion")
            .with_tag("aggressive");

        patch.modules = vec![
            ModuleDef::new("vco", "vco").with_position(100.0, 150.0),
            ModuleDef::new("folder", "wavefolder").with_position(250.0, 150.0),
            ModuleDef::new("vcf", "svf").with_position(400.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(550.0, 150.0),
            ModuleDef::new("lfo", "lfo").with_position(250.0, 300.0),
            ModuleDef::new("env", "adsr").with_position(400.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(700.0, 150.0),
        ];

        patch.cables = vec![
            CableDef::new("vco.sin", "folder.in"),
            CableDef::new("folder.out", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            // LFO modulates fold amount
            CableDef::new("lfo.tri", "folder.threshold").with_attenuation(0.3),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("lfo.rate".into(), 0.3);
        patch.parameters.insert("folder.threshold".into(), 0.7);
        patch.parameters.insert("vcf.cutoff".into(), 0.6);
        patch.parameters.insert("vcf.resonance".into(), 0.3);
        patch.parameters.insert("env.attack".into(), 0.01);
        patch.parameters.insert("env.decay".into(), 0.2);
        patch.parameters.insert("env.sustain".into(), 0.7);
        patch.parameters.insert("env.release".into(), 0.3);

        patch
    }
}

// =============================================================================
// Tutorial Presets
// =============================================================================

/// Educational tutorial presets
pub struct TutorialPresets;

impl TutorialPresets {
    /// Basic subtractive synthesis
    ///
    /// The simplest subtractive synth patch:
    /// VCO -> VCF -> VCA -> Output
    pub fn basic_subtractive() -> PatchDef {
        let mut patch = PatchDef::new("Basic Subtractive")
            .with_author("Quiver")
            .with_description(
                "Tutorial: Basic subtractive synthesis chain. \
                 VCO generates the raw waveform, VCF shapes the timbre, \
                 VCA controls the volume.",
            )
            .with_tag("tutorial")
            .with_tag("beginner");

        patch.modules = vec![
            ModuleDef::new("vco", "vco").with_position(100.0, 150.0),
            ModuleDef::new("vcf", "svf").with_position(250.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 150.0),
            ModuleDef::new("output", "stereo_output").with_position(550.0, 150.0),
        ];

        patch.cables = vec![
            CableDef::new("vco.saw", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
        ];

        patch.parameters.insert("vcf.cutoff".into(), 0.5);
        patch.parameters.insert("vcf.resonance".into(), 0.2);
        patch.parameters.insert("vca.gain".into(), 0.7);

        patch
    }

    /// Envelope basics
    ///
    /// Shows how ADSR envelope shapes the sound:
    /// VCO -> VCF -> VCA (with envelope)
    pub fn envelope_basics() -> PatchDef {
        let mut patch = PatchDef::new("Envelope Basics")
            .with_author("Quiver")
            .with_description(
                "Tutorial: ADSR envelope controlling VCA. \
                 Attack = fade in time, Decay = drop to sustain, \
                 Sustain = held level, Release = fade out after gate off.",
            )
            .with_tag("tutorial")
            .with_tag("beginner")
            .with_tag("envelope");

        patch.modules = vec![
            ModuleDef::new("vco", "vco").with_position(100.0, 150.0),
            ModuleDef::new("vcf", "svf").with_position(250.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 150.0),
            ModuleDef::new("env", "adsr").with_position(400.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(550.0, 150.0),
        ];

        patch.cables = vec![
            CableDef::new("vco.saw", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("vcf.cutoff".into(), 0.6);
        patch.parameters.insert("vcf.resonance".into(), 0.1);
        patch.parameters.insert("env.attack".into(), 0.1);
        patch.parameters.insert("env.decay".into(), 0.3);
        patch.parameters.insert("env.sustain".into(), 0.5);
        patch.parameters.insert("env.release".into(), 0.4);

        patch
    }

    /// Filter modulation with LFO
    ///
    /// LFO modulating filter cutoff for wah-wah effect
    pub fn filter_modulation() -> PatchDef {
        let mut patch = PatchDef::new("Filter Modulation")
            .with_author("Quiver")
            .with_description(
                "Tutorial: LFO modulating filter cutoff. \
                 The LFO (Low Frequency Oscillator) creates a repeating \
                 sweep of the filter, creating a 'wah-wah' effect.",
            )
            .with_tag("tutorial")
            .with_tag("beginner")
            .with_tag("modulation");

        patch.modules = vec![
            ModuleDef::new("vco", "vco").with_position(100.0, 150.0),
            ModuleDef::new("lfo", "lfo").with_position(250.0, 50.0),
            ModuleDef::new("vcf", "svf").with_position(250.0, 150.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 150.0),
            ModuleDef::new("env", "adsr").with_position(400.0, 300.0),
            ModuleDef::new("output", "stereo_output").with_position(550.0, 150.0),
        ];

        patch.cables = vec![
            CableDef::new("vco.saw", "vcf.in"),
            // LFO to filter cutoff - this is the key modulation
            CableDef::new("lfo.tri", "vcf.cutoff").with_attenuation(0.3),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            CableDef::new("env.env", "vca.cv"),
        ];

        patch.parameters.insert("lfo.rate".into(), 0.3);
        patch.parameters.insert("vcf.cutoff".into(), 0.5);
        patch.parameters.insert("vcf.resonance".into(), 0.4);
        patch.parameters.insert("env.attack".into(), 0.01);
        patch.parameters.insert("env.decay".into(), 0.1);
        patch.parameters.insert("env.sustain".into(), 0.8);
        patch.parameters.insert("env.release".into(), 0.3);

        patch
    }

    /// FM synthesis basics
    ///
    /// One oscillator modulating another's frequency
    pub fn fm_basics() -> PatchDef {
        let mut patch = PatchDef::new("FM Basics")
            .with_author("Quiver")
            .with_description(
                "Tutorial: Basic FM (Frequency Modulation) synthesis. \
                 The modulator oscillator changes the frequency of the carrier, \
                 creating complex harmonic content.",
            )
            .with_tag("tutorial")
            .with_tag("intermediate")
            .with_tag("fm");

        patch.modules = vec![
            ModuleDef::new("modulator", "vco").with_position(100.0, 100.0),
            ModuleDef::new("carrier", "vco").with_position(100.0, 200.0),
            ModuleDef::new("fm_env", "adsr").with_position(100.0, 350.0),
            ModuleDef::new("vcf", "svf").with_position(250.0, 200.0),
            ModuleDef::new("vca", "vca").with_position(400.0, 200.0),
            ModuleDef::new("amp_env", "adsr").with_position(400.0, 350.0),
            ModuleDef::new("output", "stereo_output").with_position(550.0, 200.0),
        ];

        patch.cables = vec![
            // Modulator sine -> carrier FM input
            CableDef::new("modulator.sin", "carrier.fm"),
            // FM envelope controls modulation depth
            CableDef::new("fm_env.env", "modulator.fm").with_attenuation(0.3),
            // Carrier output through filter and VCA
            CableDef::new("carrier.sin", "vcf.in"),
            CableDef::new("vcf.lp", "vca.in"),
            CableDef::new("vca.out", "output.left"),
            CableDef::new("vca.out", "output.right"),
            CableDef::new("amp_env.env", "vca.cv"),
        ];

        patch.parameters.insert("vcf.cutoff".into(), 0.8);
        patch.parameters.insert("vcf.resonance".into(), 0.0);
        patch.parameters.insert("fm_env.attack".into(), 0.01);
        patch.parameters.insert("fm_env.decay".into(), 0.5);
        patch.parameters.insert("fm_env.sustain".into(), 0.2);
        patch.parameters.insert("fm_env.release".into(), 0.3);
        patch.parameters.insert("amp_env.attack".into(), 0.01);
        patch.parameters.insert("amp_env.decay".into(), 0.2);
        patch.parameters.insert("amp_env.sustain".into(), 0.6);
        patch.parameters.insert("amp_env.release".into(), 0.4);

        patch
    }
}

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

    #[test]
    fn test_preset_library_list() {
        let presets = PresetLibrary::list();
        assert!(!presets.is_empty());
        assert!(presets.len() >= 12); // At least 12 presets defined
    }

    #[test]
    fn test_preset_library_by_category() {
        let bass_presets = PresetLibrary::by_category(PresetCategory::Bass);
        assert!(!bass_presets.is_empty());
        for preset in &bass_presets {
            assert_eq!(preset.category, PresetCategory::Bass);
        }

        let tutorials = PresetLibrary::by_category(PresetCategory::Tutorial);
        assert!(!tutorials.is_empty());
    }

    #[test]
    fn test_preset_library_by_tag() {
        let analog_presets = PresetLibrary::by_tag("analog");
        assert!(!analog_presets.is_empty());

        let beginner_presets = PresetLibrary::by_tag("beginner");
        assert!(!beginner_presets.is_empty());
    }

    #[test]
    fn test_preset_library_load() {
        // Test loading each preset
        let preset_names = [
            "Moog Bass",
            "303 Acid",
            "Juno Pad",
            "Sync Lead",
            "PWM Strings",
            "Metallic Ring",
            "Noise Sweep",
            "Wavefold Growl",
            "Basic Subtractive",
            "Envelope Basics",
            "Filter Modulation",
            "FM Basics",
        ];

        for name in preset_names {
            let patch = PresetLibrary::load(name);
            assert!(patch.is_some(), "Failed to load preset: {}", name);
            let patch = patch.unwrap();
            assert_eq!(patch.name, name);
            assert!(!patch.modules.is_empty());
            assert!(!patch.cables.is_empty());
        }
    }

    #[test]
    fn test_preset_load_nonexistent() {
        let patch = PresetLibrary::load("Nonexistent Preset");
        assert!(patch.is_none());
    }

    #[test]
    fn test_moog_bass_structure() {
        let patch = ClassicPresets::moog_bass();
        assert_eq!(patch.name, "Moog Bass");
        assert!(patch.modules.iter().any(|m| m.module_type == "vco"));
        assert!(patch.modules.iter().any(|m| m.module_type == "svf"));
        assert!(patch.modules.iter().any(|m| m.module_type == "vca"));
        assert!(patch.modules.iter().any(|m| m.module_type == "adsr"));
    }

    #[test]
    fn test_preset_serialization() {
        let patch = ClassicPresets::moog_bass();
        let json = patch.to_json().unwrap();
        assert!(json.contains("Moog Bass"));
        assert!(json.contains("vco"));

        // Round-trip
        let loaded = PatchDef::from_json(&json).unwrap();
        assert_eq!(loaded.name, patch.name);
        assert_eq!(loaded.modules.len(), patch.modules.len());
    }

    #[test]
    fn test_tutorial_presets_have_descriptions() {
        let tutorials = PresetLibrary::by_category(PresetCategory::Tutorial);
        for preset in tutorials {
            assert!(
                !preset.description.is_empty(),
                "Tutorial {} should have description",
                preset.name
            );
        }
    }

    #[test]
    fn test_preset_info_builder() {
        let info = PresetInfo::new("Test Preset", PresetCategory::Lead)
            .with_description("A test preset")
            .with_tag("test")
            .with_tag("example")
            .with_difficulty(3);

        assert_eq!(info.name, "Test Preset");
        assert_eq!(info.category, PresetCategory::Lead);
        assert_eq!(info.description, "A test preset");
        assert_eq!(info.tags.len(), 2);
        assert_eq!(info.difficulty, Some(3));
    }

    #[test]
    fn test_preset_library_new() {
        let library = PresetLibrary::new();
        // Verify default construction works
        let _clone = library.clone();
    }

    #[test]
    fn test_preset_library_get() {
        let library = PresetLibrary::new();

        // Get existing preset
        let preset = library.get("Moog Bass");
        assert!(preset.is_some());
        let preset = preset.unwrap();
        assert_eq!(preset.info.name, "Moog Bass");
        assert_eq!(preset.def.name, "Moog Bass");

        // Get non-existent preset
        let preset = library.get("Nonexistent");
        assert!(preset.is_none());
    }

    #[test]
    fn test_preset_library_search_tags() {
        let library = PresetLibrary::new();

        // Search single tag
        let results = library.search_tags(&["acid"]);
        assert!(!results.is_empty());
        assert!(results.iter().any(|p| p.name == "303 Acid"));

        // Search multiple tags
        let results = library.search_tags(&["acid", "analog"]);
        assert!(results.len() >= 2); // Should find both acid and analog presets

        // Search non-existent tag
        let results = library.search_tags(&["nonexistent_tag_xyz"]);
        assert!(results.is_empty());
    }

    #[test]
    fn test_preset_build() {
        let library = PresetLibrary::new();
        let preset = library.get("Basic Subtractive").unwrap();

        // Build the preset
        let result = preset.build(44100.0);
        assert!(result.is_ok());

        let mut patch = result.unwrap();
        // Verify patch is functional by ticking it
        let (left, right) = patch.tick();
        // Should produce some output (even if zero initially)
        assert!(left.is_finite());
        assert!(right.is_finite());
    }

    /// The names of every preset the library exposes.
    const ALL_PRESET_NAMES: [&str; 12] = [
        "Moog Bass",
        "303 Acid",
        "Juno Pad",
        "Sync Lead",
        "PWM Strings",
        "Metallic Ring",
        "Noise Sweep",
        "Wavefold Growl",
        "Basic Subtractive",
        "Envelope Basics",
        "Filter Modulation",
        "FM Basics",
    ];

    /// Q083/Q084: every built-in preset must build via `Patch::from_def` with real port
    /// names and type_ids, then tick without producing NaN/inf. With every gate/trigger
    /// input driven high, each preset's full signal chain must also reach the output
    /// (non-silence), which additionally proves the cables land on real, connected ports.
    #[test]
    fn test_all_presets_build_tick_and_sound() {
        use crate::graph::NodeId;
        use crate::port::SignalKind;

        let library = PresetLibrary::new();
        for name in ALL_PRESET_NAMES {
            let preset = library
                .get(name)
                .unwrap_or_else(|| panic!("preset '{name}' not found"));
            let mut patch = preset
                .build(44100.0)
                .unwrap_or_else(|e| panic!("preset '{name}' failed to build: {e}"));

            // Open every gate/trigger input so envelope-gated presets actually sound. These
            // inputs are unpatched in the presets, so overriding their base value to a gate
            // high opens the ADSR-driven VCAs. (Patched gates are unaffected: the override
            // only applies to unpatched inputs.)
            let gate_targets: Vec<(NodeId, String)> = patch
                .nodes()
                .flat_map(|(id, _n, m)| {
                    m.port_spec()
                        .inputs
                        .iter()
                        .filter(|p| matches!(p.kind, SignalKind::Gate | SignalKind::Trigger))
                        .map(|p| (id, p.name.clone()))
                        .collect::<Vec<_>>()
                })
                .collect();
            for (id, port) in gate_targets {
                patch.set_param_by_id(id, &port, 5.0);
            }

            let mut peak = 0.0_f64;
            for i in 0..400 {
                let (l, r) = patch.tick();
                assert!(
                    l.is_finite() && r.is_finite(),
                    "preset '{name}' produced non-finite output at sample {i}: ({l}, {r})"
                );
                peak = peak.max(l.abs()).max(r.abs());
            }
            assert!(
                peak > 1e-6,
                "preset '{name}' produced silence (peak {peak}) even with gates open"
            );
        }
    }

    /// Q083: a preset that sounds with the default (no-gate) state must be non-silent as
    /// built, without any parameter poking.
    #[test]
    fn test_basic_subtractive_sounds_without_gate() {
        let mut patch = PresetLibrary::new()
            .get("Basic Subtractive")
            .unwrap()
            .build(44100.0)
            .unwrap();
        let mut peak = 0.0_f64;
        for _ in 0..400 {
            let (l, r) = patch.tick();
            assert!(l.is_finite() && r.is_finite());
            peak = peak.max(l.abs()).max(r.abs());
        }
        assert!(peak > 1e-6, "Basic Subtractive should sound without a gate");
    }

    #[test]
    fn test_preset_into_def() {
        let library = PresetLibrary::new();
        let preset = library.get("Moog Bass").unwrap();

        let def = preset.into_def();
        assert_eq!(def.name, "Moog Bass");
    }

    #[test]
    fn test_preset_error_display() {
        let err = PresetError::NotFound("Test".into());
        assert!(err.to_string().contains("Test"));

        let err = PresetError::BuildError("failed".into());
        assert!(err.to_string().contains("failed"));
    }
}