mlua-pulse 0.1.0

Lua-friendly music composition and audio export bindings built on tunes and mlua
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
//! Track and master effects exposed to Lua and converted into `tunes` effects.

use crate::error::{PulseError, PulseResult};
use std::collections::BTreeMap;
use tunes::composition::TrackBuilder;
use tunes::synthesis::effects::{Chorus, Compressor, Delay, Limiter, Phaser, Reverb, EQ};
use tunes::synthesis::filter::{Filter, FilterSlope, FilterType};
use tunes::track::{Mixer, Track};

/// Metadata describing one Lua-visible effect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EffectInfo {
    /// Canonical effect name.
    pub name: &'static str,
    /// Broad effect family.
    pub category: &'static str,
    /// Allowed placement scopes, such as `track` or `master`.
    pub scopes: &'static [&'static str],
    /// Supported parameter names.
    pub parameters: &'static [&'static str],
    /// Supported preset names.
    pub presets: &'static [&'static str],
}

/// One parsed effect option value.
#[derive(Debug, Clone, PartialEq)]
pub enum EffectOption {
    /// Floating point option value.
    Number(f32),
    /// Text option value, commonly used for filter kinds.
    Text(String),
    /// Integer option value, commonly used for filter slopes and phaser stages.
    Integer(i64),
}

/// Parsed options for building an effect.
#[derive(Debug, Clone, Default, PartialEq)]
pub enum EffectOptions {
    /// Use the effect's default settings.
    #[default]
    Default,
    /// Use a named preset.
    Preset(String),
    /// Use named parameter values.
    Params(BTreeMap<String, EffectOption>),
}

const TRACK_AND_MASTER: &[&str] = &["track", "master"];
const TRACK_ONLY: &[&str] = &["track"];

const EFFECT_INFOS: &[EffectInfo] = &[
    EffectInfo {
        name: "delay",
        category: "time",
        scopes: TRACK_AND_MASTER,
        parameters: &["time", "feedback", "mix"],
        presets: &[
            "eighth_note",
            "quarter_note",
            "dotted_eighth",
            "half_note",
            "slapback",
            "ping_pong",
            "doubling",
            "ambient",
        ],
    },
    EffectInfo {
        name: "reverb",
        category: "space",
        scopes: TRACK_AND_MASTER,
        parameters: &["room_size", "damping", "mix"],
        presets: &[
            "room",
            "hall",
            "plate",
            "chamber",
            "cathedral",
            "ambient",
            "subtle",
            "spring",
        ],
    },
    EffectInfo {
        name: "filter",
        category: "filter",
        scopes: TRACK_ONLY,
        parameters: &["type", "cutoff", "resonance", "slope"],
        presets: &[],
    },
    EffectInfo {
        name: "compressor",
        category: "dynamics",
        scopes: TRACK_AND_MASTER,
        parameters: &["threshold", "ratio", "attack", "release", "makeup_gain"],
        presets: &["gentle", "drum_bus", "bass", "master", "aggressive"],
    },
    EffectInfo {
        name: "limiter",
        category: "dynamics",
        scopes: TRACK_AND_MASTER,
        parameters: &["threshold", "release"],
        presets: &[
            "transparent",
            "standard",
            "brick_wall",
            "mastering",
            "safety",
        ],
    },
    EffectInfo {
        name: "chorus",
        category: "modulation",
        scopes: TRACK_AND_MASTER,
        parameters: &["rate", "depth", "mix"],
        presets: &["subtle", "classic", "wide", "vibrato", "thick"],
    },
    EffectInfo {
        name: "phaser",
        category: "modulation",
        scopes: TRACK_AND_MASTER,
        parameters: &["rate", "depth", "feedback", "stages", "mix"],
        presets: &["slow", "classic", "fast", "subtle", "deep"],
    },
    EffectInfo {
        name: "eq",
        category: "filter",
        scopes: TRACK_AND_MASTER,
        parameters: &["low_gain", "mid_gain", "high_gain", "low_freq", "high_freq"],
        presets: &["flat", "bass_boost", "bright", "warm", "phone"],
    },
];

/// Delay effect parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseDelay {
    /// Delay time in seconds.
    pub time: f32,
    /// Feedback amount in `0..=0.99`.
    pub feedback: f32,
    /// Wet/dry mix in `0..=1`.
    pub mix: f32,
}

/// Reverb effect parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseReverb {
    /// Room size in `0..=1`.
    pub room_size: f32,
    /// High-frequency damping in `0..=1`.
    pub damping: f32,
    /// Wet/dry mix in `0..=1`.
    pub mix: f32,
}

/// Filter effect parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseFilter {
    /// Filter algorithm.
    pub kind: PulseFilterKind,
    /// Cutoff frequency in Hertz.
    pub cutoff: f32,
    /// Resonance amount in `0..=0.99`.
    pub resonance: f32,
    /// Filter slope.
    pub slope: PulseFilterSlope,
}

