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
//! Drum catalogs, step grids, layered drum aliases, and 808-style helpers.

use crate::effects::PulseEffect;
use crate::error::{PulseError, PulseResult};
use tunes::composition::Composition;
use tunes::instruments::drums::DrumType;

#[derive(Clone, Copy)]
struct DrumPreset {
    name: &'static str,
    drum_type: DrumType,
}

#[derive(Clone, Copy)]
struct LayeredDrumPreset {
    name: &'static str,
    drum_types: &'static [DrumType],
}

macro_rules! drum_presets {
    ($(($name:literal, $variant:ident)),+ $(,)?) => {
        const DRUM_PRESETS: &[DrumPreset] = &[
            $(DrumPreset {
                name: $name,
                drum_type: DrumType::$variant,
            },)+
        ];

        const DRUM_NAMES: &[&str] = &[
            $($name,)+
        ];
    };
}

drum_presets!(
    ("kick", Kick),
    ("kick_808", Kick808),
    ("sub_kick", SubKick),
    ("snare", Snare),
    ("snare_808", Snare808),
    ("hihat_closed", HiHatClosed),
    ("hihat_open", HiHatOpen),
    ("hihat_808_closed", HiHat808Closed),
    ("hihat_808_open", HiHat808Open),
    ("clap", Clap),
    ("clap_808", Clap808),
    ("tom", Tom),
    ("tom_high", TomHigh),
    ("tom_low", TomLow),
    ("rimshot", Rimshot),
    ("cowbell", Cowbell),
    ("crash", Crash),
    ("ride", Ride),
    ("china", China),
    ("splash", Splash),
    ("tambourine", Tambourine),
    ("shaker", Shaker),
    ("bass_drop", BassDrop),
    ("boom", Boom),
    ("claves", Claves),
    ("triangle", Triangle),
    ("side_stick", SideStick),
    ("wood_block", WoodBlock),
    ("kick_909", Kick909),
    ("snare_909", Snare909),
    ("conga_high", CongaHigh),
    ("conga_low", CongaLow),
    ("bongo_high", BongoHigh),
    ("bongo_low", BongoLow),
    ("ride_bell", RideBell),
    ("floor_tom_low", FloorTomLow),
    ("floor_tom_high", FloorTomHigh),
    ("hihat_pedal", HiHatPedal),
    ("crash_2", Crash2),
    ("vibraslap", Vibraslap),
    ("timbale_high", TimbaleHigh),
    ("timbale_low", TimbaleLow),
    ("agogo_high", AgogoHigh),
    ("agogo_low", AgogoLow),
    ("cabasa", Cabasa),
    ("guiro_short", GuiroShort),
    ("guiro_long", GuiroLong),
    ("wood_block_high", WoodBlockHigh),
    ("timpani", Timpani),
    ("gong", Gong),
    ("chimes", Chimes),
    ("djembe", Djembe),
    ("tabla_bayan", TablaBayan),
    ("tabla_dayan", TablaDayan),
    ("cajon", Cajon),
    ("fingersnap", Fingersnap),
    ("maracas", Maracas),
    ("castanet", Castanet),
    ("sleigh_bells", SleighBells),
    ("laser_zap", LaserZap),
    ("reverse_cymbal", ReverseCymbal),
    ("white_noise_hit", WhiteNoiseHit),
    ("stick_click", StickClick),
    ("kick_tight", KickTight),
    ("kick_deep", KickDeep),
    ("kick_acoustic", KickAcoustic),
    ("kick_click", KickClick),
    ("snare_rim", SnareRim),
    ("snare_tight", SnareTight),
    ("snare_loose", SnareLoose),
    ("snare_piccolo", SnarePiccolo),
    ("hihat_half_open", HiHatHalfOpen),
    ("hihat_sizzle", HiHatSizzle),
    ("clap_dry", ClapDry),
    ("clap_room", ClapRoom),
    ("clap_group", ClapGroup),
    ("clap_snare", ClapSnare),
    ("crash_short", CrashShort),
    ("ride_tip", RideTip),
    ("egg_shaker", EggShaker),
    ("tube_shaker", TubeShaker),
    ("tom_808_low", Tom808Low),
    ("tom_808_mid", Tom808Mid),
    ("tom_808_high", Tom808High),
    ("cowbell_808", Cowbell808),
    ("clave_808", Clave808),
    ("hihat_909_closed", HiHat909Closed),
    ("hihat_909_open", HiHat909Open),
    ("clap_909", Clap909),
    ("cowbell_909", Cowbell909),
    ("rim_909", Rim909),
    ("reverse_snare", ReverseSnare),
    ("cymbal_swell", CymbalSwell),
);

