tunes 1.1.0

A music composition, synthesis, and audio generation library
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
use super::TrackBuilder;
use crate::instruments::drums::DrumType;

impl<'a> TrackBuilder<'a> {
    /// Add a note or chord at the current cursor position
    pub fn note(mut self, frequencies: &[f32], duration: f32) -> Self {
        let cursor = self.cursor;
        let waveform = self.waveform;
        let envelope = self.envelope;
        let filter_envelope = self.filter_envelope;
        let fm_params = self.fm_params;
        let pitch_bend = self.pitch_bend;
        let custom_wavetable = self.custom_wavetable.clone();
        let velocity = self.velocity;
        let spatial_position = self.spatial_position;

        self.get_track_mut().add_note_with_complete_params(
            frequencies,
            cursor,
            duration,
            waveform,
            envelope,
            filter_envelope,
            fm_params,
            pitch_bend,
            custom_wavetable,
            velocity,
            spatial_position,
        );
        let swung_duration = self.apply_swing(duration);
        self.cursor += swung_duration;
        self.update_section_duration();
        self
    }

    /// Add a drum hit at the current cursor position
    ///
    /// # Arguments
    /// * `drum_type` - The type of drum sound to play
    /// * `duration` - How long to wait before the next event (cursor advance)
    ///
    /// # Example
    /// ```
    /// # use tunes::prelude::*;
    /// # let mut comp = Composition::new(Tempo::new(120.0));
    /// comp.track("drums")
    ///     .drum(DrumType::Kick, 0.5)
    ///     .drum(DrumType::Snare, 0.5)
    ///     .drum(DrumType::Kick, 0.25)
    ///     .drum(DrumType::Kick, 0.25);
    /// ```
    pub fn drum(mut self, drum_type: DrumType, duration: f32) -> Self {
        let cursor = self.cursor;
        let spatial_position = self.spatial_position;
        self.get_track_mut().add_drum(drum_type, cursor, spatial_position);
        let swung_duration = self.apply_swing(duration);
        self.cursor += swung_duration;
        self.update_section_duration();
        self
    }

    /// Play a sample at the current cursor position
    ///
    /// The sample must be previously loaded using `comp.load_sample()`.
    ///
    /// # Arguments
    /// * `sample_name` - Name of the loaded sample
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// # fn main() -> anyhow::Result<()> {
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// comp.load_sample("kick", "samples/kick.wav")?;
    ///
    /// comp.track("drums")
    ///     .sample("kick")  // Play at cursor position
    ///     .sample("kick");  // Play again
    /// # Ok(())
    /// # }
    /// ```
    pub fn sample(mut self, sample_name: &str) -> Self {
        let cursor = self.cursor;

        // Get the sample from the composition's cache
        let sample = match self.composition.get_sample(sample_name) {
            Some(s) => s.clone(),
            None => {
                eprintln!(
                    "Warning: Sample '{}' not found. Load it first with comp.load_sample(). Skipping sample event.",
                    sample_name
                );
                return self;
            }
        };

        // Add the sample event
        use crate::track::{AudioEvent, SampleEvent};
        let sample_event = SampleEvent::new(sample.clone(), cursor);
        let duration = sample.duration;

        self.get_track_mut()
            .events
            .push(AudioEvent::Sample(sample_event));
        self.get_track_mut().invalidate_time_cache();

        let swung_duration = self.apply_swing(duration);
        self.cursor += swung_duration;
        self.update_section_duration();
        self
    }

