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
//! Arrangement and section system for composing larger musical structures
//!
//! This module provides tools for creating reusable sections (verse, chorus, bridge, etc.)
//! and arranging them into complete compositions.

use crate::composition::Composition;
use crate::synthesis::envelope::Envelope;
use crate::synthesis::filter_envelope::FilterEnvelope;
use crate::synthesis::fm_synthesis::FMParams;
use crate::instruments::Instrument;
use crate::composition::timing::Tempo;
use crate::track::{AudioEvent, Track};
use crate::synthesis::waveform::Waveform;
use std::collections::HashMap;

/// A reusable section of music that can be arranged in a composition
///
/// Sections capture a portion of music with multiple tracks that can be
/// repeated and sequenced. Think of them like verse, chorus, bridge, intro, etc.
#[derive(Clone, Debug)]
pub struct Section {
    pub(crate) name: String,
    pub(crate) tracks: HashMap<String, Track>,
    pub(crate) duration: f32, // Total duration of this section in seconds
}

impl Section {
    /// Create a new empty section
    pub fn new(name: String) -> Self {
        Self {
            name,
            tracks: HashMap::new(),
            duration: 0.0,
        }
    }

    /// Get the name of this section
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the duration of this section in seconds
    pub fn duration(&self) -> f32 {
        self.duration
    }

    /// Clone this section's events and offset them by a time delta
    ///
    /// This is used internally by the arrangement system to place sections
    /// at different points in time.
    pub(crate) fn clone_with_offset(&self, time_offset: f32) -> HashMap<String, Track> {
        self.tracks
            .iter()
            .map(|(name, track)| {
                let mut new_track = track.clone();
                // Offset all event times
                for event in &mut new_track.events {
                    match event {
                        AudioEvent::Note(note) => {
                            note.start_time += time_offset;
                        }
                        AudioEvent::Drum(drum) => {
                            drum.start_time += time_offset;
                        }
                        AudioEvent::Sample(sample) => {
                            sample.start_time += time_offset;
                        }
                        AudioEvent::TempoChange(tempo) => {
                            tempo.start_time += time_offset;
                        }
                        AudioEvent::TimeSignature(time_sig) => {
                            time_sig.start_time += time_offset;
                        }
                        AudioEvent::KeySignature(key_sig) => {
                            key_sig.start_time += time_offset;
                        }
                    }
                }
                (name.clone(), new_track)
            })
            .collect()
    }
}

/// Builder for creating musical sections
///
/// SectionBuilder works similarly to Composition - you add tracks and events,
/// but the section is stored for later reuse in arrangements.
pub struct SectionBuilder<'a> {
    composition: &'a mut Composition,
    section_name: String,
    tempo: Tempo,
}

impl<'a> SectionBuilder<'a> {
    /// Create a new section builder
    pub(crate) fn new(composition: &'a mut Composition, name: String, tempo: Tempo) -> Self {
        Self {
            composition,
            section_name: name,
            tempo,
        }
    }