/// Compressor effect parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseCompressor {
    /// Compression threshold in the normalized `tunes` amplitude domain.
    pub threshold: f32,
    /// Compression ratio.
    pub ratio: f32,
    /// Attack time in seconds.
    pub attack: f32,
    /// Release time in seconds.
    pub release: f32,
    /// Makeup gain multiplier.
    pub makeup_gain: f32,
}

/// Limiter effect parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseLimiter {
    /// Limiter threshold in dB-style `tunes` units.
    pub threshold: f32,
    /// Release time in seconds.
    pub release: f32,
}

/// Chorus effect parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseChorus {
    /// Modulation rate in Hertz.
    pub rate: f32,
    /// Modulation depth.
    pub depth: f32,
    /// Wet/dry mix in `0..=1`.
    pub mix: f32,
}

/// Phaser effect parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulsePhaser {
    /// Modulation rate in Hertz.
    pub rate: f32,
    /// Modulation depth in `0..=1`.
    pub depth: f32,
    /// Feedback amount in `0..=0.95`.
    pub feedback: f32,
    /// Number of phaser stages.
    pub stages: usize,
    /// Wet/dry mix in `0..=1`.
    pub mix: f32,
}

/// Three-band EQ parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseEq {
    /// Low band gain multiplier.
    pub low_gain: f32,
    /// Mid band gain multiplier.
    pub mid_gain: f32,
    /// High band gain multiplier.
    pub high_gain: f32,
    /// Low/mid crossover frequency in Hertz.
    pub low_freq: f32,
    /// Mid/high crossover frequency in Hertz.
    pub high_freq: f32,
}

/// Filter algorithm exposed by `PulseFilter`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PulseFilterKind {
    /// Low-pass filter.
    LowPass,
    /// High-pass filter.
    HighPass,
    /// Band-pass filter.
    BandPass,
    /// Notch filter.
    Notch,
    /// All-pass filter.
    AllPass,
    /// Moog-style ladder filter.
    Moog,
}

/// Filter slope exposed by `PulseFilter`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PulseFilterSlope {
    /// 12 dB per octave slope.
    Pole12,
    /// 24 dB per octave slope.
    Pole24,
}

/// One effect instance ready to apply to a track or master bus.
#[derive(Debug, Clone, PartialEq)]
pub enum PulseEffect {
    /// Delay.
    Delay(PulseDelay),
    /// Reverb.
    Reverb(PulseReverb),
    /// Filter. This is track-only.
    Filter(PulseFilter),
    /// Compressor.
    Compressor(PulseCompressor),
    /// Limiter.
    Limiter(PulseLimiter),
    /// Chorus.
    Chorus(PulseChorus),
    /// Phaser.
    Phaser(PulsePhaser),
    /// Three-band EQ.
    Eq(PulseEq),
}

impl Default for PulseDelay {
    fn default() -> Self {
        Self {
            time: 0.25,
            feedback: 0.4,
            mix: 0.35,
        }
    }
}

impl Default for PulseReverb {
    fn default() -> Self {
        Self {
            room_size: 0.5,
            damping: 0.5,
            mix: 0.25,
        }
    }
}

impl Default for PulseFilter {
    fn default() -> Self {
        Self {
            kind: PulseFilterKind::LowPass,
            cutoff: 1200.0,
            resonance: 0.3,
            slope: PulseFilterSlope::Pole12,
        }
    }
}

impl Default for PulseCompressor {
    fn default() -> Self {
        Self {
            threshold: 0.5,
            ratio: 2.0,
            attack: 0.01,
            release: 0.1,
            makeup_gain: 1.0,
        }
    }
}

impl Default for PulseLimiter {
    fn default() -> Self {
        Self {
            threshold: -0.3,
            release: 0.05,
        }
    }
}

impl Default for PulseChorus {
    fn default() -> Self {
        Self {
            rate: 1.5,
            depth: 5.0,
            mix: 0.5,
        }
    }
}

impl Default for PulsePhaser {
    fn default() -> Self {
        Self {
            rate: 0.5,
            depth: 0.8,
            feedback: 0.6,
            stages: 4,
            mix: 0.6,
        }
    }
}

impl Default for PulseEq {
    fn default() -> Self {
        Self {
            low_gain: 1.0,
            mid_gain: 1.0,
            high_gain: 1.0,
            low_freq: 300.0,
            high_freq: 3000.0,
        }
    }
}

/// Returns metadata for all Lua-visible effects.
#[must_use]
pub fn effect_infos() -> &'static [EffectInfo] {
    EFFECT_INFOS
}

/// Returns effect names in stable API order.
#[must_use]
pub fn effect_names() -> Vec<&'static str> {
    EFFECT_INFOS.iter().map(|info| info.name).collect()
}

/// Looks up one effect's metadata by name.
///
/// # Errors
///
/// Returns `PulseError::InvalidEffect` when `name` is unknown.
pub fn effect_info(name: &str) -> PulseResult<&'static EffectInfo> {
    let normalized = normalize_name(name);
    EFFECT_INFOS
        .iter()
        .find(|info| normalize_name(info.name) == normalized)
        .ok_or_else(|| PulseError::InvalidEffect {
            name: name.to_string(),
        })
}

