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
//! Event handling
//!
//! This module defines the `EventHandler` trait and some event types: `RawMidiEvent`,
//! `SysExEvent`, ...
//!
//! Custom events
//! =============
//!
//! Implement `Copy` if possible
//! ----------------------------
//!
//! If possible, implement the `Copy` trait for the event,
//! so that the event can be dispatched to different voices in a polyphonic context.
#[cfg(feature = "backend-combined-midly-0-5")]
use crate::backend::combined::midly::midly_0_5::TrackEventKind;
#[cfg(all(test, feature = "backend-combined-midly-0-5"))]
use crate::backend::combined::midly::midly_0_5::{
    num::{u4, u7},
    MidiMessage,
};
use core::num::NonZeroU64;
use gcd::Gcd;
use std::convert::{AsMut, AsRef, TryFrom};
use std::error::Error;
use std::fmt::{Debug, Display, Formatter, Write};

pub mod event_queue;

/// The trait that plugins should implement in order to handle the given type of events.
///
/// The type parameter `E` corresponds to the type of the event.
pub trait EventHandler<E> {
    fn handle_event(&mut self, event: E);
}

/// An extension trait for [`EventHandler`] providing some convenient combinator functions.
pub trait EventHandlerExt<E> {
    /// Create a new event handler that first applies the given function to the event
    /// and then lets the "self" event handler handle the event.
    ///
    /// # Example
    /// ```
    /// use rsynth::event::EventHandler;
    /// use rsynth::event::EventHandlerExt;
    ///
    /// struct Printer;
    /// impl EventHandler<u32> for Printer {
    ///     fn handle_event(&mut self,event: u32) {
    ///         println!("{}", event)
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let mut printer = Printer;
    ///     printer.handle_event(3); // Prints "3"
    ///     let mut increased_printer = printer.map(|i| i+1_u32);
    ///     increased_printer.handle_event(3); // Prints "4"
    /// }
    /// ```
    fn map<EE, F>(&mut self, function: F) -> Map<Self, F>
    where
        F: FnMut(EE) -> E,
    {
        Map {
            inner: self,
            function,
        }
    }
}

impl<T, E> EventHandlerExt<E> for T where T: EventHandler<E> + ?Sized {}

/// An [`EventHandler`] from the [`EventHandlerExt::map`] method.
pub struct Map<'a, H, F>
where
    H: ?Sized,
{
    inner: &'a mut H,
    function: F,
}

impl<'a, E, EE, F, H> EventHandler<EE> for Map<'a, H, F>
where
    H: EventHandler<E>,
    F: FnMut(EE) -> E,
{
    fn handle_event(&mut self, event: EE) {
        self.inner.handle_event((self.function)(event))
    }
}

/// The trait that plugins should implement in order to handle the given type of events.
///
/// The type parameter `E` corresponds to the type of the event.
/// The type parameter `Context` refers to the context that is passed to the event handler.
pub trait ContextualEventHandler<E, Context> {
    fn handle_event(&mut self, event: E, context: &mut Context);
}

/// A System Exclusive ("SysEx") event.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SysExEvent<'a> {
    data: &'a [u8],
}

impl<'a> Debug for SysExEvent<'a> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "SysExEvent{{data (length: {:?}): &[", self.data.len())?;
        for byte in self.data {
            write!(f, "{:X} ", byte)?;
        }
        write!(f, "]}}")
    }
}

impl<'a> SysExEvent<'a> {
    /// Create a new `SysExEvent` with the given `data`.
    pub fn new(data: &'a [u8]) -> Self {
        Self { data }
    }
    /// Get the data from the `SysExEvent`
    pub fn data(&self) -> &'a [u8] {
        self.data
    }
}

/// A raw midi event.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct RawMidiEvent {
    data: [u8; 3],
    length: usize,
}

impl Debug for RawMidiEvent {
    fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
        match self.length {
            1 => write!(f, "RawMidiEvent({:X})", self.data[0]),
            2 => write!(f, "RawMidiEvent({:X} {:X})", self.data[0], self.data[1]),
            3 => write!(
                f,
                "RawMidiEvent({:X} {:X} {:X})",
                self.data[0], self.data[1], self.data[2]
            ),
            _ => unreachable!("Raw midi event is expected to have length 1, 2 or 3."),
        }
    }
}

