firewheel_core/
clock.rs

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
use std::ops::{Add, AddAssign, Sub, SubAssign};

use crate::node::ProcInfo;

/// When a particular audio event should occur.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EventDelay {
    /// The event should happen when the clock reaches the given time in
    /// seconds.
    ///
    /// Note, this clock is not perfectly accurate, but it does correctly
    /// account for any output underflows that may occur.
    ///
    /// The value is an absolute time, *NOT* a delta time. Use
    /// [`FirewheelCtx::clock_now`] to get the current time of the clock.
    DelayUntilSeconds(ClockSeconds),

    /// The event should happen when the clock reaches the given time in
    /// samples (of a single channel of audio).
    ///
    /// This is more accurate than `DelayUntilSeconds`, but it does not
    /// account for any output underflows that may occur. This clock is
    /// ideal for syncing events to a custom musical transport.
    ///
    /// The value is an absolute time, *NOT* a delta time. Use
    /// [`FirewheelCtx::clock_samples`] to get the current time of the clock.
    DelayUntilSamples(ClockSamples),

    /// The event should happen when the musical clock reaches the given
    /// musical time.
    ///
    /// Like `DelayUntilSamples`, this is very accurate, but note it also
    /// does not account for any output underflows that may occur.
    DelayUntilMusical(MusicalTime),
}

impl EventDelay {
    pub fn elapsed_or_get(&self, proc_info: &ProcInfo) -> Option<Self> {
        match self {
            EventDelay::DelayUntilSeconds(seconds) => {
                if *seconds <= proc_info.clock_seconds.start {
                    None
                } else {
                    Some(*self)
                }
            }
            EventDelay::DelayUntilSamples(samples) => {
                if *samples <= proc_info.clock_samples {
                    None
                } else {
                    Some(*self)
                }
            }
            EventDelay::DelayUntilMusical(musical) => {
                if let Some(transport) = &proc_info.transport_info {
                    if transport.paused || *musical <= transport.musical_clock.start {
                        None
                    } else {
                        Some(*self)
                    }
                } else {
                    None
                }
            }
        }
    }

    pub fn elapsed_on_frame(&self, proc_info: &ProcInfo, sample_rate: u32) -> Option<usize> {
        match self {
            EventDelay::DelayUntilSeconds(seconds) => {
                if *seconds <= proc_info.clock_seconds.start {
                    Some(0)
                } else if *seconds >= proc_info.clock_seconds.end {
                    None
                } else {
                    let frame = ((seconds.0 - proc_info.clock_seconds.start.0)
                        * f64::from(sample_rate))
                    .round() as usize;

                    if frame >= proc_info.frames {
                        None
                    } else {
                        Some(frame)
                    }
                }
            }
            EventDelay::DelayUntilSamples(samples) => {
                if *samples <= proc_info.clock_samples {
                    Some(0)
                } else {
                    let frame = samples.0 - proc_info.clock_samples.0;

                    if frame >= proc_info.frames as i64 {
                        None
                    } else {
                        Some(frame as usize)
                    }
                }
            }
            EventDelay::DelayUntilMusical(musical) => {
                if let Some(transport) = &proc_info.transport_info {
                    if transport.paused || *musical >= transport.musical_clock.end {
                        None
                    } else if *musical <= transport.musical_clock.start {
                        Some(0)
                    } else {
                        let frame = transport.transport.musical_to_sample(*musical, sample_rate)
                            - proc_info.clock_samples;

                        if frame.0 >= proc_info.frames as i64 {
                            None
                        } else {
                            Some(frame.0 as usize)
                        }
                    }
                } else {
                    None
                }
            }
        }
    }
}

/// An absolute clock time in units of seconds.
#[repr(transparent)]
#[derive(Default, Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct ClockSeconds(pub f64);

