mtrack 0.12.0

A multitrack audio and MIDI player for live performances.
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
// Copyright (C) 2026 Michael Wilson <mike@mdwn.dev>
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
//
use std::{error::Error, time::Duration};

use duration_string::DurationString;
use midly::{
    live::LiveEvent,
    num::{u14, u4, u7},
};
use serde::{Deserialize, Serialize};

const DEFAULT_MIDI_PLAYBACK_DELAY: Duration = Duration::ZERO;

/// A YAML representation of the MIDI configuration.
#[derive(Deserialize, Serialize, Clone)]
pub struct Midi {
    /// The MIDI device.
    device: String,

    /// Controls how long to wait before playback of a MIDI file starts.
    playback_delay: Option<String>,

    /// Enable MIDI beat clock output (24 ppqn timing clock).
    beat_clock: Option<bool>,

    /// MIDI to DMX passthrough configurations.
    midi_to_dmx: Option<Vec<MidiToDmx>>,
}

impl Midi {
    /// New will create a new MIDI configuration.
    pub fn new(device: &str, playback_delay: Option<String>) -> Midi {
        Midi {
            device: device.to_string(),
            playback_delay,
            beat_clock: None,
            midi_to_dmx: None,
        }
    }

    /// Returns the device from the configuration.
    pub fn device(&self) -> &str {
        &self.device
    }

    /// Returns the playback delay from the configuration.
    pub fn playback_delay(&self) -> Result<Duration, Box<dyn Error>> {
        super::parse_playback_delay(&self.playback_delay, DEFAULT_MIDI_PLAYBACK_DELAY)
    }

    /// Returns whether beat clock output is enabled.
    pub fn beat_clock(&self) -> bool {
        self.beat_clock.unwrap_or(false)
    }

    /// Returns the MIDI to DMX configuration.
    pub fn midi_to_dmx(&self) -> &[MidiToDmx] {
        self.midi_to_dmx.as_deref().unwrap_or_default()
    }

    /// Validates the MIDI configuration for semantic issues.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.device.trim().is_empty() {
            errors.push("midi device must not be empty".to_string());
        }
        if let Some(ref delay) = self.playback_delay {
            if DurationString::from_string(delay.clone()).is_err() {
                errors.push(format!(
                    "midi playback_delay '{}' is not a valid duration",
                    delay
                ));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

/// A YAML representation of the MIDI configuration.
#[derive(Deserialize, Serialize, Clone)]
pub struct MidiToDmx {
    /// The MIDI channel to pass through to DMX.
    midi_channel: u8,

    /// The DMX universe to target.
    universe: String,

    /// Transformations to apply to the input to this mapping.
    transformers: Option<Vec<MidiTransformer>>,
}

impl MidiToDmx {
    /// The MIDI channel associated with this mapping.
    pub fn midi_channel(&self) -> Result<u7, Box<dyn Error>> {
        u7::try_from(self.midi_channel - 1).ok_or("error parsing MIDI channel".into())
    }

    /// The DMX universe to map the MIDI channel to.
    pub fn universe(&self) -> &str {
        &self.universe
    }

    /// The transformers to apply to the input MIDI.
    pub fn transformers(&self) -> &[MidiTransformer] {
        self.transformers.as_deref().unwrap_or_default()
    }
}

/// Implementers must convert to a MIDI live event.
pub trait ToMidiEvent {
    /// Converts the implementer to a MIDI live event.
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>>;
}

#[derive(Deserialize, Serialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MidiTransformer {
    NoteMapper(NoteMapper),
    ControlChangeMapper(ControlChangeMapper),
}

/// A YAML representation of the note mapper MIDI transformation.
#[derive(Deserialize, Serialize, Clone)]
pub struct NoteMapper {
    input_note: u8,
    convert_to_notes: Vec<u8>,
}

impl NoteMapper {
    /// Gets the input note.
    pub fn input_note(&self) -> Result<u7, Box<dyn Error>> {
        u7::try_from(self.input_note).ok_or("input note cannot be converted to a u7".into())
    }

    /// Gets the notes to convert the input to.
    pub fn convert_to_notes(&self) -> Result<Vec<u7>, Box<dyn Error>> {
        self.convert_to_notes
            .iter()
            .map(|note| u7::try_from(*note).ok_or("unable to convert note to u7".into()))
            .collect()
    }
}

/// A YAML representation of the control change mapper MIDI transformation.
#[derive(Deserialize, Serialize, Clone)]
pub struct ControlChangeMapper {
    input_controller: u8,
    convert_to_controllers: Vec<u8>,
}

impl ControlChangeMapper {
    /// Gets the input controller.
    pub fn input_controller(&self) -> Result<u7, Box<dyn Error>> {
        u7::try_from(self.input_controller)
            .ok_or("input controller cannot be converted to a u7".into())
    }

    /// Gets the controllers to convert the input to.
    pub fn convert_to_notes(&self) -> Result<Vec<u7>, Box<dyn Error>> {
        self.convert_to_controllers
            .iter()
            .map(|controller| {
                u7::try_from(*controller).ok_or("unable to convert controller to u7".into())
            })
            .collect()
    }
}

/// MIDI events that can be parsed from YAML.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
    NoteOff(NoteOff),
    NoteOn(NoteOn),
    Aftertouch(Aftertouch),
    ControlChange(ControlChange),
    ProgramChange(ProgramChange),
    ChannelAftertouch(ChannelAftertouch),
    PitchBend(PitchBend),
}