impl RawMidiEvent {
    /// Create a new `RawMidiEvent` with the given raw data.
    ///
    /// Panics
    /// ------
    /// Panics when `data` does not have length 1, 2 or 3.
    #[inline]
    pub fn new(bytes: &[u8]) -> Self {
        match Self::try_new(bytes) {
            Some(s) => s,
            None => {
                Self::panic_data_too_long(bytes);
            }
        }
    }

    fn panic_data_too_long(bytes: &[u8]) -> ! {
        let mut event_as_string = String::new();
        write!(event_as_string, "data : &[");
        for (index, byte) in bytes.iter().enumerate() {
            write!(event_as_string, "{:X} ", byte);
            if index > 64 {
                write!(event_as_string, "... ");
                break;
            }
        }
        write!(event_as_string, "]");
        panic!(
            "Raw midi event is expected to have length 1, 2 or 3. Actual length: {}, data: {}",
            bytes.len(),
            event_as_string
        );
    }

    /// Try to create a new `RawMidiEvent` with the given raw data.
    /// Return None when `data` does not have length 1, 2 or 3.
    pub fn try_new(data: &[u8]) -> Option<Self> {
        match data.len() {
            1 => Some(Self {
                data: [data[0], 0, 0],
                length: data.len(),
            }),
            2 => Some(Self {
                data: [data[0], data[1], 0],
                length: data.len(),
            }),
            3 => Some(Self {
                data: [data[0], data[1], data[2]],
                length: data.len(),
            }),
            _ => None,
        }
    }

    /// Get the raw data from a `RawMidiEvent`, including "padding".
    pub fn data(&self) -> &[u8; 3] {
        &self.data
    }

    /// Get the raw data from a `RawMidiEvent`.
    pub fn bytes(&self) -> &[u8] {
        &self.data[0..self.length]
    }
}

#[cfg(feature = "backend-combined-midly-0-5")]
use crate::backend::combined::midly::midly_0_5::io::CursorError;

#[cfg(feature = "backend-combined-midly-0-5")]
#[derive(Debug, Clone)]
/// The error type when converting from `midly`'s `TrackEventKind` to a `RawMidiEvent`.
pub enum MidlyConversionError {
    /// Not a live event.
    NotALiveEvent,
    /// Cursor error (technical error).
    CursorError(CursorError),
}

#[cfg(feature = "backend-combined-midly-0-5")]
impl Display for MidlyConversionError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            MidlyConversionError::NotALiveEvent => write!(f, "Not a live event."),
            MidlyConversionError::CursorError(e) => match e {
                CursorError::InvalidInput(msg) => {
                    write!(f, "Technical error: the input SMF was invalid: {}", msg)
                }
                CursorError::OutOfSpace => {
                    write!(f, "Technical error: the in-memory buffer was too small")
                }
            },
        }
    }
}

#[cfg(feature = "backend-combined-midly-0-5")]
impl Error for MidlyConversionError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[cfg(feature = "backend-combined-midly-0-5")]
impl From<CursorError> for MidlyConversionError {
    fn from(e: CursorError) -> Self {
        MidlyConversionError::CursorError(e)
    }
}

#[cfg(feature = "backend-combined-midly-0-5")]
impl<'a> TryFrom<TrackEventKind<'a>> for RawMidiEvent {
    type Error = MidlyConversionError;

    fn try_from(value: TrackEventKind<'a>) -> Result<Self, Self::Error> {
        let mut raw_data: [u8; 3] = [0, 0, 0];
        let mut slice = &mut raw_data[0..3];
        value
            .as_live_event()
            .ok_or(MidlyConversionError::NotALiveEvent)?
            .write(&mut slice)?;
        // The slice is updated to point to the not-yet-overwritten bytes.
        let number_of_bytes = 3 - slice.len();
        Ok(RawMidiEvent::new(&raw_data[0..number_of_bytes]))
    }
}

#[cfg(feature = "backend-combined-midly-0-5")]
#[test]
fn conversion_from_midly_to_raw_midi_event_works() {
    let channel = 1;
    let program = 2;
    let event_kind = TrackEventKind::Midi {
        channel: u4::from(channel),
        message: MidiMessage::ProgramChange {
            program: u7::from(program),
        },
    };
    let raw_midi_event = RawMidiEvent::try_from(event_kind).unwrap();
    assert_eq!(raw_midi_event.length, 2);
    assert_eq!(
        raw_midi_event.data,
        [
            channel | midi_consts::channel_event::PROGRAM_CHANGE,
            program,
            0
        ]
    );
}

