pointillism 0.4.3

A compositional library for musical composition.
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
//! Declares control structures, which can be used to execute events at specified time intervals.
//!
//! The main control structures are [`Seq`] and [`Loop`]. These can be used to modify a [`Signal`]
//! at regular time intervals. Note that the [`Signal`] won't be immediately modified when the [`Seq`] or [`Loop`] is
//! initialized. It will only be modified after the first time interval transpires. You can call
//! [`Seq::skip`] or [`Loop::skip`] in order to immediately skip to and apply the first event.
//!
//! Also note that the time interval between events can be zero. The effect of this is to execute
//! these events simultaneously.
//!
//! ## Type aliases
//!
//! This file also defines various useful type aliases. [`Arpeggio`] serves to arpeggiate a signal
//! by changing its frequency in periodic intervals. [`MelodySeq`] and [`MelodyLoop`] both
//! functionally serve as piano rolls for a polyphonic signal.

mod melody;
mod timer;

#[cfg(feature = "midly")]
pub use melody::MidiNoteData;
pub use melody::{MelLoop, MelSeq, Melody, Note, NoteEvent, NoteReader};
pub use timer::{Metronome, Timer};

use crate::prelude::*;

/// Changes a signal according to a specified function, at specified times.
///
/// See the [module docs](self) for more information.
#[derive(Clone, Debug)]
pub struct Seq<S: SignalMut, F: map::Mut<S>> {
    /// A list of time intervals between an event and the next.
    pub times: Vec<unt::Time>,
    /// Time since last event.
    since: unt::Time,
    /// The current event being read.
    index: usize,

    /// A signal being modified.
    sgn: S,
    /// The function modifying the signal.
    func: F,
}

impl<S: SignalMut, F: map::Mut<S>> Seq<S, F> {
    /// Initializes a new sequence.
    pub const fn new(times: Vec<unt::Time>, sgn: S, func: F) -> Self {
        Self {
            times,
            since: unt::Time::ZERO,
            index: 0,
            sgn,
            func,
        }
    }

    /// Time since last event.
    pub const fn since(&self) -> unt::Time {
        self.since
    }

    /// The current event index.
    pub const fn index(&self) -> usize {
        self.index
    }

    /// The number of events.
    pub fn len(&self) -> usize {
        self.times.len()
    }

    /// Whether there are no events in the sequence.
    pub fn is_empty(&self) -> bool {
        self.times.is_empty()
    }

    /// Returns the time for the current event.
    pub fn current_time(&self) -> Option<unt::Time> {
        self.times.get(self.index()).copied()
    }

    /// Returns a reference to the modified signal.
    pub const fn sgn(&self) -> &S {
        &self.sgn
    }

    /// Returns a mutable reference to the modified signal.
    pub fn sgn_mut(&mut self) -> &mut S {
        &mut self.sgn
    }

    /// Returns a reference to the function modifying the signal.
    pub const fn func(&self) -> &F {
        &self.func
    }

    /// Returns a mutable reference to the function modifying the signal.
    pub fn func_mut(&mut self) -> &mut F {
        &mut self.func
    }

    /// Modifies the signal according to the function.
    fn modify(&mut self) {
        self.func.modify(&mut self.sgn);
    }

    /// Skips to the next event and applies it, returns whether it was successful.
    ///
    /// This can be used right after initializing a [`Seq`] so that the first event is applied
    /// immediately.
    pub fn skip(&mut self) -> bool {
        let res = self.index < self.len();
        if res {
            self.since = unt::Time::ZERO;
            self.modify();
            self.index += 1;
        }
        res
    }

    /// Attempts to read a single event, returns whether it was successful.
    fn read_event(&mut self) -> bool {
        match self.current_time() {
            Some(event_time) => {
                let read = self.since() >= event_time;
                if read {
                    self.since -= event_time;
                    self.modify();
                    self.index += 1;
                }
                read
            }

            None => false,
        }
    }

    /// Reads all current events.
    fn read_events(&mut self) {
        while self.read_event() {}
    }

    /// The total time this sequence takes to complete.
    ///
    /// This method is expensive, as it must add all the times together.
    pub fn total_time(&self) -> unt::Time {
        self.times.iter().copied().sum()
    }
}