/// Creates a note on MIDI event.
#[cfg(test)]
pub fn note_on(channel: u8, key: u8, velocity: u8) -> Event {
    Event::NoteOn(NoteOn {
        channel,
        key,
        velocity,
    })
}

impl ToMidiEvent for Event {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        match self {
            Event::NoteOff(e) => e.to_midi_event(),
            Event::NoteOn(e) => e.to_midi_event(),
            Event::Aftertouch(e) => e.to_midi_event(),
            Event::ControlChange(e) => e.to_midi_event(),
            Event::ProgramChange(e) => e.to_midi_event(),
            Event::ChannelAftertouch(e) => e.to_midi_event(),
            Event::PitchBend(e) => e.to_midi_event(),
        }
    }
}

/// A NoteOff event.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
pub struct NoteOff {
    /// The channel the MIDI event belongs to.
    channel: u8,
    /// The key for the note off event.
    key: u8,
    /// The velocity of the note off event.
    /// Optional for trigger matching; defaults to 0.
    #[serde(default)]
    velocity: u8,
}

impl ToMidiEvent for NoteOff {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        Ok(LiveEvent::Midi {
            channel: parse_channel(self.channel)?,
            message: midly::MidiMessage::NoteOff {
                key: parse_u7(self.key)?,
                vel: parse_u7(self.velocity)?,
            },
        })
    }
}

/// A NoteOn event.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
pub struct NoteOn {
    /// The channel the MIDI event belongs to.
    channel: u8,
    /// The key of the note on event.
    key: u8,
    /// The velocity of the note on event.
    /// Optional for trigger matching; defaults to 0.
    #[serde(default)]
    velocity: u8,
}

impl ToMidiEvent for NoteOn {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        Ok(LiveEvent::Midi {
            channel: parse_channel(self.channel)?,
            message: midly::MidiMessage::NoteOn {
                key: parse_u7(self.key)?,
                vel: parse_u7(self.velocity)?,
            },
        })
    }
}

/// An Aftertouch event.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
pub struct Aftertouch {
    /// The channel the MIDI event belongs to.
    channel: u8,
    /// The key value of the aftertouch event.
    key: u8,
    /// The velocity value of the aftertouch event.
    velocity: u8,
}

impl ToMidiEvent for Aftertouch {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        Ok(LiveEvent::Midi {
            channel: parse_channel(self.channel)?,
            message: midly::MidiMessage::Aftertouch {
                key: parse_u7(self.key)?,
                vel: parse_u7(self.velocity)?,
            },
        })
    }
}

/// A ControlChange event.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
pub struct ControlChange {
    /// The channel the MIDI event belongs to.
    channel: u8,
    /// Controller is the controller for a control_change event.
    controller: u8,
    /// Value is the control_change value.
    value: u8,
}

impl ToMidiEvent for ControlChange {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        Ok(LiveEvent::Midi {
            channel: parse_channel(self.channel)?,
            message: midly::MidiMessage::Controller {
                controller: parse_u7(self.controller)?,
                value: parse_u7(self.value)?,
            },
        })
    }
}

/// A ProgramChange event.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
pub struct ProgramChange {
    /// The channel the MIDI event belongs to.
    channel: u8,
    /// Program is the program value for program_change events.
    program: u8,
}

impl ToMidiEvent for ProgramChange {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        Ok(LiveEvent::Midi {
            channel: parse_channel(self.channel)?,
            message: midly::MidiMessage::ProgramChange {
                program: parse_u7(self.program)?,
            },
        })
    }
}