impl AsRef<Self> for RawMidiEvent {
    fn as_ref(&self) -> &RawMidiEvent {
        self
    }
}

impl AsMut<Self> for RawMidiEvent {
    fn as_mut(&mut self) -> &mut RawMidiEvent {
        self
    }
}

/// `Timed<E>` adds timing to an event.
///
/// # Suggestion
/// If you want to handle events in a sample-accurate way, you can use an
/// `EventQueue` to queue them when you receive them, and later use the
/// `split` method on the queue to render the audio.
#[derive(PartialEq, Eq, Debug)]
pub struct Timed<E> {
    /// The offset (in frames) of the event relative to the start of
    /// the audio buffer.
    ///
    /// E.g. when `time_in_frames` is 6, this means that
    /// the event happens on the sixth frame of the buffer in the call to
    /// the [`render_buffer`] method of the `Plugin` trait.
    ///
    /// [`render_buffer`]: ../trait.Plugin.html#tymethod.render_buffer
    pub time_in_frames: u32,
    /// The underlying event.
    pub event: E,
}

impl<E> Timed<E> {
    pub fn new(time_in_frames: u32, event: E) -> Self {
        Self {
            time_in_frames,
            event,
        }
    }
}

impl<E> Clone for Timed<E>
where
    E: Clone,
{
    fn clone(&self) -> Self {
        Timed {
            time_in_frames: self.time_in_frames,
            event: self.event.clone(),
        }
    }
}

impl<E> Copy for Timed<E> where E: Copy {}

impl<E> AsRef<E> for Timed<E> {
    fn as_ref(&self) -> &E {
        &self.event
    }
}

impl<E> AsMut<E> for Timed<E> {
    fn as_mut(&mut self) -> &mut E {
        &mut self.event
    }
}

/// `Indexed<E>` adds an index to an event of type `E`.
/// The index typically corresponds to the index of the channel.
#[derive(PartialEq, Eq, Debug)]
pub struct Indexed<E> {
    /// The index of the event.
    pub index: usize,
    /// The underlying event.
    pub event: E,
}

impl<E> Indexed<E> {
    pub fn new(index: usize, event: E) -> Self {
        Self { index, event }
    }
}

impl<E> Clone for Indexed<E>
where
    E: Clone,
{
    fn clone(&self) -> Self {
        Self {
            index: self.index,
            event: self.event.clone(),
        }
    }
}

impl<E> Copy for Indexed<E> where E: Copy {}

impl<E> AsRef<E> for Indexed<E> {
    fn as_ref(&self) -> &E {
        &self.event
    }
}