impl<S: SignalMut, F: map::Mut<S>> Signal for Seq<S, F> {
    type Sample = S::Sample;

    fn get(&self) -> S::Sample {
        self.sgn.get()
    }
}

impl<S: SignalMut, F: map::Mut<S>> SignalMut for Seq<S, F> {
    fn advance(&mut self) {
        self.sgn.advance();
        self.since.advance();
        self.read_events();
    }

    fn retrigger(&mut self) {
        self.sgn.retrigger();
        self.index = 0;
        self.since = unt::Time::ZERO;
    }
}

/// Changes a signal according to a specified function, at specified times. These times are looped.
///
/// Although it is not undefined behavior to initialize an empty loop, doing so will lead to panics
/// in other methods.
///
/// See the [module docs](self) for more information.
#[derive(Clone, Debug)]
pub struct Loop<S: SignalMut, F: map::Mut<S>> {
    /// The internal sequence.
    seq: Seq<S, F>,
}

impl<S: SignalMut, F: map::Mut<S>> Loop<S, F> {
    /// Turns a sequence into a loop.
    ///
    /// ## Panics
    ///
    /// This method panics if the sequence is empty.
    pub fn new_seq(seq: Seq<S, F>) -> Self {
        assert!(!seq.is_empty());
        Self { seq }
    }

    /// Initializes a new loop.
    ///
    /// ## Panics
    ///
    /// This method panics if the `times` vector is empty.
    pub fn new(times: Vec<unt::Time>, sgn: S, func: F) -> Self {
        Self::new_seq(Seq::new(times, sgn, func))
    }

    /// Time since last event.
    pub const fn since(&self) -> unt::Time {
        self.seq.since
    }

    /// The current event index.
    ///
    /// This index should, as a runtime invariant, always be less than the length of the loop,
    /// unless the loop is empty.
    pub const fn index(&self) -> usize {
        self.seq.index
    }

    /// The number of events in the loop.
    pub fn len(&self) -> usize {
        self.seq.times.len()
    }

    /// Whether there are no events in the loop.
    ///
    /// Note that such a loop might cause other methods to panic.
    pub fn is_empty(&self) -> bool {
        self.seq.times.is_empty()
    }

    /// Returns the time for the current event.
    ///
    /// ## Panics
    ///
    /// Panics if the loop is empty.
    pub fn current_time(&self) -> unt::Time {
        self.seq.current_time().expect("loop can't be empty")
    }

    /// Returns a reference to the modified signal.
    pub const fn sgn(&self) -> &S {
        &self.seq.sgn
    }

    /// Returns a mutable reference to the modified signal.
    pub fn sgn_mut(&mut self) -> &mut S {
        &mut self.seq.sgn
    }

    /// Returns a reference to the function modifying the signal.
    pub const fn func(&self) -> &F {
        &self.seq.func
    }

    /// Returns a mutable reference to the function modifying the signal.
    pub fn func_mut(&mut self) -> &mut F {
        &mut self.seq.func
    }

    /// Modifies the signal according to the function.
    fn modify(&mut self) {
        self.seq.modify();
    }

    /// Skips to the next event and applies it, returns whether it was successful.
    ///
    /// This can be used right after initializing a [`Loop`] so that the first event is applied
    /// immediately.
    ///
    /// ## Panics
    ///
    /// Panics if the loop is empty.
    pub fn skip(&mut self) {
        self.seq.since = unt::Time::ZERO;
        self.modify();
        crate::mod_inc(self.len(), &mut self.seq.index);
    }

    /// The total time this loop takes to complete.
    ///
    /// This method is expensive, as it must add all the times together.
    pub fn total_time(&self) -> unt::Time {
        self.seq.total_time()
    }
}

impl<S: SignalMut, F: map::Mut<S>> Signal for Loop<S, F> {
    type Sample = S::Sample;

    fn get(&self) -> Self::Sample {
        self.seq.sgn.get()
    }
}

impl<S: SignalMut, F: map::Mut<S>> SignalMut for Loop<S, F> {
    fn advance(&mut self) {
        self.seq.advance();

        if self.seq.index == self.len() {
            self.seq.index = 0;
        }
    }