const LAYERED_DRUM_PRESETS: &[LayeredDrumPreset] = &[
    LayeredDrumPreset {
        name: "kick_808_deep_layer",
        drum_types: &[DrumType::Kick808, DrumType::SubKick],
    },
    LayeredDrumPreset {
        name: "kick_909_click_layer",
        drum_types: &[DrumType::Kick909, DrumType::KickClick],
    },
    LayeredDrumPreset {
        name: "kick_acoustic_room_layer",
        drum_types: &[DrumType::KickAcoustic, DrumType::Boom],
    },
    LayeredDrumPreset {
        name: "snare_808_body_layer",
        drum_types: &[DrumType::Snare808, DrumType::SnareLoose],
    },
    LayeredDrumPreset {
        name: "snare_909_snap_layer",
        drum_types: &[DrumType::Snare909, DrumType::SnareRim],
    },
    LayeredDrumPreset {
        name: "snare_piccolo_clap_layer",
        drum_types: &[DrumType::SnarePiccolo, DrumType::ClapDry],
    },
    LayeredDrumPreset {
        name: "clap_808_stack_layer",
        drum_types: &[DrumType::Clap808, DrumType::ClapGroup],
    },
    LayeredDrumPreset {
        name: "clap_909_wide_layer",
        drum_types: &[DrumType::Clap909, DrumType::ClapRoom],
    },
    LayeredDrumPreset {
        name: "hihat_808_sizzle_layer",
        drum_types: &[DrumType::HiHat808Closed, DrumType::HiHatSizzle],
    },
    LayeredDrumPreset {
        name: "hihat_909_sizzle_layer",
        drum_types: &[DrumType::HiHat909Closed, DrumType::HiHatSizzle],
    },
    LayeredDrumPreset {
        name: "tom_808_stack_layer",
        drum_types: &[DrumType::Tom808Low, DrumType::Tom808Mid],
    },
    LayeredDrumPreset {
        name: "crash_swell_layer",
        drum_types: &[DrumType::Crash, DrumType::CymbalSwell],
    },
];

/// Returns stable Lua-facing drum aliases.
pub fn drum_names() -> Vec<&'static str> {
    DRUM_NAMES
        .iter()
        .copied()
        .chain(LAYERED_DRUM_PRESETS.iter().map(|preset| preset.name))
        .collect()
}

/// Resolves a Lua-facing drum alias to `tunes::DrumType`.
pub fn drum_by_name(name: &str) -> PulseResult<DrumType> {
    let normalized = normalize_name(name);
    DRUM_PRESETS
        .iter()
        .find(|preset| normalize_name(preset.name) == normalized)
        .map(|preset| preset.drum_type)
        .ok_or_else(|| PulseError::InvalidDrumType {
            value: name.to_string(),
        })
}

/// Resolves a Lua-facing drum alias to one or more `tunes::DrumType` voices.
pub fn drum_voices_by_name(name: &str) -> PulseResult<Vec<DrumType>> {
    let normalized = normalize_name(name);
    if let Some(preset) = DRUM_PRESETS
        .iter()
        .find(|preset| normalize_name(preset.name) == normalized)
    {
        return Ok(vec![preset.drum_type]);
    }

    LAYERED_DRUM_PRESETS
        .iter()
        .find(|preset| normalize_name(preset.name) == normalized)
        .map(|preset| preset.drum_types.to_vec())
        .ok_or_else(|| PulseError::InvalidDrumType {
            value: name.to_string(),
        })
}

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

#[derive(Debug, Clone, PartialEq, Eq)]
/// One named drum sound and its zero-based step pattern.
pub struct PulseDrumHit {
    drum: String,
    pattern: Vec<usize>,
}

impl PulseDrumHit {
    /// Creates a drum hit pattern without validating the drum alias.
    pub fn new(drum: impl Into<String>, pattern: Vec<usize>) -> Self {
        Self {
            drum: drum.into(),
            pattern,
        }
    }

    /// Returns the Lua-facing drum alias.
    pub fn drum(&self) -> &str {
        &self.drum
    }

