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
use pitch::{self, Hz};
use rand;
use std;
use time;
use unit::NoteHz;
use voice::{NoteState, Voice};

/// Types designed to modulate the state of a Node.
pub trait NoteFreqGenerator {
    /// The note frequency generated by the NoteFreqModulator type.
    type NoteFreq: NoteFreq;

    /// Construct a new note_freq from the note_hz given by a note_event and the last voice that
    /// handled a note.
    fn generate(&self,
                note_hz: NoteHz,
                detune: f32,
                voice: Option<&Voice<Self::NoteFreq>>) -> Self::NoteFreq;
}


/// Types to be generated by `NoteFreqGenerator` types.
pub trait NoteFreq: Clone + std::fmt::Debug {
    /// Get the current Hz from the NoteFreq.
    fn hz(&self) -> pitch::calc::Hz;
    /// Calls `NoteFreq::hz` and then steps forward `Self` by one frame.
    fn next_hz(&mut self) -> pitch::calc::Hz;
}


/// A PortamentoNote generator that applies a glissando for the given number of samples.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Portamento(pub time::calc::Samples);

/// A note that interpolates between to given frequencies over the given duration.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct PortamentoFreq {
    pub current_sample: time::calc::Samples,
    pub target_samples: time::calc::Samples,
    pub start_mel: pitch::calc::Mel,
    pub target_mel: pitch::calc::Mel,
}


/// A wrapper for switching between NoteFreqGenerators at runtime.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum DynamicGenerator {
    Portamento(Portamento),
    Constant,
}

/// A warpper for switching between different NoteFreqs at runtime.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Dynamic {
    Portamento(PortamentoFreq),
    Constant(pitch::calc::Hz),
}


impl DynamicGenerator {
    /// Construct a default portamento.
    pub fn portamento(samples: time::calc::Samples) -> DynamicGenerator {
        DynamicGenerator::Portamento(Portamento(samples))
    }
}


/// Generate a constant `Hz` frequency.
fn generate_constant_freq(note_hz: NoteHz, detune: f32) -> pitch::calc::Hz {
    // If some detune was given, slightly detune the note_hz.
    if detune > 0.0 {
        let step_offset = rand::random::<f32>() * 2.0 * detune - detune;
        pitch::Step(Hz(note_hz).step() + step_offset).hz()
    // Otherwise, our target_hz is the given note_hz.
    } else {
        note_hz
    }
}


/// Generate a portamento frequency.
fn generate_portamento_freq(portamento_samples: time::calc::Samples,
                            note_hz: NoteHz,
                            detune: f32,
                            maybe_last_hz: Option<pitch::calc::Hz>) -> PortamentoFreq {

    // If some detune was given, slightly detune the note_hz.
    let target_hz = generate_constant_freq(note_hz, detune);

    PortamentoFreq {
        current_sample: 0,
        target_samples: portamento_samples,
        start_mel: Hz(maybe_last_hz.unwrap_or(target_hz)).mel(),
        target_mel: Hz(target_hz).mel(),
    }
}


impl NoteFreqGenerator for () {
    type NoteFreq = pitch::calc::Hz;
    fn generate(&self,
                note_hz: NoteHz,
                detune: f32,
                _voice: Option<&Voice<pitch::calc::Hz>>) -> pitch::calc::Hz {
        generate_constant_freq(note_hz, detune)
    }
}

impl NoteFreq for pitch::calc::Hz {
    fn hz(&self) -> pitch::calc::Hz { *self }
    fn next_hz(&mut self) -> pitch::calc::Hz { *self }
}


impl NoteFreqGenerator for Portamento {
    type NoteFreq = PortamentoFreq;
    fn generate(&self,
                note_hz: NoteHz,
                detune: f32,
                maybe_voice: Option<&Voice<PortamentoFreq>>) -> PortamentoFreq {

        let Portamento(duration_samples) = *self;

        // If some note is already playing, take it to use for portamento.
        let maybe_last_hz = match maybe_voice {
            Some(voice) => match voice.note.as_ref() {
                Some(note) if note.state == NoteState::Playing => Some(note.freq.hz()),
                _ => None,
            },
            None => None,
        };

        generate_portamento_freq(duration_samples, note_hz, detune, maybe_last_hz)
    }
}

impl NoteFreq for PortamentoFreq {
    fn hz(&self) -> pitch::calc::Hz {
        if self.current_sample < self.target_samples {
            let perc = self.current_sample as f64 / self.target_samples as f64;
            let diff_mel = self.target_mel - self.start_mel;
            let perc_diff_mel = perc * diff_mel as f64;
            let mel = self.start_mel + perc_diff_mel as pitch::calc::Mel;
            pitch::Mel(mel).hz()
        } else {
            pitch::Mel(self.target_mel).hz()
        }
    }
    fn next_hz(&mut self) -> pitch::calc::Hz {
        let hz = self.hz();
        if self.current_sample < self.target_samples {
            self.current_sample += 1;
        }
        hz
    }
}


impl NoteFreqGenerator for DynamicGenerator {
    type NoteFreq = Dynamic;
    fn generate(&self,
                note_hz: NoteHz,
                detune: f32,
                maybe_voice: Option<&Voice<Dynamic>>) -> Dynamic {
        match *self {
            DynamicGenerator::Portamento(Portamento(portamento_ms)) => {
                // If some note is already playing, take it to use for portamento.
                let maybe_last_hz = match maybe_voice {
                    Some(voice) => match voice.note.as_ref() {
                        Some(note) if note.state == NoteState::Playing => Some(note.freq.hz()),
                        _ => None,
                    },
                    None => None,
                };
                let freq = generate_portamento_freq(portamento_ms, note_hz, detune, maybe_last_hz);
                Dynamic::Portamento(freq)
            },
            DynamicGenerator::Constant =>
                Dynamic::Constant(generate_constant_freq(note_hz, detune)),
        }
    }
}

impl NoteFreq for Dynamic {
    fn hz(&self) -> pitch::calc::Hz {
        match *self {
            Dynamic::Portamento(ref porta) => porta.hz(),
            Dynamic::Constant(ref hz) => hz.hz(),
        }
    }
    fn next_hz(&mut self) -> pitch::calc::Hz {
        match *self {
            Dynamic::Portamento(ref mut porta) => porta.next_hz(),
            Dynamic::Constant(ref mut hz)      => hz.next_hz(),
        }
    }
}