    fn retrigger(&mut self) {
        self.seq.retrigger();
    }
}

/// The function that arpeggiates a signal.
///
/// This is used to implement [`Arpeggio`].
#[derive(Clone, Debug)]
pub struct Arp {
    /// The notes to play, in order.
    pub notes: Vec<unt::Freq>,

    /// The index of the note currently playing.
    pub index: usize,
}

impl Arp {
    /// Initializes a new arpeggio with the given notes.
    #[must_use]
    pub const fn new(notes: Vec<unt::Freq>) -> Self {
        Self { notes, index: 0 }
    }

    /// The currently played note.
    #[must_use]
    pub fn current(&self) -> unt::Freq {
        self.notes[self.index]
    }

    /// The length of the arpeggio.
    #[must_use]
    pub fn len(&self) -> usize {
        self.notes.len()
    }

    /// Whether the arpeggio has no notes.
    ///
    /// Note that this will generally result in other methods panicking, and thus should be avoided.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.notes.is_empty()
    }
}

impl<S: Frequency> map::Mut<S> for Arp {
    fn modify(&mut self, sgn: &mut S) {
        *sgn.freq_mut() = self.current();
        crate::mod_inc(self.len(), &mut self.index);
    }
}

/// An arpeggiated signal.
///
/// ## Example
///
/// We create a single arpeggio which plays two chords.
///
/// ```
/// # use pointillism::prelude::*;
/// // Basic parameters.
/// const SAMPLE_RATE: unt::SampleRate = unt::SampleRate::CD;
/// const NOTE_TIME: unt::RawTime = unt::RawTime::new(3.0 / 32.0);
/// const LENGTH: unt::RawTime = unt::RawTime::new(3.0);
///
/// let note_time = unt::Time::from_raw(NOTE_TIME, SAMPLE_RATE);
/// let length = unt::Time::from_raw(LENGTH, SAMPLE_RATE);
///
/// // The notes played in the arpeggio.
/// let notes = [unt::RawFreq::C4, unt::RawFreq::E4, unt::RawFreq::G4, unt::RawFreq::A4]
///     .map(|raw| unt::Freq::from_raw(raw, SAMPLE_RATE))
///     .to_vec();
///
/// // Initializes the arpeggio.
/// let mut arp = ctr::Arpeggio::new_arp(
///     vec![note_time],
///     gen::Loop::<smp::Mono, _>::new(crv::Tri, unt::Freq::ZERO),
///     notes,
/// );
///
/// // Zero is a dummy value that gets replaced here.
/// arp.skip();
///
/// let mut timer = ctr::Timer::new(length);
/// Song::new(2u8 * length, SAMPLE_RATE, |time| {
///     // We switch up the arpeggio after the first phrase.
///     if timer.tick(time) {
///         arp.notes_mut()[2] = unt::Freq::from_raw(unt::RawFreq::F4, SAMPLE_RATE);
///     }
///
///     arp.next()
/// })
/// .export("examples/arpeggio.wav");
/// ```
pub type Arpeggio<S> = Loop<S, Arp>;

impl<S: Frequency> Arpeggio<S> {
    /// Initializes a new [`Arpeggio`].
    ///
    /// Note that the note being played by the signal won't be updated until the first time interval
    /// transpires, unless you call [`Self::skip`].
    ///
    /// ## Panics
    ///
    /// This method panics if the `times` vector is empty.
    pub fn new_arp(times: Vec<unt::Time>, sgn: S, notes: Vec<unt::Freq>) -> Self {
        Self::new(times, sgn, Arp::new(notes))
    }

    /// Returns a reference to the [`Arp`].
    pub const fn arp(&self) -> &Arp {
        self.func()
    }

    /// Returns a mutable reference to the [`Arp`].
    pub fn arp_mut(&mut self) -> &mut Arp {
        self.func_mut()
    }

    /// Returns a reference to the notes.
    pub fn notes(&self) -> &[unt::Freq] {
        &self.arp().notes
    }

    /// Returns a mutable reference to the notes.
    pub fn notes_mut(&mut self) -> &mut [unt::Freq] {
        &mut self.arp_mut().notes
    }
}