    /// Get or create a track within this section
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::consts::notes::*;
    /// # let mut comp = Composition::new(Tempo::new(120.0));
    /// comp.section("verse")
    ///     .track("melody")
    ///     .notes(&[C4, E4, G4], 0.5);
    /// ```
    pub fn track(self, name: &str) -> crate::composition::TrackBuilder<'a> {
        crate::composition::TrackBuilder {
            composition: self.composition,
            context: crate::composition::BuilderContext::Section(self.section_name),
            track_name: name.to_string(),
            bus_name: "default".to_string(),
            cursor: 0.0,
            pattern_start: 0.0,
            waveform: Waveform::Sine,
            envelope: Envelope::default(),
            filter_envelope: FilterEnvelope::default(),
            fm_params: FMParams::default(),
            swing: 0.5,
            swing_counter: 0,
            pitch_bend: 0.0,
            tempo: self.tempo,
            custom_wavetable: None,
            velocity: 0.8,
            spatial_position: None,
            last_chord: None,
        }
    }

    /// Create a track with an instrument preset within this section
    ///
    /// # Example
    /// ```
    /// # use tunes::composition::Composition;
    /// # use tunes::composition::timing::Tempo;
    /// # use tunes::instruments::Instrument;
    /// # use tunes::consts::notes::*;
    /// # let mut comp = Composition::new(Tempo::new(120.0));
    /// comp.section("chorus")
    ///     .instrument("lead", &Instrument::synth_lead())
    ///     .notes(&[E4, G4, B4], 0.25);
    /// ```
    pub fn instrument(
        self,
        name: &str,
        instrument: &Instrument,
    ) -> crate::composition::TrackBuilder<'a> {
        let mut builder = crate::composition::TrackBuilder {
            composition: self.composition,
            context: crate::composition::BuilderContext::Section(self.section_name),
            track_name: name.to_string(),
            bus_name: "default".to_string(),
            cursor: 0.0,
            pattern_start: 0.0,
            waveform: instrument.waveform,
            envelope: instrument.envelope,
            filter_envelope: FilterEnvelope::default(),
            fm_params: FMParams::default(),
            swing: 0.5,
            swing_counter: 0,
            pitch_bend: 0.0,
            tempo: self.tempo,
            custom_wavetable: None,
            velocity: 0.8,
            spatial_position: None,
            last_chord: None,
        };

        // Get or create the track and apply instrument settings
        builder.get_track_mut().apply_instrument(instrument);

        builder
    }
}

impl Track {
    /// Apply instrument settings to this track
    pub(crate) fn apply_instrument(&mut self, instrument: &Instrument) {
        self.volume = instrument.volume;
        self.pan = instrument.pan;
        self.filter = instrument.filter;
        self.effects.delay = instrument.delay.clone();
        self.effects.reverb = instrument.reverb.clone();
        self.effects.distortion = instrument.distortion.clone();
        self.modulation = instrument.modulation.clone();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::instruments::drums::DrumType;
    use crate::consts::notes::*;

    #[test]
    fn test_create_empty_section() {
        let mut comp = Composition::new(Tempo::new(120.0));
        comp.section("intro");

        assert!(comp.sections.contains_key("intro"));
    }

    #[test]
    fn test_section_duration_tracking() {
        let section = Section::new("test".to_string());
        assert_eq!(section.duration(), 0.0);
    }

    #[test]
    fn test_section_clone_with_offset() {
        let mut section = Section::new("test".to_string());
        let mut track = Track::new();
        track.add_note(&[C4], 0.0, 1.0);
        track.add_note(&[E4], 1.0, 1.0);
        section.tracks.insert("melody".to_string(), track);

        let offset_tracks = section.clone_with_offset(4.0);
        let melody = &offset_tracks["melody"];

        if let AudioEvent::Note(note) = &melody.events[0] {
            assert_eq!(note.start_time, 4.0);
        }
        if let AudioEvent::Note(note) = &melody.events[1] {
            assert_eq!(note.start_time, 5.0);
        }
    }

    #[test]
    fn test_section_with_notes() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("verse")
            .track("melody")
            .notes(&[C4, E4, G4, C5], 0.5);

        let section = comp.sections.get("verse").unwrap();
        let melody = section.tracks.get("melody").unwrap();

        assert_eq!(melody.events.len(), 4);
        assert_eq!(section.duration, 2.0); // 4 notes * 0.5s each
    }

    #[test]
    fn test_section_with_multiple_tracks() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("chorus")
            .track("melody")
            .notes(&[C4, E4], 0.5)
            .and()
            .track("bass")
            .notes(&[C2, G2], 1.0);

        let section = comp.sections.get("chorus").unwrap();

