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
// 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 super::super::effects::{
    EffectError, EffectInstance, EffectType, FixtureCapabilities, FixtureInfo, TempoAwareFrequency,
};

/// Validate fixture capabilities based on its type and channels
pub(crate) fn validate_fixture_capabilities(fixture: &FixtureInfo) -> Result<(), EffectError> {
    // Check for common capability mismatches
    if fixture.fixture_type.contains("RGB") && !fixture.channels.contains_key("red") {
        return Err(EffectError::Parameter(format!(
            "RGB fixture '{}' missing red channel",
            fixture.name
        )));
    }

    if fixture.fixture_type.contains("RGB") && !fixture.channels.contains_key("green") {
        return Err(EffectError::Parameter(format!(
            "RGB fixture '{}' missing green channel",
            fixture.name
        )));
    }

    if fixture.fixture_type.contains("RGB") && !fixture.channels.contains_key("blue") {
        return Err(EffectError::Parameter(format!(
            "RGB fixture '{}' missing blue channel",
            fixture.name
        )));
    }

    if fixture.fixture_type.contains("Strobe") && !fixture.channels.contains_key("strobe") {
        return Err(EffectError::Parameter(format!(
            "Strobe fixture '{}' missing strobe channel",
            fixture.name
        )));
    }

    if fixture.fixture_type.contains("MovingHead") && !fixture.channels.contains_key("pan") {
        return Err(EffectError::Parameter(format!(
            "Moving head fixture '{}' missing pan channel",
            fixture.name
        )));
    }

    if fixture.fixture_type.contains("MovingHead") && !fixture.channels.contains_key("tilt") {
        return Err(EffectError::Parameter(format!(
            "Moving head fixture '{}' missing tilt channel",
            fixture.name
        )));
    }

    Ok(())
}

/// Validate an effect before starting it
pub(crate) fn validate_effect(
    fixture_registry: &HashMap<String, FixtureInfo>,
    effect: &EffectInstance,
) -> Result<(), EffectError> {
    // Validate fixtures
    for fixture_name in &effect.target_fixtures {
        if !fixture_registry.contains_key(fixture_name) {
            return Err(EffectError::Fixture(format!(
                "Fixture '{}' not found",
                fixture_name
            )));
        }
    }

    // Validate effect compatibility with fixture special cases
    validate_effect_compatibility(fixture_registry, effect)?;

    // Validate effect parameters
    match &effect.effect_type {
        EffectType::Static { parameters, .. } => {
            for (key, value) in parameters {
                if *value < 0.0 || *value > 1.0 {
                    return Err(EffectError::Parameter(format!(
                        "Parameter '{}' must be between 0.0 and 1.0, got {}",
                        key, value
                    )));
                }
            }
        }
        EffectType::Strobe { frequency, .. } => {
            // For tempo-aware frequencies, we can't validate at parse time
            // They'll be validated when converted to Hz during processing
            // For fixed frequencies, validate now
            match frequency {
                TempoAwareFrequency::Fixed(freq) if *freq < 0.0 => {
                    return Err(EffectError::Parameter(format!(
                        "Strobe frequency must be non-negative, got {}",
                        freq
                    )));
                }
                _ => {}
            }
        }
        EffectType::Pulse { frequency, .. } => {
            // For tempo-aware frequencies, we can't validate at parse time
            // They'll be validated when converted to Hz during processing
            // For fixed frequencies, validate now
            match frequency {
                TempoAwareFrequency::Fixed(freq) if *freq <= 0.0 => {
                    return Err(EffectError::Parameter(format!(
                        "Pulse frequency must be positive, got {}",
                        freq
                    )));
                }
                _ => {}
            }
        }
        _ => {} // Other effect types don't need validation yet
    }

    // Validate timing
    let total_duration = effect.total_duration();
    if total_duration.as_secs_f64() < 0.0 {
        return Err(EffectError::Timing(format!(
            "Effect total duration must be non-negative, got {}s",
            total_duration.as_secs_f64()
        )));
    }

    Ok(())
}