    /// Play a Sample directly (without pre-loading into cache)
    ///
    /// Use this to play samples or sample slices directly without needing to
    /// load them into the composition's sample cache first.
    ///
    /// # Arguments
    /// * `sample` - The Sample to play
    /// * `playback_rate` - Speed multiplier (1.0 = normal, 2.0 = double speed, 0.5 = half speed)
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// # fn main() -> anyhow::Result<()> {
    /// let mut comp = Composition::new(Tempo::new(120.0));
    ///
    /// // Load and slice a sample
    /// let sample = Sample::from_file("drumloop.wav")?;
    /// let slices = sample.slice_equal(16)?;
    ///
    /// // Play slices directly without caching
    /// comp.track("drums")
    ///     .play_sample(&slices[0].to_sample()?, 1.0)   // Kick
    ///     .at(0.5).play_sample(&slices[4].to_sample()?, 1.0)   // Snare
    ///     .at(1.0).play_sample(&slices[8].to_sample()?, 1.0);  // Kick
    /// # Ok(())
    /// # }
    /// ```
    pub fn play_sample(mut self, sample: &crate::synthesis::Sample, playback_rate: f32) -> Self {
        let cursor = self.cursor;

        use crate::track::{AudioEvent, SampleEvent};
        let sample_event =
            SampleEvent::new(sample.clone(), cursor).with_playback_rate(playback_rate);
        let duration = sample.duration / playback_rate;

        self.get_track_mut()
            .events
            .push(AudioEvent::Sample(sample_event));
        self.get_track_mut().invalidate_time_cache();

        let swung_duration = self.apply_swing(duration);
        self.cursor += swung_duration;
        self.update_section_duration();
        self
    }