impl<E> AsMut<E> for Indexed<E> {
    fn as_mut(&mut self) -> &mut E {
        &mut self.event
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DeltaEvent<E> {
    pub microseconds_since_previous_event: u64,
    pub event: E,
}

/// Stretch integer (`u64`) time stamps by a fractional factor that may change over time.
pub struct TimeStretcher {
    nominator: u64,
    denominator: NonZeroU64,
    input_offset: u64,
    output_offset: u64,
    drifting_correction: f64,
}

impl TimeStretcher {
    /// Create a new `TimeStretcher`.
    pub fn new(nominator: u64, denominator: NonZeroU64) -> Self {
        Self {
            nominator,
            denominator,
            input_offset: 0,
            output_offset: 0,
            drifting_correction: 0.0,
        }
    }

    /// Stretch the input time by the factor `nominator/denominator`.
    ///
    /// # Parameters
    /// `input_time`: the time to be stretched
    /// `new_speed`: if this contains `Some((nominator, denominator))`, future times will
    /// be stretched by the new factor `nominator/denominator`.
    pub fn stretch(
        &mut self,
        absolute_input_time: u64,
        new_speed: Option<(u64, NonZeroU64)>,
    ) -> u64 {
        let self_denominator: u64 = self.denominator.into(); // Avoid some cumbersome type annotations.

        // Adapt offset in order to avoid integer overflow when multiplying.
        let input_offset_delta: u64 = (absolute_input_time - self.input_offset) / self_denominator;
        self.input_offset += input_offset_delta * self_denominator;
        self.output_offset += input_offset_delta * self.nominator;

        let new_time = (absolute_input_time - self.input_offset) * self.nominator
            / self_denominator
            + self.output_offset;

        if let Some((mut new_nominator, mut new_denominator)) = new_speed {
            let gcd = new_nominator.gcd(new_denominator.into());
            new_nominator = new_nominator / gcd;
            // Safety: because new_denominator != 0, gcd != 0.
            // Safety: gcd <= new_denominator, new_denominator / gcd >= 1 > 0.
            new_denominator =
                unsafe { NonZeroU64::new_unchecked(<_ as Into<u64>>::into(new_denominator) / gcd) };
            if new_nominator != self.nominator || new_denominator != self.denominator {
                // Update the drifting correction
                let error = ((absolute_input_time - self.input_offset) * self.nominator) as f64
                    / (self_denominator as f64)
                    - ((new_time - self.output_offset) as f64);
                self.drifting_correction += error;
                let correction = self.drifting_correction as u64;
                self.drifting_correction -= correction as f64;

                // Set the new offsets, taking into account the correction.
                self.input_offset = absolute_input_time;
                self.output_offset = new_time + correction;

                // Set the new nominators and denominators
                self.nominator = new_nominator;
                self.denominator = new_denominator;
            }
        }
        new_time
    }
}

#[test]
pub fn event_time_stretcher_works_when_no_drifting_correction_needed() {
    let mut stretcher = TimeStretcher::new(1, NonZeroU64::new(1).unwrap());
    // Input events and the line below: output events
    // 0 . . 1 . . 2 . . . . 3 . . . . 4
    // 0 . 1 . 2 . . . . . . 3 . . . . . . 4
    let input = vec![
        (0, Some((2, NonZeroU64::new(3).unwrap()))),
        (3, None),
        (6, Some((7, NonZeroU64::new(5).unwrap()))),
        (11, None),
        (16, None),
    ];
    let mut observed_output = Vec::new();
    for input in input.into_iter() {
        observed_output.push(stretcher.stretch(input.0, input.1));
    }
    let expected_output = vec![0, 2, 4, 11, 18];
    assert_eq!(expected_output, observed_output);
}

#[test]
pub fn event_time_stretcher_works_when_drifting_correction_needed() {
    let mut stretcher = TimeStretcher::new(1, NonZeroU64::new(1).unwrap());
    // Underscore: factor 1/2, dash: factor 1/3
    // _______ ----- _______------
    // 0 . 1 2 . . 3 4 . 5 6 . . 7
    // Below: the output. We use two lines since there are sometimes two events at the same time.
    // 0 => 0
    // 1 => 1
    // 2 => 1 + 1/2, after rounding: 1. Here we change the speed, so this error gets accumulated. Error: 1/2
    // 3 => 2 + 1/2, after rounding: 2.
    // 4 => 2 + 1/2 + 1/3, after rounding: 2. Here we change speed, so this error gets accumulated as well. Error: 5/6.
    // 5 => 3 + 1/2 + 1/3, after rounding: 3.
    // 6 => 3 + 1/2 + 1/3 + 1/2. Rounding: floor(floor(floor(1 + 1/2) + 1 + 1/3) + 1 + 1/2) = 3.
    //                           We change speed, so this error gets accumulated. Error: 8/6.
    // 7 => 3 + 1/2 + 1/3 + 1/2 + 1. Here we apply the correction and we get 5.
    let input = vec![
        (0, Some((1, NonZeroU64::new(2).unwrap()))),  // 0
        (2, None),                                    // 1
        (3, Some((1, NonZeroU64::new(3).unwrap()))),  // 2
        (6, None),                                    // 3
        (7, Some((1, NonZeroU64::new(2).unwrap()))),  // 4
        (9, None),                                    // 5
        (10, Some((1, NonZeroU64::new(3).unwrap()))), // 6
        (13, None),                                   // 7
    ];
    let mut observed_output = Vec::new();
    for input in input.into_iter() {
        observed_output.push(stretcher.stretch(input.0, input.1));
    }
    let expected_output = vec![0, 1, 1, 2, 2, 3, 3, 5];
    assert_eq!(expected_output, observed_output);
}