        assert_eq!(section.tracks.len(), 2);
        assert!(section.tracks.contains_key("melody"));
        assert!(section.tracks.contains_key("bass"));
        assert_eq!(section.duration, 2.0); // Bass track is longer
    }

    #[test]
    fn test_section_with_drums() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("beat")
            .track("drums")
            .drum(DrumType::Kick, 0.5)
            .drum(DrumType::Snare, 0.5)
            .drum(DrumType::Kick, 0.5)
            .drum(DrumType::Snare, 0.0);

        let section = comp.sections.get("beat").unwrap();
        let drums = section.tracks.get("drums").unwrap();

        assert_eq!(drums.events.len(), 4);
    }

    #[test]
    fn test_arrange_single_section() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("verse").track("melody").notes(&[C4, E4], 0.5);

        comp.arrange(&["verse"]);

        let melody = comp.tracks.get("melody").unwrap();
        assert_eq!(melody.events.len(), 2);
    }

    #[test]
    fn test_arrange_multiple_sections() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("intro").track("melody").note(&[C4], 1.0);

        comp.section("verse").track("melody").notes(&[E4, G4], 0.5);

        comp.arrange(&["intro", "verse"]);

        let melody = comp.tracks.get("melody").unwrap();
        assert_eq!(melody.events.len(), 3); // 1 from intro + 2 from verse

        // Check timing
        if let AudioEvent::Note(note) = &melody.events[0] {
            assert_eq!(note.start_time, 0.0); // Intro note
        }
        if let AudioEvent::Note(note) = &melody.events[1] {
            assert_eq!(note.start_time, 1.0); // First verse note (after 1s intro)
        }
        if let AudioEvent::Note(note) = &melody.events[2] {
            assert_eq!(note.start_time, 1.5); // Second verse note
        }
    }

    #[test]
    fn test_arrange_repeated_section() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("chorus").track("melody").notes(&[C4, E4], 0.5);

        comp.arrange(&["chorus", "chorus"]);

        let melody = comp.tracks.get("melody").unwrap();
        assert_eq!(melody.events.len(), 4); // 2 notes × 2 repetitions

        // Check timing
        if let AudioEvent::Note(note) = &melody.events[0] {
            assert_eq!(note.start_time, 0.0);
        }
        if let AudioEvent::Note(note) = &melody.events[2] {
            assert_eq!(note.start_time, 1.0); // Second chorus starts after first (1s)
        }
    }

    #[test]
    fn test_section_pattern_repeat() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("riff")
            .track("guitar")
            .pattern_start()
            .notes(&[C4, E4], 0.25)
            .repeat(2);

        let section = comp.sections.get("riff").unwrap();
        let guitar = section.tracks.get("guitar").unwrap();

        assert_eq!(guitar.events.len(), 6); // 2 notes + (2 notes × 2 repeats)
        assert_eq!(section.duration, 1.5); // Original 0.5s + 2 repeats × 0.5s
    }

    #[test]
    fn test_complex_arrangement() {
        let mut comp = Composition::new(Tempo::new(120.0));

        // Define sections
        comp.section("intro").track("melody").notes(&[C4], 2.0);

        comp.section("verse").track("melody").notes(&[E4, G4], 1.0);

        comp.section("chorus")
            .track("melody")
            .notes(&[C5, B4, A4, G4], 0.5);

        // Arrange: intro, verse, chorus, verse
        comp.arrange(&["intro", "verse", "chorus", "verse"]);

        let melody = comp.tracks.get("melody").unwrap();

        // Total events: 1 + 2 + 4 + 2 = 9
        assert_eq!(melody.events.len(), 9);

        // Check last note timing
        // intro: 2s, verse: 2s, chorus: 2s, verse starts at 6s
        if let AudioEvent::Note(note) = &melody.events[8] {
            assert_eq!(note.start_time, 7.0); // 6s + 1s
        }
    }

    #[test]
    fn test_section_at_positioning() {
        let mut comp = Composition::new(Tempo::new(120.0));

        comp.section("test")
            .track("melody")
            .at(1.0)
            .note(&[C4], 0.5)
            .at(3.0)
            .note(&[E4], 0.5);

        let section = comp.sections.get("test").unwrap();
        let melody = section.tracks.get("melody").unwrap();

        if let AudioEvent::Note(note) = &melody.events[0] {
            assert_eq!(note.start_time, 1.0);
        }
        if let AudioEvent::Note(note) = &melody.events[1] {
            assert_eq!(note.start_time, 3.0);
        }
    }
}