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
// 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::collections::HashMap;

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use super::audio::Audio;
use super::controller::Controller;
use super::dmx::Dmx;
use super::midi::Midi;
use super::notification::NotificationConfig;
use super::trigger::TriggerConfig;

/// Audio configuration with track mappings.
///
/// Uses `IndexMap` so insertion order is preserved through serialize/deserialize
/// round-trips — important for the web UI config editor.
#[derive(Deserialize, Serialize, Clone)]
pub struct AudioConfig {
    #[serde(flatten)]
    audio: Audio,
    track_mappings: IndexMap<String, Vec<u16>>,
}

impl AudioConfig {
    /// Creates a new AudioConfig.
    pub fn new(audio: Audio, track_mappings: IndexMap<String, Vec<u16>>) -> Self {
        AudioConfig {
            audio,
            track_mappings,
        }
    }

    /// Returns the audio configuration.
    pub fn audio(&self) -> &Audio {
        &self.audio
    }

    /// Returns the track mappings as an IndexMap (preserves insertion order).
    #[cfg(test)]
    pub fn track_mappings(&self) -> &IndexMap<String, Vec<u16>> {
        &self.track_mappings
    }

    /// Validates the audio configuration within a profile.
    pub fn validate(&self, errors: &mut Vec<String>) {
        if let Err(audio_errors) = self.audio.validate() {
            errors.extend(audio_errors);
        }
        for (name, channels) in &self.track_mappings {
            for &ch in channels {
                if ch == 0 {
                    errors.push(format!(
                        "track_mappings '{}': channel 0 is invalid (channels are 1-indexed)",
                        name
                    ));
                }
            }
        }
    }

    /// Returns the track mappings as a HashMap (for runtime use where order doesn't matter).
    pub fn track_mappings_hash(&self) -> HashMap<String, Vec<u16>> {
        self.track_mappings
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect()
    }
}

/// A unified hardware profile representing one complete host configuration.
/// Profiles are tried in list order; the first one whose hostname matches (or has
/// no constraint) is used.
#[derive(Deserialize, Serialize, Clone)]
pub struct Profile {
    /// Identifies this config file as a hardware profile.
    #[serde(default = "default_hardware_profile_kind")]
    kind: super::kind::ConfigKind,

    /// Optional hostname restriction.
    hostname: Option<String>,

    /// Audio configuration (optional if absent from profile).
    audio: Option<AudioConfig>,

    /// MIDI configuration (optional if absent from profile).
    midi: Option<Midi>,

    /// DMX configuration (optional if absent from profile).
    dmx: Option<Dmx>,

    /// Audio trigger configuration (optional).
    trigger: Option<TriggerConfig>,

    /// Controllers associated with this profile.
    #[serde(default)]
    controllers: Vec<Controller>,

    /// Notification audio configuration (global overrides).
    #[serde(default)]
    notifications: Option<NotificationConfig>,

    /// Status events — MIDI events emitted on player state changes.
    #[serde(default)]
    status_events: Option<super::statusevents::StatusEvents>,
}

impl Profile {
    /// Creates a new Profile.
    pub fn new(
        hostname: Option<String>,
        audio: Option<AudioConfig>,
        midi: Option<Midi>,
        dmx: Option<Dmx>,
    ) -> Self {
        Profile {
            kind: super::kind::ConfigKind::HardwareProfile,
            hostname,
            audio,
            midi,
            dmx,
            trigger: None,
            controllers: Vec::new(),
            notifications: None,
            status_events: None,
        }
    }

    /// Returns the optional hostname constraint.
    pub fn hostname(&self) -> Option<&str> {
        self.hostname.as_deref()
    }

    /// Returns the audio configuration, if present.
    pub fn audio_config(&self) -> Option<&AudioConfig> {
        self.audio.as_ref()
    }

    /// Returns the MIDI configuration.
    pub fn midi(&self) -> Option<&Midi> {
        self.midi.as_ref()
    }

    /// Returns the DMX configuration.
    pub fn dmx(&self) -> Option<&Dmx> {
        self.dmx.as_ref()
    }

    /// Returns a mutable reference to the DMX configuration.
    pub fn dmx_mut(&mut self) -> Option<&mut Dmx> {
        self.dmx.as_mut()
    }

    /// Returns the trigger configuration, if present.
    pub fn trigger(&self) -> Option<&TriggerConfig> {
        self.trigger.as_ref()
    }

    /// Sets the trigger configuration (used during legacy config normalization).
    pub(super) fn set_trigger(&mut self, trigger: Option<TriggerConfig>) {
        self.trigger = trigger;
    }

    /// Returns the controllers associated with this profile.
    pub fn controllers(&self) -> &[Controller] {
        &self.controllers
    }

    /// Sets the controllers (used during legacy config normalization).
    pub(super) fn set_controllers(&mut self, controllers: Vec<Controller>) {
        self.controllers = controllers;
    }

    /// Returns the notification audio configuration, if present.
    pub fn notifications(&self) -> Option<&NotificationConfig> {
        self.notifications.as_ref()
    }

    /// Returns the status events configuration, if present.
    pub fn status_events(&self) -> Option<&super::statusevents::StatusEvents> {
        self.status_events.as_ref()
    }

    /// Sets the status events (used during legacy config normalization).
    pub(super) fn set_status_events(
        &mut self,
        status_events: Option<super::statusevents::StatusEvents>,
    ) {
        self.status_events = status_events;
    }

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