/// Builds an effect from a name and parsed options.
///
/// # Errors
///
/// Returns an error when the name, preset, option name, or option value is invalid.
pub fn effect_from_options(name: &str, options: EffectOptions) -> PulseResult<PulseEffect> {
    match normalize_name(name).as_str() {
        "delay" => build_delay(options).map(PulseEffect::Delay),
        "reverb" => build_reverb(options).map(PulseEffect::Reverb),
        "filter" => build_filter(options).map(PulseEffect::Filter),
        "compressor" => build_compressor(options).map(PulseEffect::Compressor),
        "limiter" => build_limiter(options).map(PulseEffect::Limiter),
        "chorus" => build_chorus(options).map(PulseEffect::Chorus),
        "phaser" => build_phaser(options).map(PulseEffect::Phaser),
        "eq" => build_eq(options).map(PulseEffect::Eq),
        _ => Err(PulseError::InvalidEffect {
            name: name.to_string(),
        }),
    }
}

fn normalize_name(value: &str) -> String {
    value
        .trim()
        .to_ascii_lowercase()
        .replace(['_', '-', ' '], "")
}

fn option_key_error(effect: &str, option: &str) -> PulseError {
    PulseError::InvalidEffectOption {
        effect: effect.to_string(),
        option: option.to_string(),
        value: "unsupported".to_string(),
    }
}

fn option_value_error(effect: &str, option: &str, value: impl ToString) -> PulseError {
    PulseError::InvalidEffectOption {
        effect: effect.to_string(),
        option: option.to_string(),
        value: value.to_string(),
    }
}

fn invalid_preset(effect: &str, preset: &str) -> PulseError {
    PulseError::InvalidEffectPreset {
        effect: effect.to_string(),
        preset: preset.to_string(),
    }
}

fn number_option(effect: &str, option: &str, value: &EffectOption) -> PulseResult<f32> {
    match value {
        EffectOption::Number(value) if value.is_finite() => Ok(*value),
        EffectOption::Integer(value) => Ok(*value as f32),
        EffectOption::Number(value) => Err(option_value_error(effect, option, value)),
        EffectOption::Text(value) => Err(option_value_error(effect, option, value)),
    }
}

fn integer_option(effect: &str, option: &str, value: &EffectOption) -> PulseResult<i64> {
    match value {
        EffectOption::Integer(value) => Ok(*value),
        EffectOption::Number(value) if value.is_finite() && value.fract() == 0.0 => {
            Ok(*value as i64)
        }
        EffectOption::Number(value) => Err(option_value_error(effect, option, value)),
        EffectOption::Text(value) => Err(option_value_error(effect, option, value)),
    }
}

fn text_option(effect: &str, option: &str, value: &EffectOption) -> PulseResult<String> {
    match value {
        EffectOption::Text(value) => Ok(value.clone()),
        EffectOption::Number(value) => Err(option_value_error(effect, option, value)),
        EffectOption::Integer(value) => Err(option_value_error(effect, option, value)),
    }
}

fn bounded_number(
    effect: &str,
    option: &str,
    value: &EffectOption,
    min: f32,
    max: f32,
) -> PulseResult<f32> {
    let value = number_option(effect, option, value)?;
    if (min..=max).contains(&value) {
        Ok(value)
    } else {
        Err(option_value_error(effect, option, value))
    }
}

fn unsupported_option(effect: &str, key: &str) -> PulseResult<()> {
    Err(option_key_error(effect, key))
}

fn build_delay(options: EffectOptions) -> PulseResult<PulseDelay> {
    match options {
        EffectOptions::Default => Ok(PulseDelay::default()),
        EffectOptions::Preset(preset) => match normalize_name(&preset).as_str() {
            "eighthnote" => Ok(PulseDelay {
                time: 0.125,
                feedback: 0.35,
                mix: 0.3,
            }),
            "quarternote" => Ok(PulseDelay {
                time: 0.25,
                feedback: 0.4,
                mix: 0.35,
            }),
            "dottedeighth" => Ok(PulseDelay {
                time: 0.1875,
                feedback: 0.35,
                mix: 0.3,
            }),
            "halfnote" => Ok(PulseDelay {
                time: 0.5,
                feedback: 0.45,
                mix: 0.4,
            }),
            "slapback" => Ok(PulseDelay {
                time: 0.08,
                feedback: 0.0,
                mix: 0.3,
            }),
            "pingpong" => Ok(PulseDelay {
                time: 0.375,
                feedback: 0.5,
                mix: 0.4,
            }),
            "doubling" => Ok(PulseDelay {
                time: 0.03,
                feedback: 0.0,
                mix: 0.2,
            }),
            "ambient" => Ok(PulseDelay {
                time: 1.0,
                feedback: 0.6,
                mix: 0.5,
            }),
            _ => Err(invalid_preset("delay", &preset)),
        },
        EffectOptions::Params(params) => {
            let mut effect = PulseDelay::default();
            for (key, value) in params {
                match key.as_str() {
                    "time" => effect.time = bounded_number("delay", "time", &value, 0.001, 10.0)?,
                    "feedback" => {
                        effect.feedback = bounded_number("delay", "feedback", &value, 0.0, 0.99)?;
                    }
                    "mix" => effect.mix = bounded_number("delay", "mix", &value, 0.0, 1.0)?,
                    _ => unsupported_option("delay", &key)?,
                }
            }
            Ok(effect)
        }
    }
}

