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
//! Helper items related to working with sequences of musical bars.

use period::Period;
use time_calc as time;

/// An iterator that converts some iterator of ticks to their simplest possible musical divisions.
///
/// NOTE: This is ported from an old version of jen/core.
#[derive(Clone)]
pub struct SimplestDivisions<I> {
    ppqn: time::Ppqn,
    duration_ticks: time::Ticks,
    ticks_iter: I,
}

/// An iterator yielding each bar's time signature along with its starting position in ticks.
#[derive(Clone)]
pub struct WithStarts<I> {
    bars: I,
    next_start: time::Ticks,
    ppqn: time::Ppqn,
}

/// Convert an iterator yielding bar time signatures into their consecutive periods over time.
#[derive(Clone)]
pub struct Periods<I> {
    bars_with_starts: I,
    ppqn: time::Ppqn,
}

impl<I> SimplestDivisions<I> {
    /// Produce an iterator that converts some iterator of ticks to their simplest possible musical
    /// divisions.
    pub fn new<It>(ticks: It, ppqn: time::Ppqn, duration_ticks: time::Ticks) -> Self
    where
        It: IntoIterator<Item = time::Ticks, IntoIter = I>,
        It::IntoIter: Iterator<Item = time::Ticks>,
    {
        let ticks_iter = ticks.into_iter();
        SimplestDivisions {
            ticks_iter,
            ppqn,
            duration_ticks,
        }
    }
}

impl<I> WithStarts<I> {
    /// Convert an iterator yielding a time signature each bar to also yield the ticks at which
    /// that bar would begin.
    ///
    /// Assumes the first bar starts at `Ticks(0)`.
    pub fn new<It>(bars: It, ppqn: time::Ppqn) -> Self
    where
        It: IntoIterator<Item = time::TimeSig, IntoIter = I>,
        It::IntoIter: Iterator<Item = time::TimeSig>,
    {
        let bars = bars.into_iter();
        WithStarts {
            bars,
            ppqn,
            next_start: time::Ticks(0),
        }
    }
}

impl<I> Periods<WithStarts<I>> {
    pub fn new<It>(bars: It, ppqn: time::Ppqn) -> Self
    where
        It: IntoIterator<Item = time::TimeSig, IntoIter = I>,
        It::IntoIter: Iterator<Item = time::TimeSig>,
    {
        Periods {
            bars_with_starts: WithStarts::new(bars, ppqn),
            ppqn,
        }
    }
}

impl<I> Iterator for SimplestDivisions<I>
where
    I: Iterator<Item = time::Ticks>,
{
    type Item = Option<time::Division>;
    fn next(&mut self) -> Option<Option<time::Division>> {
        match self.ticks_iter.next() {
            None => None,
            Some(ticks) => {
                // If the ticks exceeds the duration of our bar, we'll stop iteration.
                if ticks > self.duration_ticks {
                    return None;
                }

                // If the ticks is 0, we can assume we're on the start of the Bar.
                if ticks == time::Ticks(0) {
                    return Some(Some(time::Division::Bar));
                }

                // We'll start at a `Minim` division and zoom in until we find a division that
                // would divide our ticks and return a whole number.
                let mut div = time::Division::Minim;
                while div.to_u8() <= time::Division::OneThousandTwentyFourth.to_u8() {
                    let div_in_beats = 2.0f64.powi(time::Division::Beat as i32 - div as i32);
                    let div_in_ticks = time::Ticks((div_in_beats * self.ppqn as f64).floor() as _);
                    if ticks % div_in_ticks == time::Ticks(0) {
                        return Some(Some(div));
                    }
                    div = div
                        .zoom_in(1)
                        .expect("Zoomed in too far when finding the simplest div");
                }

                // If we didn't find any matching divisions, we'll indicate this by returning None.
                Some(None)
            }
        }
    }
}

impl<I> Iterator for WithStarts<I>
where
    I: Iterator<Item = time::TimeSig>,
{
    type Item = (time::TimeSig, time::Ticks);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(ts) = self.bars.next() {
            let ticks = ts.ticks_per_bar(self.ppqn);
            let start = self.next_start;
            self.next_start += ticks;
            return Some((ts, start));
        }
        None
    }
}

impl<I> Iterator for Periods<I>
where
    I: Iterator<Item = (time::TimeSig, time::Ticks)>,
{
    type Item = Period;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((ts, start)) = self.bars_with_starts.next() {
            let duration = ts.ticks_per_bar(self.ppqn);
            let end = start + duration;
            return Some(Period { start, end });
        }
        None
    }
}