/// A ChannelAftertouch event.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
pub struct ChannelAftertouch {
    /// The channel the MIDI event belongs to.
    channel: u8,
    /// The velocity of the channel aftertouch event.
    velocity: u8,
}

impl ToMidiEvent for ChannelAftertouch {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        Ok(LiveEvent::Midi {
            channel: parse_channel(self.channel)?,
            message: midly::MidiMessage::ChannelAftertouch {
                vel: parse_u7(self.velocity)?,
            },
        })
    }
}

/// A PitchBend event.
#[derive(Deserialize, Clone, Serialize, Debug, PartialEq, Eq)]
pub struct PitchBend {
    /// The channel the MIDI event belongs to.
    channel: u8,
    /// The pitchbend event.
    bend: u16,
}

impl ToMidiEvent for PitchBend {
    fn to_midi_event(&self) -> Result<LiveEvent<'static>, Box<dyn Error>> {
        Ok(LiveEvent::Midi {
            channel: parse_channel(self.channel)?,
            message: midly::MidiMessage::PitchBend {
                bend: midly::PitchBend(parse_u14(self.bend)?),
            },
        })
    }
}

/// Parses a channel from the config. Input is expected to be [1, 16].
fn parse_channel(channel: u8) -> Result<u4, Box<dyn Error>> {
    match u4::try_from(channel - 1) {
        Some(val) => Ok(val),
        None => Err(format!("error parsing channel: {} is invalid", channel).into()),
    }
}

/// Parses a raw u7 value.
fn parse_u7(raw: u8) -> Result<u7, Box<dyn Error>> {
    match u7::try_from(raw) {
        Some(val) => Ok(val),
        None => Err(format!("error parsing u7 value: {} is invalid", raw).into()),
    }
}

// Parses a raw u14 value.
fn parse_u14(raw: u16) -> Result<u14, Box<dyn Error>> {
    match u14::try_from(raw) {
        Some(val) => Ok(val),
        None => Err(format!("error parsing u14 value: {} is invalid", raw).into()),
    }
}

#[cfg(test)]
mod test {
    use std::error::Error;

    use config::{Config, File, FileFormat};
    use midly::{
        live::LiveEvent,
        num::{u14, u4, u7},
    };

    use crate::config::midi::ToMidiEvent;

    #[test]
    fn note_off() -> Result<(), Box<dyn Error>> {
        assert_yaml_matches_midi(
            r#"
            type: note_off
            channel: 7
            key: 5
            velocity: 28
        "#
            .into(),
            LiveEvent::Midi {
                channel: u4::from(6),
                message: midly::MidiMessage::NoteOff {
                    key: u7::from(5),
                    vel: u7::from(28),
                },
            },
        )
    }

    #[test]
    fn note_on() -> Result<(), Box<dyn Error>> {
        assert_yaml_matches_midi(
            r#"
            type: note_on
            channel: 7
            key: 5
            velocity: 28
        "#
            .into(),
            LiveEvent::Midi {
                channel: u4::from(6),
                message: midly::MidiMessage::NoteOn {
                    key: u7::from(5),
                    vel: u7::from(28),
                },
            },
        )
    }

    #[test]
    fn aftertouch() -> Result<(), Box<dyn Error>> {
        assert_yaml_matches_midi(
            r#"
            type: aftertouch
            channel: 7
            key: 5
            velocity: 28
        "#
            .into(),
            LiveEvent::Midi {
                channel: u4::from(6),
                message: midly::MidiMessage::Aftertouch {
                    key: u7::from(5),
                    vel: u7::from(28),
                },
            },
        )
    }

    #[test]
    fn control_change() -> Result<(), Box<dyn Error>> {
        assert_yaml_matches_midi(
            r#"
            type: control_change
            channel: 7
            controller: 5
            value: 28
        "#
            .into(),
            LiveEvent::Midi {
                channel: u4::from(6),
                message: midly::MidiMessage::Controller {
                    controller: u7::from(5),
                    value: u7::from(28),
                },
            },
        )
    }

    #[test]
    fn program_change() -> Result<(), Box<dyn Error>> {
        assert_yaml_matches_midi(
            r#"
            type: program_change
            channel: 7
            program: 5
        "#
            .into(),
            LiveEvent::Midi {
                channel: u4::from(6),
                message: midly::MidiMessage::ProgramChange {
                    program: u7::from(5),
                },
            },
        )
    }