fn build_reverb(options: EffectOptions) -> PulseResult<PulseReverb> {
    match options {
        EffectOptions::Default => Ok(PulseReverb::default()),
        EffectOptions::Preset(preset) => match normalize_name(&preset).as_str() {
            "room" => Ok(PulseReverb {
                room_size: 0.3,
                damping: 0.7,
                mix: 0.2,
            }),
            "hall" => Ok(PulseReverb {
                room_size: 0.8,
                damping: 0.5,
                mix: 0.3,
            }),
            "plate" => Ok(PulseReverb {
                room_size: 0.5,
                damping: 0.3,
                mix: 0.25,
            }),
            "chamber" => Ok(PulseReverb {
                room_size: 0.6,
                damping: 0.6,
                mix: 0.25,
            }),
            "cathedral" => Ok(PulseReverb {
                room_size: 0.95,
                damping: 0.4,
                mix: 0.4,
            }),
            "ambient" => Ok(PulseReverb {
                room_size: 0.9,
                damping: 0.4,
                mix: 0.5,
            }),
            "subtle" => Ok(PulseReverb {
                room_size: 0.4,
                damping: 0.6,
                mix: 0.15,
            }),
            "spring" => Ok(PulseReverb {
                room_size: 0.4,
                damping: 0.8,
                mix: 0.3,
            }),
            _ => Err(invalid_preset("reverb", &preset)),
        },
        EffectOptions::Params(params) => {
            let mut effect = PulseReverb::default();
            for (key, value) in params {
                match key.as_str() {
                    "room_size" => {
                        effect.room_size = bounded_number("reverb", "room_size", &value, 0.0, 1.0)?;
                    }
                    "damping" => {
                        effect.damping = bounded_number("reverb", "damping", &value, 0.0, 1.0)?;
                    }
                    "mix" => effect.mix = bounded_number("reverb", "mix", &value, 0.0, 1.0)?,
                    _ => unsupported_option("reverb", &key)?,
                }
            }
            Ok(effect)
        }
    }
}

fn build_filter(options: EffectOptions) -> PulseResult<PulseFilter> {
    match options {
        EffectOptions::Default => Ok(PulseFilter::default()),
        EffectOptions::Preset(preset) => Err(invalid_preset("filter", &preset)),
        EffectOptions::Params(params) => {
            let mut effect = PulseFilter::default();
            for (key, value) in params {
                match key.as_str() {
                    "type" => {
                        let kind = text_option("filter", "type", &value)?;
                        effect.kind = match normalize_name(&kind).as_str() {
                            "lowpass" => PulseFilterKind::LowPass,
                            "highpass" => PulseFilterKind::HighPass,
                            "bandpass" => PulseFilterKind::BandPass,
                            "notch" => PulseFilterKind::Notch,
                            "allpass" => PulseFilterKind::AllPass,
                            "moog" => PulseFilterKind::Moog,
                            _ => return Err(option_value_error("filter", "type", kind)),
                        };
                    }
                    "cutoff" => {
                        effect.cutoff = bounded_number("filter", "cutoff", &value, 20.0, 20000.0)?;
                    }
                    "resonance" => {
                        effect.resonance =
                            bounded_number("filter", "resonance", &value, 0.0, 0.99)?;
                    }
                    "slope" => {
                        let slope = integer_option("filter", "slope", &value)?;
                        effect.slope = match slope {
                            12 => PulseFilterSlope::Pole12,
                            24 => PulseFilterSlope::Pole24,
                            _ => return Err(option_value_error("filter", "slope", slope)),
                        };
                    }
                    _ => unsupported_option("filter", &key)?,
                }
            }
            Ok(effect)
        }
    }
}