#[cfg(test)]
fn make_fixture(name: &str, fixture_type: &str, channels: Vec<(&str, u16)>) -> FixtureInfo {
    let ch: HashMap<String, u16> = channels.iter().map(|(n, o)| (n.to_string(), *o)).collect();
    FixtureInfo::new(name.to_string(), 1, 1, fixture_type.to_string(), ch, None)
}

/// Validate that the effect is compatible with fixture special cases
pub(crate) fn validate_effect_compatibility(
    fixture_registry: &HashMap<String, FixtureInfo>,
    effect: &EffectInstance,
) -> Result<(), EffectError> {
    for fixture_name in &effect.target_fixtures {
        if let Some(fixture_info) = fixture_registry.get(fixture_name) {
            // Check if the effect type is compatible with the fixture's special cases
            match &effect.effect_type {
                EffectType::ColorCycle { .. } => {
                    if !fixture_info.has_capability(FixtureCapabilities::RGB_COLOR) {
                        return Err(EffectError::Parameter(format!(
                            "Color cycle effect not compatible with fixture '{}' (no RGB capability)",
                            fixture_name
                        )));
                    }
                }
                EffectType::Strobe { .. } => {
                    // Strobe effects work with any fixture that has strobe, dimmer, or RGB capability
                    if !fixture_info.has_capability(FixtureCapabilities::STROBING)
                        && !fixture_info.has_capability(FixtureCapabilities::DIMMING)
                        && !fixture_info.has_capability(FixtureCapabilities::RGB_COLOR)
                    {
                        return Err(EffectError::Parameter(format!(
                            "Strobe effect not compatible with fixture '{}' (no strobe, dimmer, or RGB capability)",
                            fixture_name
                        )));
                    }
                }
                EffectType::Chase { .. } => {
                    // Chase effects work with any fixture that has RGB or dimmer capability
                    if !fixture_info.has_capability(FixtureCapabilities::RGB_COLOR)
                        && !fixture_info.has_capability(FixtureCapabilities::DIMMING)
                    {
                        return Err(EffectError::Parameter(format!(
                            "Chase effect not compatible with fixture '{}' (no RGB or dimmer capability)",
                            fixture_name
                        )));
                    }
                }
                EffectType::Rainbow { .. } => {
                    // Rainbow effects require RGB channels
                    if !fixture_info.has_capability(FixtureCapabilities::RGB_COLOR) {
                        return Err(EffectError::Parameter(format!(
                            "Rainbow effect not compatible with fixture '{}' (no RGB capability)",
                            fixture_name
                        )));
                    }
                }
                _ => {} // Other effects are generally compatible
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use crate::lighting::effects::{
        ChaseDirection, ChasePattern, Color, CycleDirection, CycleTransition, TempoAwareFrequency,
        TempoAwareSpeed,
    };

    fn rgb_fixture(name: &str) -> FixtureInfo {
        make_fixture(name, "RGB Par", vec![("red", 1), ("green", 2), ("blue", 3)])
    }

    fn dimmer_fixture(name: &str) -> FixtureInfo {
        make_fixture(name, "Dimmer", vec![("dimmer", 1)])
    }

    fn strobe_fixture(name: &str) -> FixtureInfo {
        make_fixture(name, "Strobe Unit", vec![("strobe", 1)])
    }

    fn make_effect_instance(effect_type: EffectType, fixtures: Vec<&str>) -> EffectInstance {
        EffectInstance::new(
            "test".to_string(),
            effect_type,
            fixtures.into_iter().map(|s| s.to_string()).collect(),
            None,
            None,
            None,
        )
    }

    fn registry_with(fixtures: Vec<FixtureInfo>) -> HashMap<String, FixtureInfo> {
        fixtures.into_iter().map(|f| (f.name.clone(), f)).collect()
    }

    // ── validate_fixture_capabilities ──────────────────────────────

    #[test]
    fn valid_rgb_fixture() {
        let f = rgb_fixture("par1");
        assert!(validate_fixture_capabilities(&f).is_ok());
    }

    #[test]
    fn rgb_fixture_missing_red() {
        let f = make_fixture("par1", "RGB Par", vec![("green", 2), ("blue", 3)]);
        assert!(validate_fixture_capabilities(&f).is_err());
    }

    #[test]
    fn rgb_fixture_missing_green() {
        let f = make_fixture("par1", "RGB Par", vec![("red", 1), ("blue", 3)]);
        assert!(validate_fixture_capabilities(&f).is_err());
    }

    #[test]
    fn rgb_fixture_missing_blue() {
        let f = make_fixture("par1", "RGB Par", vec![("red", 1), ("green", 2)]);
        assert!(validate_fixture_capabilities(&f).is_err());
    }

    #[test]
    fn strobe_fixture_missing_strobe_channel() {
        let f = make_fixture("s1", "Strobe Unit", vec![("dimmer", 1)]);
        assert!(validate_fixture_capabilities(&f).is_err());
    }

    #[test]
    fn moving_head_missing_pan() {
        let f = make_fixture("mh1", "MovingHead", vec![("tilt", 2)]);
        assert!(validate_fixture_capabilities(&f).is_err());
    }

    #[test]
    fn moving_head_missing_tilt() {
        let f = make_fixture("mh1", "MovingHead", vec![("pan", 1)]);
        assert!(validate_fixture_capabilities(&f).is_err());
    }

    #[test]
    fn non_special_type_always_valid() {
        let f = make_fixture("generic", "Generic", vec![("intensity", 1)]);
        assert!(validate_fixture_capabilities(&f).is_ok());
    }

    // ── validate_effect — fixture existence ────────────────────────

    #[test]
    fn validate_effect_unknown_fixture() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Static {
                parameters: HashMap::new(),
                duration: Duration::from_secs(5),
            },
            vec!["nonexistent"],
        );
        assert!(validate_effect(&registry, &effect).is_err());
    }

    #[test]
    fn validate_effect_known_fixture() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Static {
                parameters: HashMap::new(),
                duration: Duration::from_secs(5),
            },
            vec!["par1"],
        );
        assert!(validate_effect(&registry, &effect).is_ok());
    }

    // ── validate_effect — parameter ranges ─────────────────────────

    #[test]
    fn validate_static_param_out_of_range() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let mut params = HashMap::new();
        params.insert("red".to_string(), 1.5); // > 1.0
        let effect = make_effect_instance(
            EffectType::Static {
                parameters: params,
                duration: Duration::from_secs(5),
            },
            vec!["par1"],
        );
        assert!(validate_effect(&registry, &effect).is_err());
    }

    #[test]
    fn validate_static_param_negative() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let mut params = HashMap::new();
        params.insert("red".to_string(), -0.1);
        let effect = make_effect_instance(
            EffectType::Static {
                parameters: params,
                duration: Duration::from_secs(5),
            },
            vec!["par1"],
        );
        assert!(validate_effect(&registry, &effect).is_err());
    }

    #[test]
    fn validate_strobe_negative_frequency() {
        let registry = registry_with(vec![strobe_fixture("s1")]);
        let effect = make_effect_instance(
            EffectType::Strobe {
                frequency: TempoAwareFrequency::Fixed(-1.0),
                duration: Duration::from_secs(5),
            },
            vec!["s1"],
        );
        assert!(validate_effect(&registry, &effect).is_err());
    }

    #[test]
    fn validate_pulse_zero_frequency() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Pulse {
                base_level: 0.0,
                pulse_amplitude: 1.0,
                frequency: TempoAwareFrequency::Fixed(0.0),
                duration: Duration::from_secs(5),
            },
            vec!["par1"],
        );
        assert!(validate_effect(&registry, &effect).is_err());
    }

    // ── validate_effect_compatibility ──────────────────────────────

    #[test]
    fn color_cycle_requires_rgb() {
        let registry = registry_with(vec![dimmer_fixture("d1")]);
        let effect = make_effect_instance(
            EffectType::ColorCycle {
                colors: vec![Color::new(255, 0, 0)],
                speed: TempoAwareSpeed::Fixed(1.0),
                direction: CycleDirection::Forward,
                transition: CycleTransition::Fade,
                duration: Duration::from_secs(10),
            },
            vec!["d1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_err());
    }

    #[test]
    fn color_cycle_ok_with_rgb() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::ColorCycle {
                colors: vec![Color::new(255, 0, 0)],
                speed: TempoAwareSpeed::Fixed(1.0),
                direction: CycleDirection::Forward,
                transition: CycleTransition::Fade,
                duration: Duration::from_secs(10),
            },
            vec!["par1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    #[test]
    fn rainbow_requires_rgb() {
        let registry = registry_with(vec![dimmer_fixture("d1")]);
        let effect = make_effect_instance(
            EffectType::Rainbow {
                speed: TempoAwareSpeed::Fixed(1.0),
                saturation: 1.0,
                brightness: 1.0,
                duration: Duration::from_secs(10),
            },
            vec!["d1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_err());
    }

    #[test]
    fn chase_ok_with_rgb() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Chase {
                pattern: ChasePattern::Linear,
                speed: TempoAwareSpeed::Fixed(1.0),
                direction: ChaseDirection::LeftToRight,
                transition: CycleTransition::Snap,
                duration: Duration::from_secs(10),
            },
            vec!["par1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    #[test]
    fn chase_ok_with_dimmer() {
        let registry = registry_with(vec![dimmer_fixture("d1")]);
        let effect = make_effect_instance(
            EffectType::Chase {
                pattern: ChasePattern::Linear,
                speed: TempoAwareSpeed::Fixed(1.0),
                direction: ChaseDirection::LeftToRight,
                transition: CycleTransition::Snap,
                duration: Duration::from_secs(10),
            },
            vec!["d1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    #[test]
    fn strobe_ok_with_dimmer() {
        let registry = registry_with(vec![dimmer_fixture("d1")]);
        let effect = make_effect_instance(
            EffectType::Strobe {
                frequency: TempoAwareFrequency::Fixed(10.0),
                duration: Duration::from_secs(1),
            },
            vec!["d1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    #[test]
    fn static_effect_ok_with_anything() {
        let registry = registry_with(vec![dimmer_fixture("d1")]);
        let effect = make_effect_instance(
            EffectType::Static {
                parameters: HashMap::new(),
                duration: Duration::from_secs(5),
            },
            vec!["d1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    // ── Strobe with no strobe/dimmer/RGB capability ─────────────────

    #[test]
    fn strobe_incompatible_with_no_capability() {
        // A fixture with no strobe, dimmer, or RGB capability should fail for strobe effects
        let f = make_fixture("generic", "Generic", vec![("pan", 1), ("tilt", 2)]);
        let registry = registry_with(vec![f]);
        let effect = make_effect_instance(
            EffectType::Strobe {
                frequency: TempoAwareFrequency::Fixed(10.0),
                duration: Duration::from_secs(5),
            },
            vec!["generic"],
        );
        let result = validate_effect_compatibility(&registry, &effect);
        assert!(
            result.is_err(),
            "Strobe should be incompatible with fixture lacking strobe/dimmer/RGB"
        );
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Strobe effect not compatible"),
            "Error should mention strobe incompatibility: {}",
            err
        );
    }

    #[test]
    fn strobe_ok_with_rgb() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Strobe {
                frequency: TempoAwareFrequency::Fixed(10.0),
                duration: Duration::from_secs(5),
            },
            vec!["par1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    #[test]
    fn strobe_ok_with_strobe_fixture() {
        let registry = registry_with(vec![strobe_fixture("s1")]);
        let effect = make_effect_instance(
            EffectType::Strobe {
                frequency: TempoAwareFrequency::Fixed(10.0),
                duration: Duration::from_secs(5),
            },
            vec!["s1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    // ── Chase with no RGB/dimmer capability ──────────────────────────

    #[test]
    fn chase_incompatible_with_no_rgb_or_dimmer() {
        // A fixture with no RGB or dimmer capability should fail for chase effects
        let f = make_fixture("generic", "Generic", vec![("pan", 1), ("tilt", 2)]);
        let registry = registry_with(vec![f]);
        let effect = make_effect_instance(
            EffectType::Chase {
                pattern: ChasePattern::Linear,
                speed: TempoAwareSpeed::Fixed(1.0),
                direction: ChaseDirection::LeftToRight,
                transition: CycleTransition::Snap,
                duration: Duration::from_secs(10),
            },
            vec!["generic"],
        );
        let result = validate_effect_compatibility(&registry, &effect);
        assert!(
            result.is_err(),
            "Chase should be incompatible with fixture lacking RGB/dimmer"
        );
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Chase effect not compatible"),
            "Error should mention chase incompatibility: {}",
            err
        );
    }

    // ── Rainbow with non-RGB fixture ─────────────────────────────────

    #[test]
    fn rainbow_ok_with_rgb() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Rainbow {
                speed: TempoAwareSpeed::Fixed(1.0),
                saturation: 1.0,
                brightness: 1.0,
                duration: Duration::from_secs(10),
            },
            vec!["par1"],
        );
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }

    // ── Validate effect with valid strobe frequency ──────────────────

    #[test]
    fn validate_strobe_zero_frequency_ok() {
        let registry = registry_with(vec![strobe_fixture("s1")]);
        let effect = make_effect_instance(
            EffectType::Strobe {
                frequency: TempoAwareFrequency::Fixed(0.0),
                duration: Duration::from_secs(5),
            },
            vec!["s1"],
        );
        // Zero frequency is valid (it disables strobing)
        assert!(validate_effect(&registry, &effect).is_ok());
    }

    // ── Validate effect with tempo-aware frequency ───────────────────

    #[test]
    fn validate_strobe_tempo_aware_frequency() {
        let registry = registry_with(vec![strobe_fixture("s1")]);
        let effect = make_effect_instance(
            EffectType::Strobe {
                frequency: TempoAwareFrequency::Beats(2.0),
                duration: Duration::from_secs(5),
            },
            vec!["s1"],
        );
        // Tempo-aware frequencies can't be validated at parse time
        assert!(validate_effect(&registry, &effect).is_ok());
    }

    // ── Validate pulse with tempo-aware frequency ────────────────────

    #[test]
    fn validate_pulse_tempo_aware_frequency() {
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Pulse {
                base_level: 0.5,
                pulse_amplitude: 0.5,
                frequency: TempoAwareFrequency::Beats(1.0),
                duration: Duration::from_secs(5),
            },
            vec!["par1"],
        );
        // Tempo-aware frequencies can't be validated at parse time
        assert!(validate_effect(&registry, &effect).is_ok());
    }

    // ── Validate effect with fixture not in registry ─────────────────

    #[test]
    fn validate_effect_compatibility_unknown_fixture_skipped() {
        // If a fixture isn't in the registry, validate_effect_compatibility
        // should still succeed (the fixture check is done in validate_effect separately)
        let registry = registry_with(vec![rgb_fixture("par1")]);
        let effect = make_effect_instance(
            EffectType::Static {
                parameters: HashMap::new(),
                duration: Duration::from_secs(5),
            },
            vec!["not_in_registry"],
        );
        // validate_effect_compatibility doesn't check fixture existence
        assert!(validate_effect_compatibility(&registry, &effect).is_ok());
    }
}