    /// Returns zero-based step indices that trigger this drum.
    pub fn pattern(&self) -> &[usize] {
        &self.pattern
    }
}

/// A step-based drum arrangement rendered into a `tunes` composition track.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseDrumGrid {
    track_name: String,
    steps: usize,
    step_duration: f32,
    hits: Vec<PulseDrumHit>,
    accents: Option<Vec<usize>>,
    velocities: Option<Vec<f32>>,
    repeats: usize,
    effects: Vec<PulseEffect>,
    volume: f32,
    pan: f32,
}

impl Default for PulseDrumGrid {
    fn default() -> Self {
        Self::new()
    }
}

impl PulseDrumGrid {
    /// Creates a 16-step drum grid named `drums` with eighth-note steps.
    pub fn new() -> Self {
        Self {
            track_name: "drums".to_string(),
            steps: 16,
            step_duration: 0.125,
            hits: Vec::new(),
            accents: None,
            velocities: None,
            repeats: 0,
            effects: Vec::new(),
            volume: 1.0,
            pan: 0.0,
        }
    }

    /// Sets the output track name.
    #[must_use]
    pub fn with_track(mut self, track_name: impl Into<String>) -> Self {
        self.track_name = track_name.into();
        self
    }

    /// Sets the number of steps in the grid.
    ///
    /// # Errors
    ///
    /// Returns an error when `steps` is zero.
    pub fn with_steps(mut self, steps: usize) -> PulseResult<Self> {
        validate_drum_steps(steps)?;
        self.steps = steps;
        Ok(self)
    }

    /// Sets the duration of one grid step in beats.
    ///
    /// # Errors
    ///
    /// Returns an error when `duration` is zero, negative, or not finite.
    pub fn with_step_duration(mut self, duration: f32) -> PulseResult<Self> {
        if !duration.is_finite() || duration <= 0.0 {
            return Err(PulseError::InvalidStepDuration { duration });
        }
        self.step_duration = duration;
        Ok(self)
    }

    /// Adds a drum alias and zero-based step pattern.
    ///
    /// # Errors
    ///
    /// Returns an error when `drum` is not in the drum catalog.
    pub fn sound(mut self, drum: impl Into<String>, pattern: Vec<usize>) -> PulseResult<Self> {
        let drum = drum.into();
        drum_voices_by_name(&drum)?;
        self.hits.push(PulseDrumHit::new(drum, pattern));
        Ok(self)
    }

    /// Sets accent steps that raise matching drum hit velocities.
    #[must_use]
    pub fn accent(mut self, pattern: Vec<usize>) -> Self {
        self.accents = Some(pattern);
        self
    }

    /// Sets per-step velocity multipliers.
    #[must_use]
    pub fn velocity(mut self, velocities: Vec<f32>) -> Self {
        self.velocities = Some(velocities);
        self
    }

    /// Sets additional grid repetitions after the first pass.
    #[must_use]
    pub fn with_repeat(mut self, repeats: usize) -> Self {
        self.repeats = repeats;
        self
    }

    /// Sets how many total times the grid should play.
    ///
    /// # Errors
    ///
    /// Returns an error when `repeat_times` is zero.
    pub fn with_repeat_times(mut self, repeat_times: usize) -> PulseResult<Self> {
        if repeat_times == 0 {
            return Err(PulseError::InvalidRepeatTimes { repeat_times });
        }
        validate_drum_repeat_expansion(self.steps, repeat_times)?;
        self.repeats = repeat_times - 1;
        Ok(self)
    }

    /// Adds a track-level effect to the drum grid.
    #[must_use]
    pub fn with_effect(mut self, effect: PulseEffect) -> Self {
        self.effects.push(effect);
        self
    }

    /// Sets the exported drum track volume.
    ///
    /// # Errors
    ///
    /// Returns an error when `volume` is outside `0..=2`.
    pub fn with_volume(mut self, volume: f32) -> PulseResult<Self> {
        validate_drum_range("volume", volume, 0.0, 2.0)?;
        self.volume = volume;
        Ok(self)
    }

    /// Sets the exported drum track stereo pan.
    ///
    /// # Errors
    ///
    /// Returns an error when `pan` is outside `-1..=1`.
    pub fn with_pan(mut self, pan: f32) -> PulseResult<Self> {
        validate_drum_range("pan", pan, -1.0, 1.0)?;
        self.pan = pan;
        Ok(self)
    }