fn build_compressor(options: EffectOptions) -> PulseResult<PulseCompressor> {
    match options {
        EffectOptions::Default => Ok(PulseCompressor::default()),
        EffectOptions::Preset(preset) => match normalize_name(&preset).as_str() {
            "gentle" => Ok(PulseCompressor {
                threshold: 0.5,
                ratio: 2.0,
                attack: 0.01,
                release: 0.1,
                makeup_gain: 1.0,
            }),
            "drumbus" => Ok(PulseCompressor {
                threshold: 0.6,
                ratio: 4.0,
                attack: 0.01,
                release: 0.15,
                makeup_gain: 1.0,
            }),
            "bass" => Ok(PulseCompressor {
                threshold: 0.5,
                ratio: 6.0,
                attack: 0.02,
                release: 0.2,
                makeup_gain: 1.0,
            }),
            "master" => Ok(PulseCompressor {
                threshold: 0.6,
                ratio: 2.5,
                attack: 0.01,
                release: 0.1,
                makeup_gain: 1.0,
            }),
            "aggressive" => Ok(PulseCompressor {
                threshold: 0.3,
                ratio: 8.0,
                attack: 0.005,
                release: 0.08,
                makeup_gain: 1.0,
            }),
            _ => Err(invalid_preset("compressor", &preset)),
        },
        EffectOptions::Params(params) => {
            let mut effect = PulseCompressor::default();
            for (key, value) in params {
                match key.as_str() {
                    "threshold" => {
                        effect.threshold =
                            bounded_number("compressor", "threshold", &value, 0.0, 1.0)?;
                    }
                    "ratio" => {
                        effect.ratio = bounded_number("compressor", "ratio", &value, 1.0, 20.0)?;
                    }
                    "attack" => {
                        effect.attack = bounded_number("compressor", "attack", &value, 0.001, 1.0)?;
                    }
                    "release" => {
                        effect.release =
                            bounded_number("compressor", "release", &value, 0.001, 5.0)?;
                    }
                    "makeup_gain" => {
                        effect.makeup_gain =
                            bounded_number("compressor", "makeup_gain", &value, 0.1, 4.0)?;
                    }
                    _ => unsupported_option("compressor", &key)?,
                }
            }
            Ok(effect)
        }
    }
}

fn build_limiter(options: EffectOptions) -> PulseResult<PulseLimiter> {
    match options {
        EffectOptions::Default => Ok(PulseLimiter::default()),
        EffectOptions::Preset(preset) => match normalize_name(&preset).as_str() {
            "transparent" => Ok(PulseLimiter {
                threshold: -0.5,
                release: 0.1,
            }),
            "standard" => Ok(PulseLimiter {
                threshold: -0.3,
                release: 0.05,
            }),
            "brickwall" => Ok(PulseLimiter {
                threshold: -0.1,
                release: 0.005,
            }),
            "mastering" => Ok(PulseLimiter {
                threshold: -0.2,
                release: 0.08,
            }),
            "safety" => Ok(PulseLimiter {
                threshold: 0.0,
                release: 0.01,
            }),
            _ => Err(invalid_preset("limiter", &preset)),
        },
        EffectOptions::Params(params) => {
            let mut effect = PulseLimiter::default();
            for (key, value) in params {
                match key.as_str() {
                    "threshold" => {
                        effect.threshold =
                            bounded_number("limiter", "threshold", &value, -60.0, 0.0)?;
                    }
                    "release" => {
                        effect.release = bounded_number("limiter", "release", &value, 0.001, 5.0)?;
                    }
                    _ => unsupported_option("limiter", &key)?,
                }
            }
            Ok(effect)
        }
    }
}

fn build_chorus(options: EffectOptions) -> PulseResult<PulseChorus> {
    match options {
        EffectOptions::Default => Ok(PulseChorus::default()),
        EffectOptions::Preset(preset) => match normalize_name(&preset).as_str() {
            "subtle" => Ok(PulseChorus {
                rate: 0.5,
                depth: 3.0,
                mix: 0.3,
            }),
            "classic" => Ok(PulseChorus {
                rate: 1.5,
                depth: 5.0,
                mix: 0.5,
            }),
            "wide" => Ok(PulseChorus {
                rate: 0.8,
                depth: 8.0,
                mix: 0.6,
            }),
            "vibrato" => Ok(PulseChorus {
                rate: 5.0,
                depth: 3.0,
                mix: 1.0,
            }),
            "thick" => Ok(PulseChorus {
                rate: 2.0,
                depth: 7.0,
                mix: 0.7,
            }),
            _ => Err(invalid_preset("chorus", &preset)),
        },
        EffectOptions::Params(params) => {
            let mut effect = PulseChorus::default();
            for (key, value) in params {
                match key.as_str() {
                    "rate" => effect.rate = bounded_number("chorus", "rate", &value, 0.1, 10.0)?,
                    "depth" => {
                        effect.depth = bounded_number("chorus", "depth", &value, 0.5, 50.0)?;
                    }
                    "mix" => effect.mix = bounded_number("chorus", "mix", &value, 0.0, 1.0)?,
                    _ => unsupported_option("chorus", &key)?,
                }
            }
            Ok(effect)
        }
    }
}