        if let Some(ref audio_config) = self.audio {
            audio_config.validate(&mut errors);
        }
        if let Some(ref midi) = self.midi {
            if let Err(midi_errors) = midi.validate() {
                errors.extend(midi_errors);
            }
        }
        if let Some(ref dmx) = self.dmx {
            if let Err(dmx_errors) = dmx.validate() {
                errors.extend(dmx_errors);
            }
        }

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

fn default_hardware_profile_kind() -> super::kind::ConfigKind {
    super::kind::ConfigKind::HardwareProfile
}

/// Filters profiles by hostname. Returns profiles that either have no hostname
/// constraint or whose hostname matches the given value.
#[cfg(test)]
fn filter_by_hostname<'a, P, F>(profiles: &'a [P], hostname: &str, get_hostname: F) -> Vec<&'a P>
where
    F: Fn(&'a P) -> Option<&'a str>,
{
    profiles
        .iter()
        .filter(|p| match get_hostname(p) {
            Some(h) => h == hostname,
            None => true,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use config::{Config, File, FileFormat};

    use super::*;

    #[test]
    fn test_profile_deserialize() {
        let yaml = r#"
            hostname: pi-a
            audio:
              device: mock-device
              sample_rate: 48000
              track_mappings:
                drums:
                  - 1
                synth:
                  - 2
            midi:
              device: mock-midi
            dmx:
              universes:
                - universe: 1
                  name: light-show
            controllers:
              - kind: grpc
                port: 43234
              - kind: osc
        "#;

        let profile: Profile = Config::builder()
            .add_source(File::from_str(yaml, FileFormat::Yaml))
            .build()
            .unwrap()
            .try_deserialize()
            .unwrap();

        assert_eq!(profile.hostname(), Some("pi-a"));
        let audio_config = profile.audio_config().unwrap();
        assert_eq!(audio_config.audio().device(), "mock-device");
        assert_eq!(audio_config.audio().sample_rate(), 48000);
        assert_eq!(
            audio_config.track_mappings().get("drums"),
            Some(&vec![1u16])
        );
        assert_eq!(
            audio_config.track_mappings().get("synth"),
            Some(&vec![2u16])
        );
        assert!(profile.midi().is_some());
        assert_eq!(profile.midi().unwrap().device(), "mock-midi");
        assert!(profile.dmx().is_some());
        assert_eq!(profile.controllers().len(), 2);
    }

    #[test]
    fn test_profile_without_audio() {
        let yaml = r#"
            hostname: lighting-node
            midi:
              device: mock-midi
            dmx:
              universes:
                - universe: 1
                  name: light-show
        "#;

        let profile: Profile = Config::builder()
            .add_source(File::from_str(yaml, FileFormat::Yaml))
            .build()
            .unwrap()
            .try_deserialize()
            .unwrap();

        assert_eq!(profile.hostname(), Some("lighting-node"));
        assert!(profile.audio_config().is_none());
        assert!(profile.midi().is_some());
        assert!(profile.dmx().is_some());
    }

    #[test]
    fn test_profile_with_all_subsystems() {
        let audio = Audio::new("test-device");
        let track_mappings = IndexMap::from([("drums".to_string(), vec![1, 2])]);
        let audio_config = AudioConfig::new(audio, track_mappings);
        let midi = Some(Midi::new("midi-device", None));
        let dmx = Some(Dmx::new(None, None, None, vec![], None));

        let profile = Profile::new(Some("pi-a".to_string()), Some(audio_config), midi, dmx);

        assert_eq!(profile.hostname(), Some("pi-a"));
        assert!(profile.audio_config().is_some());
        assert!(profile.midi().is_some());
        assert!(profile.dmx().is_some());
    }

    #[test]
    fn test_profile_without_midi_dmx() {
        let audio = Audio::new("test-device");
        let track_mappings = IndexMap::from([("drums".to_string(), vec![1])]);
        let audio_config = AudioConfig::new(audio, track_mappings);

        let profile = Profile::new(None, Some(audio_config), None, None);

        assert_eq!(profile.hostname(), None);
        assert!(profile.audio_config().is_some());
        assert!(profile.midi().is_none());
        assert!(profile.dmx().is_none());
    }

    #[test]
    fn test_filter_by_hostname() {
        let profiles = vec![
            Profile::new(
                Some("pi-a".to_string()),
                Some(AudioConfig::new(
                    Audio::new("device-a"),
                    IndexMap::from([("drums".to_string(), vec![1])]),
                )),
                None,
                None,
            ),
            Profile::new(
                Some("pi-b".to_string()),
                Some(AudioConfig::new(
                    Audio::new("device-b"),
                    IndexMap::from([("drums".to_string(), vec![11])]),
                )),
                None,
                None,
            ),
            Profile::new(
                None,
                Some(AudioConfig::new(
                    Audio::new("fallback"),
                    IndexMap::from([("drums".to_string(), vec![1])]),
                )),
                None,
                None,
            ),
        ];

        // pi-a matches hostname-specific + wildcard
        let filtered = filter_by_hostname(&profiles, "pi-a", |p| p.hostname());
        assert_eq!(filtered.len(), 2);
        assert_eq!(
            filtered[0].audio_config().unwrap().audio().device(),
            "device-a"
        );
        assert_eq!(
            filtered[1].audio_config().unwrap().audio().device(),
            "fallback"
        );

        // pi-b matches hostname-specific + wildcard
        let filtered = filter_by_hostname(&profiles, "pi-b", |p| p.hostname());
        assert_eq!(filtered.len(), 2);
        assert_eq!(
            filtered[0].audio_config().unwrap().audio().device(),
            "device-b"
        );
        assert_eq!(
            filtered[1].audio_config().unwrap().audio().device(),
            "fallback"
        );

        // unknown host only matches wildcard
        let filtered = filter_by_hostname(&profiles, "pi-c", |p| p.hostname());
        assert_eq!(filtered.len(), 1);
        assert_eq!(
            filtered[0].audio_config().unwrap().audio().device(),
            "fallback"
        );
    }
}