    /// Applies the grid to a composition starting at time zero.
    ///
    /// # Errors
    ///
    /// Returns an error when stored grid options are invalid.
    pub fn apply_to_composition(&self, composition: &mut Composition) -> PulseResult<()> {
        self.apply_to_composition_at(composition, 0.0)
    }

    /// Applies the grid to a composition at an absolute start offset in beats.
    ///
    /// # Errors
    ///
    /// Returns an error when stored grid options are invalid.
    pub fn apply_to_composition_at(
        &self,
        composition: &mut Composition,
        start_at: f32,
    ) -> PulseResult<()> {
        validate_drum_steps(self.steps)?;
        if !self.step_duration.is_finite() || self.step_duration <= 0.0 {
            return Err(PulseError::InvalidStepDuration {
                duration: self.step_duration,
            });
        }
        validate_drum_range("volume", self.volume, 0.0, 2.0)?;
        validate_drum_range("pan", self.pan, -1.0, 1.0)?;
        validate_drum_repeat_expansion(self.steps, self.repeats.saturating_add(1))?;

        let resolved_hits = self
            .hits
            .iter()
            .map(|hit| drum_voices_by_name(hit.drum()).map(|drums| (drums, hit.pattern().to_vec())))
            .collect::<PulseResult<Vec<_>>>()?;
        let accents = self.accents.clone();
        let velocities = self.velocities.clone();
        let repeats = self.repeats;

        let mut builder = composition
            .track(&self.track_name)
            .volume(self.volume)
            .pan(self.pan)
            .at(start_at)
            .drum_grid(self.steps, self.step_duration, |grid| {
                let mut grid = resolved_hits.iter().fold(grid, |grid, (drums, pattern)| {
                    drums
                        .iter()
                        .fold(grid, |grid, drum| grid.sound(*drum, pattern))
                });
                if let Some(pattern) = &accents {
                    grid = grid.accent(pattern);
                }
                if let Some(values) = &velocities {
                    grid = grid.velocity(values);
                }
                if repeats > 0 {
                    grid = grid.repeat(repeats);
                }
                grid
            });

        for effect in &self.effects {
            builder = effect.apply_to_track_builder(builder);
        }
        let _ = builder;

        Ok(())
    }

    /// Returns the output track name.
    pub fn track_name(&self) -> &str {
        &self.track_name
    }

    /// Returns the number of steps.
    pub fn steps(&self) -> usize {
        self.steps
    }

    /// Returns the duration of one grid step in beats.
    pub fn step_duration(&self) -> f32 {
        self.step_duration
    }

    /// Returns all drum hit patterns.
    pub fn hits(&self) -> &[PulseDrumHit] {
        &self.hits
    }

    /// Returns additional repeat count.
    pub fn repeats(&self) -> usize {
        self.repeats
    }

    /// Returns total grid duration in beats after repeats.
    pub fn duration(&self) -> f32 {
        self.steps as f32 * self.step_duration * self.repeats.saturating_add(1) as f32
    }

    /// Returns track-level effects in insertion order.
    pub fn effects(&self) -> &[PulseEffect] {
        &self.effects
    }

    /// Returns track volume.
    pub fn volume(&self) -> f32 {
        self.volume
    }

    /// Returns track stereo pan.
    pub fn pan(&self) -> f32 {
        self.pan
    }
}

fn validate_drum_range(option: &str, value: f32, min: f32, max: f32) -> PulseResult<()> {
    if value.is_finite() && value >= min && value <= max {
        Ok(())
    } else {
        Err(PulseError::InvalidDrumOption {
            option: option.to_string(),
            value: value.to_string(),
        })
    }
}

fn validate_drum_steps(steps: usize) -> PulseResult<()> {
    if steps == 0 || steps > isize::MAX as usize {
        return Err(PulseError::InvalidDrumGridSteps { steps });
    }
    Ok(())
}

