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
use block::{Chunk, Tick};
use node::{AudioNodeEngine, AudioScheduledSourceNodeMessage, BlockInfo, OnEndedCallback};
use node::{AudioNodeType, ChannelInfo, ShouldPlay};
use num_traits::cast::NumCast;
use param::{Param, ParamType};

#[derive(Clone, Debug)]
pub struct PeriodicWaveOptions {
    // XXX https://webaudio.github.io/web-audio-api/#dictdef-periodicwaveoptions
}
#[derive(Clone, Debug)]
pub enum OscillatorType {
    Sine,
    Square,
    Sawtooth,
    Triangle,
    Custom,
}

#[derive(Clone, Debug)]
pub struct OscillatorNodeOptions {
    pub oscillator_type: OscillatorType,
    pub freq: f32,
    pub detune: f32,
    pub periodic_wave_options: Option<PeriodicWaveOptions>,
}

impl Default for OscillatorNodeOptions {
    fn default() -> Self {
        OscillatorNodeOptions {
            oscillator_type: OscillatorType::Sine,
            freq: 440.,
            detune: 0.,
            periodic_wave_options: None,
        }
    }
}

#[derive(Clone, Debug)]
pub enum OscillatorNodeMessage {
    SetOscillatorType(OscillatorType),
}

#[derive(AudioScheduledSourceNode, AudioNodeCommon)]
pub(crate) struct OscillatorNode {
    channel_info: ChannelInfo,
    oscillator_type: OscillatorType,
    frequency: Param,
    detune: Param,
    phase: f64,
    /// Time at which the source should start playing.
    start_at: Option<Tick>,
    /// Time at which the source should stop playing.
    stop_at: Option<Tick>,
    /// The ended event callback.
    onended_callback: Option<OnEndedCallback>,
}

impl OscillatorNode {
    pub fn new(options: OscillatorNodeOptions, channel_info: ChannelInfo) -> Self {
        Self {
            channel_info,
            oscillator_type: options.oscillator_type,
            frequency: Param::new(options.freq.into()),
            detune: Param::new(options.detune.into()),
            phase: 0.,
            start_at: None,
            stop_at: None,
            onended_callback: None,
        }
    }

    pub fn update_parameters(&mut self, info: &BlockInfo, tick: Tick) -> bool {
        self.frequency.update(info, tick)
    }

    fn handle_oscillator_message(&mut self, message: OscillatorNodeMessage, _sample_rate: f32) {
        match message {
            OscillatorNodeMessage::SetOscillatorType(o) => {
                self.oscillator_type = o;
            }
        }
    }
}

impl AudioNodeEngine for OscillatorNode {
    fn node_type(&self) -> AudioNodeType {
        AudioNodeType::OscillatorNode
    }

    fn process(&mut self, mut inputs: Chunk, info: &BlockInfo) -> Chunk {
        // XXX Implement this properly and according to self.options
        // as defined in https://webaudio.github.io/web-audio-api/#oscillatornode
        use std::f64::consts::PI;
        debug_assert!(inputs.len() == 0);
        inputs.blocks.push(Default::default());
        let (start_at, stop_at) = match self.should_play_at(info.frame) {
            ShouldPlay::No => {
                return inputs;
            }
            ShouldPlay::Between(start, end) => (start, end),
        };

        {
            inputs.blocks[0].explicit_silence();
            let mut iter = inputs.blocks[0].iter();

            // Convert all our parameters to the target type for calculations
            let vol: f32 = 1.0;
            let sample_rate = info.sample_rate as f64;
            let two_pi = 2.0 * PI;

            // We're carrying a phase with up to 2pi around instead of working
            // on the sample offset. High sample offsets cause too much inaccuracy when
            // converted to floating point numbers and then iterated over in 1-steps
            //
            // Also, if the frequency changes the phase should not
            let mut step = two_pi * self.frequency.value() as f64 / sample_rate;
            while let Some(mut frame) = iter.next() {
                let tick = frame.tick();
                if tick < start_at {
                    continue;
                } else if tick > stop_at {
                    break;
                }

                if self.update_parameters(info, tick) {
                    step = two_pi * self.frequency.value() as f64 / sample_rate;
                }
                let mut value = vol;
                match self.oscillator_type {
                    OscillatorType::Sine => {
                        value = vol * f32::sin(NumCast::from(self.phase).unwrap());
                    }

                    OscillatorType::Square => {
                        if self.phase >= PI && self.phase < two_pi {
                            value = vol * 1.0;
                        } else if self.phase > 0.0 && self.phase < PI {
                            value = vol * (-1.0);
                        }
                    }

                    OscillatorType::Sawtooth => {
                        value = vol * ((self.phase as f64) / (PI)) as f32;
                    }

                    OscillatorType::Triangle => {
                        if self.phase >= 0. && self.phase < PI / 2. {
                            value = vol * 2.0 * ((self.phase as f64) / (PI)) as f32;
                        } else if self.phase >= PI / 2. && self.phase < PI {
                            value =
                                vol * (1. - (((self.phase as f64) - (PI / 2.)) * (2. / PI)) as f32);
                        } else if self.phase >= PI && self.phase < (3. * PI / 2.) {
                            value = vol
                                * -1.
                                * (1. - (((self.phase as f64) - (PI / 2.)) * (2. / PI)) as f32);
                        } else if self.phase >= 3. * PI / 2. && self.phase < 2. * PI {
                            value = vol * (-2.0) * ((self.phase as f64) / (PI)) as f32;
                        }
                    }

                    OscillatorType::Custom => {}
                }

                frame.mutate_with(|sample, _| *sample = value);

                self.phase += step;
                if self.phase >= two_pi {
                    self.phase -= two_pi;
                }
            }
        }
        inputs
    }

    fn input_count(&self) -> u32 {
        0
    }

    fn get_param(&mut self, id: ParamType) -> &mut Param {
        match id {
            ParamType::Frequency => &mut self.frequency,
            ParamType::Detune => &mut self.detune,
            _ => panic!("Unknown param {:?} for OscillatorNode", id),
        }
    }
    make_message_handler!(
        AudioScheduledSourceNode: handle_source_node_message,
        OscillatorNode: handle_oscillator_message
    );
}