maolan 0.2.0

Rust DAW application for recording, editing, routing, automation, export, and plugin hosting
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
use super::{AudioClip, MIDIClip};
use crate::message::{MidiEditorViewMode, TrackAutomationMode, TrackAutomationTarget};
use iced::{Color, Point};
use serde::{Deserialize, Deserializer, Serialize};

pub use crate::consts::state_track::{
    TRACK_FOLDER_HEADER_HEIGHT, TRACK_MIN_HEIGHT, TRACK_SUBTRACK_GAP, TRACK_SUBTRACK_MIN_HEIGHT,
};

#[derive(Debug, Clone, Copy)]
pub struct TrackLaneLayout {
    pub header_height: f32,
    pub lane_height: f32,
    pub audio_lanes: usize,
    pub midi_lanes: usize,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AudioData {
    pub clips: Vec<AudioClip>,
    pub ins: usize,
    pub outs: usize,
}

impl AudioData {
    pub fn new(ins: usize, outs: usize) -> Self {
        Self {
            clips: vec![],
            ins,
            outs,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MIDIData {
    pub clips: Vec<MIDIClip>,
    pub ins: usize,
    pub outs: usize,
    #[serde(default)]
    pub editor_view_mode: MidiEditorViewMode,
}

impl MIDIData {
    pub fn new(ins: usize, outs: usize) -> Self {
        Self {
            clips: vec![],
            ins,
            outs,
            editor_view_mode: MidiEditorViewMode::PianoRoll,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackAutomationPoint {
    pub sample: usize,
    pub value: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackAutomationLane {
    pub target: TrackAutomationTarget,
    pub visible: bool,
    pub points: Vec<TrackAutomationPoint>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub struct EditorMarker {
    pub sample: usize,
    #[serde(default)]
    pub name: String,
}

impl<'de> Deserialize<'de> for EditorMarker {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum LegacyOrCurrent {
            Legacy(usize),
            Current {
                sample: usize,
                #[serde(default)]
                name: String,
            },
        }

        match LegacyOrCurrent::deserialize(deserializer)? {
            LegacyOrCurrent::Legacy(sample) => Ok(Self {
                sample,
                name: String::new(),
            }),
            LegacyOrCurrent::Current { sample, name } => Ok(Self { sample, name }),
        }
    }
}

#[derive(Serialize, Deserialize)]
#[serde(remote = "Point")]
struct PointDef {
    x: f32,
    y: f32,
}

mod color_option_def {
    use iced::Color;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S>(value: &Option<Color>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        #[derive(Serialize)]
        struct ColorProxy {
            r: f32,
            g: f32,
            b: f32,
            a: f32,
        }
        match value {
            Some(c) => ColorProxy {
                r: c.r,
                g: c.g,
                b: c.b,
                a: c.a,
            }
            .serialize(serializer),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Color>, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct ColorProxy {
            r: f32,
            g: f32,
            b: f32,
            a: f32,
        }
        let proxy = Option::<ColorProxy>::deserialize(deserializer)?;
        Ok(proxy.map(|p| Color::from_rgba(p.r, p.g, p.b, p.a)))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Track {
    id: usize,
    pub name: String,
    pub level: f32,
    pub balance: f32,
    #[serde(skip, default)]
    pub meter_out_db: Vec<f32>,
    pub armed: bool,
    pub muted: bool,
    pub phase_inverted: bool,
    pub soloed: bool,
    pub is_master: bool,
    pub input_monitor: bool,
    pub disk_monitor: bool,
    #[serde(default)]
    pub midi_learn_volume: Option<maolan_engine::message::MidiLearnBinding>,
    #[serde(default)]
    pub midi_learn_balance: Option<maolan_engine::message::MidiLearnBinding>,
    #[serde(default)]
    pub midi_learn_mute: Option<maolan_engine::message::MidiLearnBinding>,
    #[serde(default)]
    pub midi_learn_solo: Option<maolan_engine::message::MidiLearnBinding>,
    #[serde(default)]
    pub midi_learn_arm: Option<maolan_engine::message::MidiLearnBinding>,
    #[serde(default)]
    pub midi_learn_input_monitor: Option<maolan_engine::message::MidiLearnBinding>,
    #[serde(default)]
    pub midi_learn_disk_monitor: Option<maolan_engine::message::MidiLearnBinding>,
    #[serde(default)]
    pub vca_master: Option<String>,
    #[serde(default)]
    pub frozen: bool,
    #[serde(default)]
    pub is_folder: bool,
    #[serde(default)]
    pub folder_open: bool,
    #[serde(default)]
    pub parent_track: Option<String>,
    pub height: f32,
    #[serde(default)]
    pub primary_audio_ins: usize,
    #[serde(default)]
    pub primary_audio_outs: usize,
    pub audio: AudioData,
    pub midi: MIDIData,
    #[serde(default)]
    pub midi_lane_channels: Vec<Option<u8>>,
    #[serde(default)]
    pub frozen_audio_backup: Vec<AudioClip>,
    #[serde(default)]
    pub frozen_midi_backup: Vec<MIDIClip>,
    #[serde(default)]
    pub frozen_render_clip: Option<String>,
    #[serde(default)]
    pub automation_lanes: Vec<TrackAutomationLane>,
    #[serde(default)]
    pub editor_markers: Vec<EditorMarker>,
    #[serde(default = "default_automation_mode")]
    pub automation_mode: TrackAutomationMode,
    #[serde(with = "PointDef")]
    pub position: Point,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "color_option_def"
    )]
    pub color: Option<Color>,
}

fn default_automation_mode() -> TrackAutomationMode {
    TrackAutomationMode::Read
}

impl Track {
    pub fn new(
        name: String,
        level: f32,
        audio_ins: usize,
        audio_outs: usize,
        midi_ins: usize,
        midi_outs: usize,
    ) -> Self {
        let mut track = Self {
            id: 0,
            name,
            level,
            balance: 0.0,
            meter_out_db: vec![-90.0; audio_outs],
            armed: false,
            muted: false,
            phase_inverted: false,
            soloed: false,
            is_master: false,
            input_monitor: false,
            disk_monitor: true,
            midi_learn_volume: None,
            midi_learn_balance: None,
            midi_learn_mute: None,
            midi_learn_solo: None,
            midi_learn_arm: None,
            midi_learn_input_monitor: None,
            midi_learn_disk_monitor: None,
            vca_master: None,
            frozen: false,
            is_folder: false,
            folder_open: true,
            parent_track: None,
            audio: AudioData::new(audio_ins, audio_outs),
            midi: MIDIData::new(midi_ins, midi_outs),
            midi_lane_channels: vec![None; midi_ins],
            primary_audio_ins: audio_ins,
            primary_audio_outs: audio_outs,
            frozen_audio_backup: vec![],
            frozen_midi_backup: vec![],
            frozen_render_clip: None,
            automation_lanes: vec![],
            editor_markers: vec![],
            automation_mode: TrackAutomationMode::Read,
            height: 82.0,
            position: Point::new(100.0, 100.0),
            color: None,
        };
        track.height = track.min_height_for_layout().max(TRACK_MIN_HEIGHT);
        track
    }

    pub fn audio_lane_count(&self) -> usize {
        if self.is_master {
            0
        } else if self.audio.ins > 0 {
            1
        } else {
            0
        }
    }

    pub fn primary_audio_ins(&self) -> usize {
        if self.primary_audio_ins == 0 && self.audio.ins > 0 {
            self.audio.ins
        } else {
            self.primary_audio_ins.min(self.audio.ins)
        }
    }

    pub fn primary_audio_outs(&self) -> usize {
        if self.primary_audio_outs == 0 && self.audio.outs > 0 {
            self.audio.outs
        } else {
            self.primary_audio_outs.min(self.audio.outs)
        }
    }

    pub fn return_count(&self) -> usize {
        self.audio.ins.saturating_sub(self.primary_audio_ins())
    }

    pub fn send_count(&self) -> usize {
        self.audio.outs.saturating_sub(self.primary_audio_outs())
    }

    pub fn midi_lane_count(&self) -> usize {
        if self.is_master { 0 } else { self.midi.ins }
    }

    pub fn automation_lane_count(&self) -> usize {
        self.automation_lanes
            .iter()
            .filter(|lane| lane.visible)
            .count()
    }

    pub fn total_lane_count(&self) -> usize {
        self.audio_lane_count()
            .saturating_add(self.midi_lane_count())
            .saturating_add(self.automation_lane_count())
    }

    pub fn min_height_for_layout(&self) -> f32 {
        let lanes = self.total_lane_count().max(1);
        TRACK_FOLDER_HEADER_HEIGHT
            + (lanes as f32 * TRACK_SUBTRACK_MIN_HEIGHT)
            + ((lanes.saturating_sub(1)) as f32 * TRACK_SUBTRACK_GAP)
    }

    pub fn collapsed(&self) -> bool {
        self.height < self.min_height_for_layout()
    }

    pub fn lane_layout(&self) -> TrackLaneLayout {
        if self.collapsed() {
            TrackLaneLayout {
                header_height: 0.0,
                lane_height: self.height.max(1.0),
                audio_lanes: self.audio_lane_count(),
                midi_lanes: self.midi_lane_count(),
            }
        } else {
            let total_lanes = self.total_lane_count().max(1);
            let available = (self.height - TRACK_FOLDER_HEADER_HEIGHT).max(0.0);
            let gaps = (total_lanes.saturating_sub(1)) as f32 * TRACK_SUBTRACK_GAP;
            let lane_height =
                ((available - gaps) / total_lanes as f32).max(TRACK_SUBTRACK_MIN_HEIGHT);
            TrackLaneLayout {
                header_height: TRACK_FOLDER_HEADER_HEIGHT,
                lane_height,
                audio_lanes: self.audio_lane_count(),
                midi_lanes: self.midi_lane_count(),
            }
        }
    }

    pub fn lane_top(&self, kind: maolan_engine::kind::Kind, lane: usize) -> f32 {
        if self.collapsed() {
            return 0.0;
        }
        let layout = self.lane_layout();
        let mut y = layout.header_height;
        match kind {
            maolan_engine::kind::Kind::Audio => {
                y + lane.min(layout.audio_lanes.saturating_sub(1)) as f32
                    * (layout.lane_height + TRACK_SUBTRACK_GAP)
            }
            maolan_engine::kind::Kind::MIDI => {
                y += layout.audio_lanes as f32 * (layout.lane_height + TRACK_SUBTRACK_GAP);
                y + lane.min(layout.midi_lanes.saturating_sub(1)) as f32
                    * (layout.lane_height + TRACK_SUBTRACK_GAP)
            }
        }
    }

    pub fn lane_index_at_y(&self, kind: maolan_engine::kind::Kind, y: f32) -> usize {
        if self.collapsed() {
            return 0;
        }
        let layout = self.lane_layout();
        let lane_span = layout.lane_height + TRACK_SUBTRACK_GAP;
        let local = (y - layout.header_height).max(0.0);
        match kind {
            maolan_engine::kind::Kind::Audio => {
                if layout.audio_lanes == 0 {
                    0
                } else {
                    ((local / lane_span).floor() as usize).min(layout.audio_lanes - 1)
                }
            }
            maolan_engine::kind::Kind::MIDI => {
                let midi_local = local - (layout.audio_lanes as f32 * lane_span);
                if layout.midi_lanes == 0 {
                    0
                } else {
                    ((midi_local.max(0.0) / lane_span).floor() as usize).min(layout.midi_lanes - 1)
                }
            }
        }
    }

    pub fn automation_lane_top(&self, lane: usize) -> f32 {
        if self.collapsed() {
            return 0.0;
        }
        let layout = self.lane_layout();
        let lane_span = layout.lane_height + TRACK_SUBTRACK_GAP;
        layout.header_height + (layout.audio_lanes + layout.midi_lanes + lane) as f32 * lane_span
    }

    pub fn folder_depth(&self, all_tracks: &[Track]) -> usize {
        let mut depth = 0;
        let mut current = self.parent_track.as_deref();
        while let Some(parent_name) = current {
            depth += 1;
            current = all_tracks
                .iter()
                .find(|t| t.name == parent_name)
                .and_then(|t| t.parent_track.as_deref());
        }
        depth
    }

    pub fn is_inside_closed_folder(&self, all_tracks: &[Track]) -> bool {
        let mut current = self.parent_track.as_deref();
        while let Some(parent_name) = current {
            if let Some(parent) = all_tracks.iter().find(|t| t.name == parent_name) {
                if !parent.folder_open {
                    return true;
                }
                current = parent.parent_track.as_deref();
            } else {
                break;
            }
        }
        false
    }

    pub fn has_folder_children(&self, all_tracks: &[Track]) -> bool {
        all_tracks
            .iter()
            .any(|t| t.parent_track.as_deref() == Some(self.name.as_str()))
    }

    pub fn effective_muted(&self, all_tracks: &[Track]) -> bool {
        if self.muted {
            return true;
        }
        let mut current = self.parent_track.as_deref();
        while let Some(parent_name) = current {
            if let Some(parent) = all_tracks.iter().find(|t| t.name == parent_name) {
                if parent.muted {
                    return true;
                }
                current = parent.parent_track.as_deref();
            } else {
                break;
            }
        }
        false
    }

    pub fn effective_soloed(&self, all_tracks: &[Track]) -> bool {
        if self.soloed {
            return true;
        }
        let mut current = self.parent_track.as_deref();
        while let Some(parent_name) = current {
            if let Some(parent) = all_tracks.iter().find(|t| t.name == parent_name) {
                if parent.soloed {
                    return true;
                }
                current = parent.parent_track.as_deref();
            } else {
                break;
            }
        }
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn audio_data_new_creates_empty() {
        let data = AudioData::new(2, 2);
        assert!(data.clips.is_empty());
        assert_eq!(data.ins, 2);
        assert_eq!(data.outs, 2);
    }

    #[test]
    fn midi_data_new_creates_empty() {
        let data = MIDIData::new(1, 1);
        assert!(data.clips.is_empty());
        assert_eq!(data.ins, 1);
        assert_eq!(data.outs, 1);
    }

    #[test]
    fn track_automation_point_creation() {
        let point = TrackAutomationPoint {
            sample: 100,
            value: 0.5,
        };
        assert_eq!(point.sample, 100);
        assert!((point.value - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn track_automation_lane_default() {
        use crate::message::TrackAutomationTarget;
        let lane = TrackAutomationLane {
            target: TrackAutomationTarget::Volume,
            visible: true,
            points: vec![],
        };
        assert!(lane.visible);
        assert!(lane.points.is_empty());
    }

    #[test]
    fn editor_marker_creation() {
        let marker = EditorMarker {
            sample: 48000,
            name: "Verse".to_string(),
        };
        assert_eq!(marker.sample, 48000);
        assert_eq!(marker.name, "Verse");
    }

    #[test]
    fn track_lane_layout_creation() {
        let layout = TrackLaneLayout {
            header_height: 24.0,
            lane_height: 80.0,
            audio_lanes: 2,
            midi_lanes: 1,
        };
        assert_eq!(layout.header_height, 24.0);
        assert_eq!(layout.audio_lanes, 2);
    }
}