fn validate_drum_repeat_expansion(steps: usize, repeat_times: usize) -> PulseResult<()> {
    let total_steps = steps
        .checked_mul(repeat_times)
        .ok_or(PulseError::InvalidRepeatTimes { repeat_times })?;
    if total_steps > isize::MAX as usize {
        return Err(PulseError::InvalidRepeatTimes { repeat_times });
    }
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Drum machine kit selector.
pub enum DrumKit {
    /// Roland TR-808 style mapping.
    Tr808,
}

/// Convenience builder for common 808 drum-machine patterns.
#[derive(Debug, Clone, PartialEq)]
pub struct PulseDrumMachine {
    kit: DrumKit,
    grid: PulseDrumGrid,
}

impl PulseDrumMachine {
    /// Creates a drum-machine builder for a kit name.
    ///
    /// # Errors
    ///
    /// Returns an error for unsupported kit names.
    pub fn new(kit: &str) -> PulseResult<Self> {
        match normalize_name(kit).as_str() {
            "808" | "tr808" => Ok(Self {
                kit: DrumKit::Tr808,
                grid: PulseDrumGrid::new(),
            }),
            _ => Err(PulseError::InvalidDrumType {
                value: kit.to_string(),
            }),
        }
    }

    /// Sets the backing grid step count.
    ///
    /// # Errors
    ///
    /// Returns an error when `steps` is zero.
    pub fn steps(mut self, steps: usize) -> PulseResult<Self> {
        self.grid = self.grid.with_steps(steps)?;
        Ok(self)
    }

    /// Sets the backing grid step duration in beats.
    ///
    /// # Errors
    ///
    /// Returns an error when `duration` is invalid.
    pub fn step_duration(mut self, duration: f32) -> PulseResult<Self> {
        self.grid = self.grid.with_step_duration(duration)?;
        Ok(self)
    }

    /// Adds 808 kick hits.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapped drum alias cannot be resolved.
    pub fn kick(mut self, pattern: Vec<usize>) -> PulseResult<Self> {
        self.grid = self.grid.sound("kick_808", pattern)?;
        Ok(self)
    }

    /// Adds 808 snare hits.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapped drum alias cannot be resolved.
    pub fn snare(mut self, pattern: Vec<usize>) -> PulseResult<Self> {
        self.grid = self.grid.sound("snare_808", pattern)?;
        Ok(self)
    }

    /// Adds closed 808 hi-hat hits.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapped drum alias cannot be resolved.
    pub fn hihat(mut self, pattern: Vec<usize>) -> PulseResult<Self> {
        self.grid = self.grid.sound("hihat_808_closed", pattern)?;
        Ok(self)
    }

    /// Adds open 808 hi-hat hits.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapped drum alias cannot be resolved.
    pub fn open_hihat(mut self, pattern: Vec<usize>) -> PulseResult<Self> {
        self.grid = self.grid.sound("hihat_808_open", pattern)?;
        Ok(self)
    }

    /// Adds 808 clap hits.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapped drum alias cannot be resolved.
    pub fn clap(mut self, pattern: Vec<usize>) -> PulseResult<Self> {
        self.grid = self.grid.sound("clap_808", pattern)?;
        Ok(self)
    }

    /// Finishes the builder and returns its drum grid.
    #[must_use]
    pub fn grid(self) -> PulseDrumGrid {
        self.grid
    }

    /// Returns the selected kit.
    #[must_use]
    pub fn kit(&self) -> DrumKit {
        self.kit
    }
}

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

    fn test_compressor_effect() -> crate::effects::PulseEffect {
        crate::effects::effect_from_options("compressor", crate::effects::EffectOptions::Default)
            .expect("default compressor should parse")
    }

    #[test]
    fn exposes_all_current_tunes_drum_types() {
        let names = drum_names();
        assert!(names.len() >= 100);
        assert!(names.contains(&"kick_808"));
        assert!(names.contains(&"snare_808"));
        assert!(names.contains(&"hihat_808_closed"));
        assert!(names.contains(&"clap_808"));
        assert!(names.contains(&"kick_808_deep_layer"));
        assert!(names.contains(&"snare_808_body_layer"));
        assert!(names.contains(&"clap_909_wide_layer"));

        for name in names {
            drum_voices_by_name(name).expect("catalog entry should resolve");
        }
    }

    #[test]
    fn layered_drum_aliases_resolve_to_multiple_tunes_drum_types() {
        let voices =
            drum_voices_by_name("kick_808_deep_layer").expect("layered kick should resolve");

        assert_eq!(voices, vec![DrumType::Kick808, DrumType::SubKick]);
        assert_eq!(
            drum_by_name("kick_808_deep_layer")
                .expect_err("layered aliases should require voice resolution")
                .to_string(),
            "invalid drum type: kick_808_deep_layer"
        );
    }

    #[test]
    fn rejects_unknown_drum_alias() {
        let error = drum_by_name("kick_707").expect_err("unknown drum should fail");
        assert_eq!(error.to_string(), "invalid drum type: kick_707");
    }

    #[test]
    fn drum_grid_validates_and_builds_patterns() {
        let grid = PulseDrumGrid::new()
            .with_steps(16)
            .unwrap()
            .with_step_duration(0.125)
            .unwrap()
            .sound("kick_808", vec![0, 4, 8, 12])
            .unwrap()
            .accent(vec![0, 4, 8, 12])
            .with_repeat(1);

        assert_eq!(grid.steps(), 16);
        assert_eq!(grid.hits().len(), 1);
        assert_eq!(grid.repeats(), 1);
    }

    #[test]
    fn drum_grid_repeat_times_uses_total_play_count() {
        let single_pass = PulseDrumGrid::new()
            .with_steps(4)
            .unwrap()
            .with_step_duration(0.25)
            .unwrap()
            .with_repeat_times(1)
            .unwrap();

        assert_eq!(single_pass.repeats(), 0);
        assert_eq!(single_pass.duration(), 1.0);

        let double_pass = single_pass.clone().with_repeat_times(2).unwrap();
        assert_eq!(double_pass.repeats(), 1);
        assert_eq!(double_pass.duration(), 2.0);

        assert_eq!(
            PulseDrumGrid::new()
                .with_repeat_times(0)
                .unwrap_err()
                .to_string(),
            "invalid repeat times: 0"
        );
    }

    #[test]
    fn drum_grid_rejects_unrenderable_repeat_expansion() {
        let error = PulseDrumGrid::new()
            .with_repeat_times(usize::MAX)
            .expect_err("unrenderable drum repeat expansion should fail");

        assert!(matches!(error, PulseError::InvalidRepeatTimes { .. }));
    }

    #[test]
    fn drum_grid_rejects_unrenderable_step_counts() {
        let error = PulseDrumGrid::new()
            .with_steps(usize::MAX)
            .expect_err("unrenderable drum step count should fail");

        assert!(matches!(error, PulseError::InvalidDrumGridSteps { .. }));
    }

    #[test]
    fn drum_machine_808_builds_grid() {
        let grid = PulseDrumMachine::new("808")
            .unwrap()
            .steps(16)
            .unwrap()
            .kick(vec![0, 4, 8, 12])
            .unwrap()
            .snare(vec![4, 12])
            .unwrap()
            .hihat(vec![0, 2, 4, 6, 8, 10, 12, 14])
            .unwrap()
            .grid();

        assert_eq!(grid.hits().len(), 3);
    }

    #[test]
    fn drum_grid_stores_and_applies_track_effects() {
        let grid = PulseDrumGrid::new()
            .sound("kick_808", vec![0, 4, 8, 12])
            .unwrap()
            .with_effect(test_compressor_effect());

        assert_eq!(grid.effects().len(), 1);

        let song = crate::composition::PulseSong::new().add_drum_grid(grid);
        let mixer = song.to_mixer().expect("drum grid should build");
        let tracks = mixer.all_tracks();

        assert_eq!(tracks.len(), 1);
        assert!(tracks[0].effects.compressor.is_some());
    }

    #[test]
    fn drum_grid_applies_volume_and_pan_to_exported_track() {
        let grid = PulseDrumGrid::new()
            .sound("kick_808", vec![0])
            .unwrap()
            .with_volume(0.8)
            .unwrap()
            .with_pan(0.2)
            .unwrap();

        let song = crate::composition::PulseSong::new().add_drum_grid(grid);
        let mixer = song.to_mixer().expect("drum grid should build");
        let tracks = mixer.all_tracks();

        assert_eq!(tracks.len(), 1);
        assert_eq!(tracks[0].volume, 0.8);
        assert_eq!(tracks[0].pan, 0.2);
    }

    #[test]
    fn drum_grid_expands_layered_aliases_into_exported_events() {
        let grid = PulseDrumGrid::new()
            .sound("kick_808_deep_layer", vec![0])
            .unwrap();

        let song = crate::composition::PulseSong::new().add_drum_grid(grid);
        let mixer = song.to_mixer().expect("layered drum grid should build");
        let tracks = mixer.all_tracks();
        let drum_events = tracks[0]
            .events
            .iter()
            .filter(|event| matches!(event, tunes::track::AudioEvent::Drum(_)))
            .count();

        assert_eq!(drum_events, 2);
    }
}