fn build_phaser(options: EffectOptions) -> PulseResult<PulsePhaser> {
    match options {
        EffectOptions::Default => Ok(PulsePhaser::default()),
        EffectOptions::Preset(preset) => match normalize_name(&preset).as_str() {
            "slow" => Ok(PulsePhaser {
                rate: 0.3,
                depth: 0.7,
                feedback: 0.5,
                stages: 4,
                mix: 0.5,
            }),
            "classic" => Ok(PulsePhaser {
                rate: 0.5,
                depth: 0.8,
                feedback: 0.6,
                stages: 4,
                mix: 0.6,
            }),
            "fast" => Ok(PulsePhaser {
                rate: 2.0,
                depth: 0.9,
                feedback: 0.7,
                stages: 6,
                mix: 0.7,
            }),
            "subtle" => Ok(PulsePhaser {
                rate: 0.4,
                depth: 0.5,
                feedback: 0.3,
                stages: 4,
                mix: 0.4,
            }),
            "deep" => Ok(PulsePhaser {
                rate: 0.6,
                depth: 1.0,
                feedback: 0.8,
                stages: 8,
                mix: 0.8,
            }),
            _ => Err(invalid_preset("phaser", &preset)),
        },
        EffectOptions::Params(params) => {
            let mut effect = PulsePhaser::default();
            for (key, value) in params {
                match key.as_str() {
                    "rate" => effect.rate = bounded_number("phaser", "rate", &value, 0.1, 10.0)?,
                    "depth" => {
                        effect.depth = bounded_number("phaser", "depth", &value, 0.0, 1.0)?;
                    }
                    "feedback" => {
                        effect.feedback = bounded_number("phaser", "feedback", &value, 0.0, 0.95)?;
                    }
                    "mix" => effect.mix = bounded_number("phaser", "mix", &value, 0.0, 1.0)?,
                    "stages" => {
                        let stages = integer_option("phaser", "stages", &value)?;
                        effect.stages = match stages {
                            2 | 4 | 6 | 8 => stages as usize,
                            _ => return Err(option_value_error("phaser", "stages", stages)),
                        };
                    }
                    _ => unsupported_option("phaser", &key)?,
                }
            }
            Ok(effect)
        }
    }
}

fn build_eq(options: EffectOptions) -> PulseResult<PulseEq> {
    match options {
        EffectOptions::Default => Ok(PulseEq::default()),
        EffectOptions::Preset(preset) => match normalize_name(&preset).as_str() {
            "flat" => Ok(PulseEq::default()),
            "bassboost" => Ok(PulseEq {
                low_gain: 1.5,
                mid_gain: 1.0,
                high_gain: 1.0,
                low_freq: 100.0,
                high_freq: 3000.0,
            }),
            "bright" => Ok(PulseEq {
                low_gain: 0.8,
                mid_gain: 1.0,
                high_gain: 1.4,
                low_freq: 300.0,
                high_freq: 5000.0,
            }),
            "warm" => Ok(PulseEq {
                low_gain: 1.3,
                mid_gain: 1.0,
                high_gain: 0.9,
                low_freq: 150.0,
                high_freq: 3000.0,
            }),
            "phone" => Ok(PulseEq {
                low_gain: 0.2,
                mid_gain: 1.4,
                high_gain: 0.2,
                low_freq: 600.0,
                high_freq: 3000.0,
            }),
            _ => Err(invalid_preset("eq", &preset)),
        },
        EffectOptions::Params(params) => {
            let mut effect = PulseEq::default();
            for (key, value) in params {
                match key.as_str() {
                    "low_gain" => {
                        effect.low_gain = bounded_number("eq", "low_gain", &value, 0.0, 4.0)?;
                    }
                    "mid_gain" => {
                        effect.mid_gain = bounded_number("eq", "mid_gain", &value, 0.0, 4.0)?;
                    }
                    "high_gain" => {
                        effect.high_gain = bounded_number("eq", "high_gain", &value, 0.0, 4.0)?;
                    }
                    "low_freq" => {
                        effect.low_freq = bounded_number("eq", "low_freq", &value, 20.0, 20000.0)?;
                    }
                    "high_freq" => {
                        effect.high_freq =
                            bounded_number("eq", "high_freq", &value, 20.0, 20000.0)?;
                    }
                    _ => unsupported_option("eq", &key)?,
                }
            }
            if effect.high_freq <= effect.low_freq {
                return Err(option_value_error("eq", "high_freq", effect.high_freq));
            }
            Ok(effect)
        }
    }
}

impl PulseDelay {
    /// Converts this wrapper to the corresponding `tunes` delay.
    #[must_use]
    pub fn to_tunes(&self) -> Delay {
        Delay::new(self.time, self.feedback, self.mix)
    }
}

impl PulseReverb {
    /// Converts this wrapper to the corresponding `tunes` reverb.
    #[must_use]
    pub fn to_tunes(&self) -> Reverb {
        Reverb::new(self.room_size, self.damping, self.mix)
    }
}

impl PulseFilter {
    /// Converts this wrapper to the corresponding `tunes` filter.
    #[must_use]
    pub fn to_tunes(&self) -> Filter {
        let filter_type = match self.kind {
            PulseFilterKind::LowPass => FilterType::LowPass,
            PulseFilterKind::HighPass => FilterType::HighPass,
            PulseFilterKind::BandPass => FilterType::BandPass,
            PulseFilterKind::Notch => FilterType::Notch,
            PulseFilterKind::AllPass => FilterType::AllPass,
            PulseFilterKind::Moog => FilterType::Moog,
        };
        let slope = match self.slope {
            PulseFilterSlope::Pole12 => FilterSlope::Pole12dB,
            PulseFilterSlope::Pole24 => FilterSlope::Pole24dB,
        };
        Filter::with_slope(filter_type, self.cutoff, self.resonance, slope)
    }
}

impl PulseCompressor {
    /// Converts this wrapper to the corresponding `tunes` compressor.
    #[must_use]
    pub fn to_tunes(&self) -> Compressor {
        Compressor::new(
            self.threshold,
            self.ratio,
            self.attack,
            self.release,
            self.makeup_gain,
        )
    }
}

