summaryrefslogtreecommitdiff
path: root/src/seq/sequencer.rs
blob: deedc4b71e80d65cb7fb97e248b86b93769c3630 (plain)
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
use super::{Note, NoteStream, IV};

pub fn coalesce<'a, I: Iterator<Item = &'a NoteStream>>(stream_iter: I) -> NoteStream {
    let mut output = NoteStream::new();

    for ns in stream_iter {
        output.extend(ns.iter().cloned());
    }

    output
}

pub struct SchedParams {
    pub epsilon: f32,
}

impl Default for SchedParams {
    fn default() -> SchedParams {
        SchedParams { epsilon: 0.0 }
    }
}

pub fn schedule<'a, 'b: 'a, I: Iterator<Item = &'a Note>, F: FnMut(&'a Note) -> Option<&'b str>>(
    notes: I,
    mut classifier: F,
    params: &SchedParams,
) -> IV {
    let mut output: IV = Default::default();

    for note in notes {
        let grp_name = classifier(note);
        let grp = if let Some(name) = grp_name {
            if !output.groups.contains_key(name) {
                output.groups.insert(name.into(), Vec::new());
            }
            output.groups.get_mut(name).unwrap()
        } else {
            &mut output.default_group
        };

        let mut found: Option<usize> = None;
        for (idx, ns) in grp.iter().enumerate() {
            if ns.len() > 0 {
                let nt = &ns[ns.len() - 1];
                if note.time.0 < nt.time.0 + nt.dur.0 + params.epsilon {
                    continue;
                }
            }
            found = Some(idx);
            break;
        }

        if let Some(nidx) = found {
            grp[nidx].push(note.clone());
        } else {
            grp.push(vec![note.clone()]);
        }
    }

    output
}