impl Add for ClockSeconds {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl Sub for ClockSeconds {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl AddAssign for ClockSeconds {
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl SubAssign for ClockSeconds {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

impl From<f64> for ClockSeconds {
    fn from(value: f64) -> Self {
        Self(value)
    }
}

impl Into<f64> for ClockSeconds {
    fn into(self) -> f64 {
        self.0
    }
}

/// An absolute clock time in units of samples (in a single channel of audio).
#[repr(transparent)]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClockSamples(pub i64);

impl ClockSamples {
    pub const fn new(samples: i64) -> Self {
        Self(samples)
    }

    pub fn from_secs_f64(seconds: f64, sample_rate: u32) -> Self {
        let seconds_i64 = seconds.floor() as i64;
        let fract_samples_i64 = (seconds.fract() * f64::from(sample_rate)).round() as i64;

        Self((seconds_i64 * i64::from(sample_rate)) + fract_samples_i64)
    }

    /// (whole seconds, samples *after* whole seconds)
    pub fn whole_seconds_and_fract(&self, sample_rate: u32) -> (i64, u32) {
        let whole_seconds = self.0 / i64::from(sample_rate);
        let fract_samples = self.0 % i64::from(sample_rate);

        if fract_samples < 0 {
            (
                whole_seconds - 1,
                sample_rate - (fract_samples.abs() as u32),
            )
        } else {
            (whole_seconds, fract_samples as u32)
        }
    }

    #[inline]
    pub fn fract_second_samples(&self, sample_rate: u32) -> u32 {
        (self.0 % i64::from(sample_rate)) as u32
    }

    pub fn as_secs_f64(&self, sample_rate: u32, sample_rate_recip: f64) -> f64 {
        let whole_seconds = self.0 / i64::from(sample_rate);
        let fract_samples = self.0 % i64::from(sample_rate);

        whole_seconds as f64 + (fract_samples as f64 * sample_rate_recip)
    }
}

impl Add for ClockSamples {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl Sub for ClockSamples {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl AddAssign for ClockSamples {
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl SubAssign for ClockSamples {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

impl From<i64> for ClockSamples {
    fn from(value: i64) -> Self {
        Self(value)
    }
}

impl Into<i64> for ClockSamples {
    fn into(self) -> i64 {
        self.0
    }
}

/// Musical time in units of beats.
#[derive(Default, Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct MusicalTime(pub f64);

impl MusicalTime {
    pub const fn new(beats: f64) -> Self {
        Self(beats)
    }

    /// Convert to the corresponding time in samples.
    pub fn to_sample_time(&self, seconds_per_beat: f64, sample_rate: u32) -> ClockSamples {
        let secs_f64 = self.0 * seconds_per_beat;
        ClockSamples::from_secs_f64(secs_f64, sample_rate)
    }

    /// Convert from the corresponding time in samples.
    pub fn from_sample_time(
        sample_time: ClockSamples,
        beats_per_second: f64,
        sample_rate: u32,
        sample_rate_recip: f64,
    ) -> Self {
        let secs_f64 = sample_time.as_secs_f64(sample_rate, sample_rate_recip);
        MusicalTime(secs_f64 * beats_per_second)
    }
}

pub fn seconds_per_beat(beats_per_minute: f64) -> f64 {
    60.0 / beats_per_minute
}

pub fn beats_per_second(beats_per_minute: f64) -> f64 {
    beats_per_minute * (1.0 / 60.0)
}

impl Add for MusicalTime {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl Sub for MusicalTime {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl AddAssign for MusicalTime {
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl SubAssign for MusicalTime {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MusicalTransport {
    beats_per_minute: f64,
    seconds_per_beat: f64,
    // TODO: Automated tempo?
}

impl MusicalTransport {
    pub fn new(beats_per_minute: f64) -> Self {
        Self {
            beats_per_minute,
            seconds_per_beat: seconds_per_beat(beats_per_minute),
        }
    }

    pub fn beats_per_minute(&self) -> f64 {
        self.beats_per_minute
    }

    pub fn seconds_per_beat(&self) -> f64 {
        self.seconds_per_beat
    }
}

impl MusicalTransport {
    /// Convert from musical time the corresponding time in samples.
    pub fn musical_to_sample(&self, musical: MusicalTime, sample_rate: u32) -> ClockSamples {
        musical.to_sample_time(self.seconds_per_beat, sample_rate)
    }

    /// Convert from the time in samples to the corresponding musical time.
    pub fn sample_to_musical(
        &self,
        sample_time: ClockSamples,
        sample_rate: u32,
        sample_rate_recip: f64,
    ) -> MusicalTime {
        MusicalTime::from_sample_time(
            sample_time,
            self.beats_per_minute * (1.0 / 60.0),
            sample_rate,
            sample_rate_recip,
        )
    }
}