impl PulseLimiter {
    /// Converts this wrapper to the corresponding `tunes` limiter.
    #[must_use]
    pub fn to_tunes(&self) -> Limiter {
        Limiter::new(self.threshold, self.release)
    }
}

impl PulseChorus {
    /// Converts this wrapper to the corresponding `tunes` chorus.
    #[must_use]
    pub fn to_tunes(&self) -> Chorus {
        Chorus::new(self.rate, self.depth, self.mix)
    }
}

impl PulsePhaser {
    /// Converts this wrapper to the corresponding `tunes` phaser.
    #[must_use]
    pub fn to_tunes(&self) -> Phaser {
        Phaser::new(self.rate, self.depth, self.feedback, self.stages, self.mix)
    }
}

impl PulseEq {
    /// Converts this wrapper to the corresponding `tunes` EQ.
    #[must_use]
    pub fn to_tunes(&self) -> EQ {
        EQ::new(
            self.low_gain,
            self.mid_gain,
            self.high_gain,
            self.low_freq,
            self.high_freq,
        )
    }
}

impl PulseEffect {
    /// Returns the canonical effect name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Delay(_) => "delay",
            Self::Reverb(_) => "reverb",
            Self::Filter(_) => "filter",
            Self::Compressor(_) => "compressor",
            Self::Limiter(_) => "limiter",
            Self::Chorus(_) => "chorus",
            Self::Phaser(_) => "phaser",
            Self::Eq(_) => "eq",
        }
    }

    /// Returns whether this effect can be applied to the master bus.
    #[must_use]
    pub fn allowed_on_master(&self) -> bool {
        !matches!(self, Self::Filter(_))
    }

    /// Applies this effect to a `tunes` track builder.
    #[must_use]
    pub fn apply_to_track_builder<'a>(&self, builder: TrackBuilder<'a>) -> TrackBuilder<'a> {
        match self {
            Self::Delay(value) => builder.delay(value.to_tunes()),
            Self::Reverb(value) => builder.reverb(value.to_tunes()),
            Self::Filter(value) => builder.filter(value.to_tunes()),
            Self::Compressor(value) => builder.compressor(value.to_tunes()),
            Self::Limiter(value) => builder.limiter(value.to_tunes()),
            Self::Chorus(value) => builder.chorus(value.to_tunes()),
            Self::Phaser(value) => builder.phaser(value.to_tunes()),
            Self::Eq(value) => builder.eq(value.to_tunes()),
        }
    }

    /// Applies this effect directly to an existing `tunes` track.
    pub(crate) fn apply_to_track(&self, track: &mut Track) {
        match self {
            Self::Delay(value) => {
                track.effects = track.effects.clone().with_delay(value.to_tunes())
            }
            Self::Reverb(value) => {
                track.effects = track.effects.clone().with_reverb(value.to_tunes());
            }
            Self::Filter(value) => {
                track.filter = value.to_tunes();
            }
            Self::Compressor(value) => {
                track.effects = track.effects.clone().with_compressor(value.to_tunes());
            }
            Self::Limiter(value) => {
                track.effects = track.effects.clone().with_limiter(value.to_tunes());
            }
            Self::Chorus(value) => {
                track.effects = track.effects.clone().with_chorus(value.to_tunes());
            }
            Self::Phaser(value) => {
                track.effects = track.effects.clone().with_phaser(value.to_tunes());
            }
            Self::Eq(value) => {
                track.effects = track.effects.clone().with_eq(value.to_tunes());
            }
        }
    }

    /// Applies this effect to a `tunes` mixer master bus.
    ///
    /// # Errors
    ///
    /// Returns an invalid-scope error when called for a track-only effect.
    pub fn apply_to_master(&self, mixer: &mut Mixer) -> PulseResult<()> {
        match self {
            Self::Delay(value) => mixer.master_delay(value.to_tunes()),
            Self::Reverb(value) => mixer.master_reverb(value.to_tunes()),
            Self::Filter(_) => {
                return Err(PulseError::InvalidEffectScope {
                    effect: "filter".to_string(),
                    scope: "master".to_string(),
                });
            }
            Self::Compressor(value) => mixer.master_compressor(value.to_tunes()),
            Self::Limiter(value) => mixer.master_limiter(value.to_tunes()),
            Self::Chorus(value) => mixer.master_chorus(value.to_tunes()),
            Self::Phaser(value) => mixer.master_phaser(value.to_tunes()),
            Self::Eq(value) => mixer.master_eq(value.to_tunes()),
        }
        Ok(())
    }
}

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

    fn params(entries: &[(&str, EffectOption)]) -> EffectOptions {
        let mut values = BTreeMap::new();
        for (key, value) in entries {
            values.insert((*key).to_string(), value.clone());
        }
        EffectOptions::Params(values)
    }

    #[test]
    fn effect_catalog_exposes_v1_effects() {
        let names = effect_names();

        assert_eq!(names.len(), 8);
        assert!(names.contains(&"delay"));
        assert!(names.contains(&"reverb"));
        assert!(names.contains(&"filter"));
        assert!(names.contains(&"compressor"));
        assert!(names.contains(&"limiter"));
        assert!(names.contains(&"chorus"));
        assert!(names.contains(&"phaser"));
        assert!(names.contains(&"eq"));

        let delay = effect_info("delay").expect("delay info should exist");
        assert_eq!(delay.category, "time");
        assert!(delay.scopes.contains(&"track"));
        assert!(delay.scopes.contains(&"master"));
        assert!(delay.parameters.contains(&"time"));
        assert!(delay.presets.contains(&"quarter_note"));

        let filter = effect_info("filter").expect("filter info should exist");
        assert_eq!(filter.scopes, &["track"]);
    }

    #[test]
    fn invalid_effect_name_reports_stable_error() {
        let error = effect_from_options("shimmer", EffectOptions::Default)
            .expect_err("unknown effect should fail");

        assert_eq!(error.to_string(), "invalid effect: shimmer");
    }

    #[test]
    fn delay_validates_params_and_presets() {
        let effect = effect_from_options(
            "delay",
            params(&[
                ("time", EffectOption::Number(0.25)),
                ("feedback", EffectOption::Number(0.35)),
                ("mix", EffectOption::Number(0.3)),
            ]),
        )
        .expect("valid delay should parse");

        let PulseEffect::Delay(delay) = effect else {
            panic!("expected delay");
        };
        assert_eq!(delay.time, 0.25);
        assert_eq!(delay.feedback, 0.35);
        assert_eq!(delay.mix, 0.3);

        let preset = effect_from_options("delay", EffectOptions::Preset("slapback".to_string()))
            .expect("delay preset should parse");
        assert!(matches!(preset, PulseEffect::Delay(_)));

        let invalid =
            effect_from_options("delay", params(&[("feedback", EffectOption::Number(1.2))]))
                .expect_err("feedback outside range should fail");
        assert_eq!(
            invalid.to_string(),
            "invalid effect option delay.feedback: 1.2"
        );
    }

    #[test]
    fn filter_validates_type_cutoff_resonance_and_scope() {
        let effect = effect_from_options(
            "filter",
            params(&[
                ("type", EffectOption::Text("low_pass".to_string())),
                ("cutoff", EffectOption::Number(1800.0)),
                ("resonance", EffectOption::Number(0.4)),
                ("slope", EffectOption::Integer(24)),
            ]),
        )
        .expect("valid filter should parse");

        let PulseEffect::Filter(filter) = effect else {
            panic!("expected filter");
        };
        assert_eq!(filter.kind, PulseFilterKind::LowPass);
        assert_eq!(filter.cutoff, 1800.0);
        assert_eq!(filter.resonance, 0.4);
        assert_eq!(filter.slope, PulseFilterSlope::Pole24);
        assert!(!PulseEffect::Filter(filter).allowed_on_master());

        let invalid = effect_from_options(
            "filter",
            params(&[("type", EffectOption::Text("comb".to_string()))]),
        )
        .expect_err("unknown filter type should fail");
        assert_eq!(
            invalid.to_string(),
            "invalid effect option filter.type: comb"
        );
    }

    #[test]
    fn eq_rejects_invalid_frequency_order() {
        let invalid = effect_from_options(
            "eq",
            params(&[
                ("low_freq", EffectOption::Number(5000.0)),
                ("high_freq", EffectOption::Number(200.0)),
            ]),
        )
        .expect_err("high frequency must be above low frequency");

        assert_eq!(
            invalid.to_string(),
            "invalid effect option eq.high_freq: 200"
        );
    }

    #[test]
    fn all_default_effects_convert_to_tunes_types() {
        let effects = [
            effect_from_options("delay", EffectOptions::Default).unwrap(),
            effect_from_options("reverb", EffectOptions::Default).unwrap(),
            effect_from_options("filter", EffectOptions::Default).unwrap(),
            effect_from_options("compressor", EffectOptions::Default).unwrap(),
            effect_from_options("limiter", EffectOptions::Default).unwrap(),
            effect_from_options("chorus", EffectOptions::Default).unwrap(),
            effect_from_options("phaser", EffectOptions::Default).unwrap(),
            effect_from_options("eq", EffectOptions::Default).unwrap(),
        ];

        for effect in effects {
            match effect {
                PulseEffect::Delay(value) => {
                    let _ = value.to_tunes();
                }
                PulseEffect::Reverb(value) => {
                    let _ = value.to_tunes();
                }
                PulseEffect::Filter(value) => {
                    let _ = value.to_tunes();
                }
                PulseEffect::Compressor(value) => {
                    let _ = value.to_tunes();
                }
                PulseEffect::Limiter(value) => {
                    let _ = value.to_tunes();
                }
                PulseEffect::Chorus(value) => {
                    let _ = value.to_tunes();
                }
                PulseEffect::Phaser(value) => {
                    let _ = value.to_tunes();
                }
                PulseEffect::Eq(value) => {
                    let _ = value.to_tunes();
                }
            }
        }
    }
}