    #[test]
    fn channel_aftertouch() -> Result<(), Box<dyn Error>> {
        assert_yaml_matches_midi(
            r#"
            type: channel_aftertouch
            channel: 7
            velocity: 5
        "#
            .into(),
            LiveEvent::Midi {
                channel: u4::from(6),
                message: midly::MidiMessage::ChannelAftertouch { vel: u7::from(5) },
            },
        )
    }

    #[test]
    fn pitch_bend() -> Result<(), Box<dyn Error>> {
        assert_yaml_matches_midi(
            r#"
            type: pitch_bend
            channel: 7
            bend: 200
        "#
            .into(),
            LiveEvent::Midi {
                channel: u4::from(6),
                message: midly::MidiMessage::PitchBend {
                    bend: midly::PitchBend(u14::from(200)),
                },
            },
        )
    }

    #[test]
    fn midi_device_and_delay() {
        let midi = super::Midi::new("my-device", Some("500ms".to_string()));
        assert_eq!(midi.device(), "my-device");
        assert_eq!(
            midi.playback_delay().unwrap(),
            std::time::Duration::from_millis(500)
        );
    }

    #[test]
    fn midi_playback_delay_default() {
        let midi = super::Midi::new("dev", None);
        assert_eq!(midi.playback_delay().unwrap(), std::time::Duration::ZERO);
    }

    #[test]
    fn midi_to_dmx_empty_default() {
        let midi = super::Midi::new("dev", None);
        assert!(midi.midi_to_dmx().is_empty());
    }

    #[test]
    fn beat_clock_default_is_false() {
        let midi = super::Midi::new("dev", None);
        assert!(!midi.beat_clock());
    }

    #[test]
    fn beat_clock_deserialization() -> Result<(), Box<dyn Error>> {
        let yaml = r#"
            device: test
            beat_clock: true
        "#;
        let midi: super::Midi = Config::builder()
            .add_source(File::from_str(yaml, FileFormat::Yaml))
            .build()?
            .try_deserialize()?;
        assert!(midi.beat_clock());
        Ok(())
    }

    #[test]
    fn midi_to_dmx_deserialization() -> Result<(), Box<dyn Error>> {
        let yaml = r#"
            device: test
            midi_to_dmx:
              - midi_channel: 10
                universe: "main"
                transformers:
                  - type: note_mapper
                    input_note: 60
                    convert_to_notes: [61, 62]
        "#;
        let midi: super::Midi = Config::builder()
            .add_source(File::from_str(yaml, FileFormat::Yaml))
            .build()?
            .try_deserialize()?;
        let mappings = midi.midi_to_dmx();
        assert_eq!(mappings.len(), 1);
        assert_eq!(mappings[0].universe(), "main");
        assert_eq!(u8::from(mappings[0].midi_channel()?), 9); // 10 - 1
        assert_eq!(mappings[0].transformers().len(), 1);
        Ok(())
    }

    #[test]
    fn parse_channel_boundary_values() -> Result<(), Box<dyn Error>> {
        // Channel 1 (min valid) -> u4(0)
        let ch = super::parse_channel(1)?;
        assert_eq!(u8::from(ch), 0);

        // Channel 16 (max valid) -> u4(15)
        let ch = super::parse_channel(16)?;
        assert_eq!(u8::from(ch), 15);

        // Channel 17 (out of range) -> error
        assert!(super::parse_channel(17).is_err());
        Ok(())
    }

    #[test]
    fn parse_u7_boundary_values() -> Result<(), Box<dyn Error>> {
        assert_eq!(u8::from(super::parse_u7(0)?), 0);
        assert_eq!(u8::from(super::parse_u7(127)?), 127);
        assert!(super::parse_u7(128).is_err());
        Ok(())
    }

    #[test]
    fn parse_u14_boundary_values() -> Result<(), Box<dyn Error>> {
        assert_eq!(u16::from(super::parse_u14(0)?), 0);
        assert_eq!(u16::from(super::parse_u14(16383)?), 16383);
        assert!(super::parse_u14(16384).is_err());
        Ok(())
    }

    fn assert_yaml_matches_midi(
        yaml: String,
        expected_event: midly::live::LiveEvent,
    ) -> Result<(), Box<dyn Error>> {
        let event = Config::builder()
            .add_source(File::from_str(&yaml, FileFormat::Yaml))
            .build()?
            .try_deserialize::<super::Event>()?
            .to_midi_event()?;

        if expected_event == event {
            Ok(())
        } else {
            Err("expected event did not match".into())
        }
    }
}