    /// Play a SampleSlice directly
    ///
    /// Convenience method for playing slices. This converts the slice to a Sample
    /// and plays it, so there's a copy overhead. For repeated playback of the same
    /// slice, consider converting once with `.to_sample()` and reusing it.
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// # use tunes::synthesis::Sample;
    /// # fn main() -> anyhow::Result<()> {
    /// let mut comp = Composition::new(Tempo::new(140.0));
    ///
    /// let sample = Sample::from_file("drumloop.wav")?;
    /// let slices = sample.slice_by_transients(0.3, 50.0)?;
    ///
    /// // Play each detected hit
    /// let mut track = comp.track("drums");
    /// for slice in &slices {
    ///     let pos = track.peek_cursor() + 0.25;
    ///     track = track.play_slice(slice, 1.0)?.at(pos);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn play_slice(
        self,
        slice: &crate::synthesis::SampleSlice,
        playback_rate: f32,
    ) -> Result<Self, crate::error::TunesError> {
        let sample = slice.to_sample()?;
        Ok(self.play_sample(&sample, playback_rate))
    }

    /// Play a sample with custom playback rate
    ///
    /// # Arguments
    /// * `sample_name` - Name of the loaded sample
    /// * `playback_rate` - Speed multiplier (1.0 = normal, 2.0 = double speed/octave up, 0.5 = half speed/octave down)
    ///
    /// # Example
    /// ```no_run
    /// # use tunes::prelude::*;
    /// # fn main() -> anyhow::Result<()> {
    /// let mut comp = Composition::new(Tempo::new(120.0));
    /// comp.load_sample("kick", "samples/kick.wav")?;
    ///
    /// comp.track("drums")
    ///     .sample_with_rate("kick", 1.0)   // Normal speed
    ///     .sample_with_rate("kick", 2.0)   // Double speed (octave up)
    ///     .sample_with_rate("kick", 0.5);  // Half speed (octave down)
    /// # Ok(())
    /// # }
    /// ```
    pub fn sample_with_rate(mut self, sample_name: &str, playback_rate: f32) -> Self {
        let cursor = self.cursor;

        let sample = match self.composition.get_sample(sample_name) {
            Some(s) => s.clone(),
            None => {
                eprintln!(
                    "Warning: Sample '{}' not found. Load it first with comp.load_sample(). Skipping sample event.",
                    sample_name
                );
                return self;
            }
        };

        use crate::track::{AudioEvent, SampleEvent};
        let sample_event =
            SampleEvent::new(sample.clone(), cursor).with_playback_rate(playback_rate);
        let duration = sample.duration / playback_rate;

        self.get_track_mut()
            .events
            .push(AudioEvent::Sample(sample_event));
        self.get_track_mut().invalidate_time_cache();

        let swung_duration = self.apply_swing(duration);
        self.cursor += swung_duration;
        self.update_section_duration();
        self
    }

    /// Add an interpolated sequence starting at the current cursor position
    pub fn interpolated(
        mut self,
        start_freq: f32,
        end_freq: f32,
        segments: usize,
        note_duration: f32,
    ) -> Self {
        // Handle edge cases
        if segments == 0 {
            return self; // Nothing to play
        }

        let waveform = self.waveform;
        let envelope = self.envelope;

        if segments == 1 {
            // Just play the start frequency
            let cursor = self.cursor;
            self.get_track_mut().add_note_with_waveform_and_envelope(
                &[start_freq],
                cursor,
                note_duration,
                waveform,
                envelope,
            );
            self.cursor += note_duration;
            self.update_section_duration();
            return self;
        }

        for i in 0..segments {
            let t = i as f32 / (segments - 1) as f32;
            let freq = start_freq + (end_freq - start_freq) * t;
            let cursor = self.cursor;
            self.get_track_mut().add_note_with_waveform_and_envelope(
                &[freq],
                cursor,
                note_duration,
                waveform,
                envelope,
            );
            self.cursor += note_duration;
        }
        self.update_section_duration();
        self
    }

    /// Add a sequence of notes with equal duration starting at the current cursor position
    pub fn notes(mut self, frequencies: &[f32], note_duration: f32) -> Self {
        let waveform = self.waveform;
        let envelope = self.envelope;
        let filter_envelope = self.filter_envelope;
        let fm_params = self.fm_params;
        let pitch_bend = self.pitch_bend;
        let custom_wavetable = self.custom_wavetable.clone();
        let velocity = self.velocity;
        let spatial_position = self.spatial_position;

        for &freq in frequencies {
            let cursor = self.cursor;
            self.get_track_mut().add_note_with_complete_params(
                &[freq],
                cursor,
                note_duration,
                waveform,
                envelope,
                filter_envelope,
                fm_params,
                pitch_bend,
                custom_wavetable.clone(),
                velocity,
                spatial_position,
            );
            let swung_duration = self.apply_swing(note_duration);
            self.cursor += swung_duration;
        }
        self.update_section_duration();
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::composition::Composition;
    use crate::consts::notes::*;
    use crate::composition::timing::Tempo;
    use crate::track::AudioEvent;

    #[test]
    fn test_note_adds_single_note() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("test").note(&[440.0], 1.0);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 1);

        if let AudioEvent::Note(note) = &track.events[0] {
            assert_eq!(note.frequencies[0], 440.0);
            assert_eq!(note.start_time, 0.0);
            assert_eq!(note.duration, 1.0);
        } else {
            panic!("Expected NoteEvent");
        }
    }

    #[test]
    fn test_note_advances_cursor() {
        let mut comp = Composition::new(Tempo::new(120.0));
        let builder = comp.track("test").note(&[440.0], 1.0);

        // Cursor should have advanced by the note duration
        assert_eq!(builder.cursor, 1.0);
    }

    #[test]
    fn test_note_chaining() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("test")
            .note(&[440.0], 0.5)
            .note(&[550.0], 0.5)
            .note(&[660.0], 0.5);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 3);

        // Verify timing
        if let AudioEvent::Note(note) = &track.events[0] {
            assert_eq!(note.start_time, 0.0);
        }
        if let AudioEvent::Note(note) = &track.events[1] {
            assert_eq!(note.start_time, 0.5);
        }
        if let AudioEvent::Note(note) = &track.events[2] {
            assert_eq!(note.start_time, 1.0);
        }
    }

    #[test]
    fn test_note_with_chord() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("test").note(&[440.0, 554.37, 659.25], 1.0); // A major chord

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 1);

        if let AudioEvent::Note(note) = &track.events[0] {
            assert_eq!(note.num_freqs, 3);
            assert_eq!(note.frequencies[0], 440.0);
            assert_eq!(note.frequencies[1], 554.37);
            assert_eq!(note.frequencies[2], 659.25);
        }
    }

    #[test]
    fn test_drum_adds_drum_hit() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("drums").drum(DrumType::Kick, 0.0);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 1);

        if let AudioEvent::Drum(drum) = &track.events[0] {
            assert!(matches!(drum.drum_type, DrumType::Kick));
            assert_eq!(drum.start_time, 0.0);
        } else {
            panic!("Expected DrumEvent");
        }
    }

    #[test]
    fn test_drum_advances_cursor_by_duration() {
        let mut comp = Composition::new(Tempo::new(120.0));
        let builder = comp.track("drums").drum(DrumType::Kick, 0.5);

        // Cursor should advance by specified duration (0.5s)
        assert_eq!(builder.cursor, 0.5);
    }

    #[test]
    fn test_drum_chaining() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("drums")
            .drum(DrumType::Kick, 0.25)
            .drum(DrumType::Snare, 0.25)
            .drum(DrumType::HiHatClosed, 0.0);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 3);

        // Verify different drum types
        if let AudioEvent::Drum(drum) = &track.events[0] {
            assert!(matches!(drum.drum_type, DrumType::Kick));
        }
        if let AudioEvent::Drum(drum) = &track.events[1] {
            assert!(matches!(drum.drum_type, DrumType::Snare));
        }
        if let AudioEvent::Drum(drum) = &track.events[2] {
            assert!(matches!(drum.drum_type, DrumType::HiHatClosed));
        }
    }

    #[test]
    fn test_interpolated_creates_smooth_glide() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("melody").interpolated(440.0, 880.0, 5, 0.1);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 5);

        // Verify frequencies interpolate smoothly
        let expected_freqs = [440.0, 550.0, 660.0, 770.0, 880.0];
        for (i, expected) in expected_freqs.iter().enumerate() {
            if let AudioEvent::Note(note) = &track.events[i] {
                assert_eq!(note.frequencies[0], *expected);
                assert_eq!(note.start_time, i as f32 * 0.1);
            }
        }
    }

    #[test]
    fn test_interpolated_with_zero_segments() {
        let mut comp = Composition::new(Tempo::new(120.0));
        let builder = comp.track("melody").interpolated(440.0, 880.0, 0, 0.1);

        // Check cursor first before moving comp
        assert_eq!(builder.cursor, 0.0, "Cursor should not advance");

        let mixer = comp.into_mixer();
        // With zero segments, no track is created since interpolated returns early
        assert_eq!(
            mixer.tracks().len(),
            0,
            "Zero segments should create no track"
        );
    }

    #[test]
    fn test_interpolated_with_one_segment() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("melody").interpolated(440.0, 880.0, 1, 0.5);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 1);

        if let AudioEvent::Note(note) = &track.events[0] {
            assert_eq!(note.frequencies[0], 440.0); // Should use start freq
            assert_eq!(note.duration, 0.5);
        }
    }

    #[test]
    fn test_notes_creates_sequence() {
        let mut comp = Composition::new(Tempo::new(120.0));
        let freqs = [C4, E4, G4, C5]; // C major arpeggio
        comp.track("melody").notes(&freqs, 0.25);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 4);

        for (i, &expected_freq) in freqs.iter().enumerate() {
            if let AudioEvent::Note(note) = &track.events[i] {
                assert_eq!(note.frequencies[0], expected_freq);
                assert_eq!(note.start_time, i as f32 * 0.25);
                assert_eq!(note.duration, 0.25);
            }
        }
    }

    #[test]
    fn test_notes_with_empty_array() {
        let mut comp = Composition::new(Tempo::new(120.0));
        let builder = comp.track("melody").notes(&[], 0.5);

        // Check cursor first before moving comp
        assert_eq!(
            builder.cursor, 0.0,
            "Cursor should not advance for empty array"
        );

        let mixer = comp.into_mixer();
        // With empty array, no track is created since loop doesn't execute
        assert_eq!(mixer.tracks().len(), 0, "Empty array should create no track");
    }

    #[test]
    fn test_notes_advances_cursor_correctly() {
        let mut comp = Composition::new(Tempo::new(120.0));
        let freqs = [440.0, 550.0, 660.0];
        let builder = comp.track("melody").notes(&freqs, 0.5);

        // Cursor should advance by num_notes * duration
        assert_eq!(builder.cursor, 1.5); // 3 notes * 0.5s
    }

    #[test]
    fn test_mixed_notes_and_drums() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.track("mixed")
            .note(&[440.0], 0.5)
            .drum(DrumType::Kick, 0.25)
            .note(&[550.0], 0.5)
            .drum(DrumType::Snare, 0.0);

        let track = &comp.into_mixer().tracks()[0];
        assert_eq!(track.events.len(), 4);

        // Verify alternating pattern
        assert!(matches!(track.events[0], AudioEvent::Note(_)));
        assert!(matches!(track.events[1], AudioEvent::Drum(_)));
        assert!(matches!(track.events[2], AudioEvent::Note(_)));
        assert!(matches!(track.events[3], AudioEvent::Drum(_)));
    }
}