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
use analyser_node::AnalyserNode;
use biquad_filter_node::BiquadFilterNode;
use block::{Chunk, Tick, FRAMES_PER_BLOCK};
use buffer_source_node::AudioBufferSourceNode;
use channel_node::{ChannelMergerNode, ChannelSplitterNode};
use constant_source_node::ConstantSourceNode;
use context::{AudioContextOptions, ProcessingState, StateChangeResult};
use gain_node::GainNode;
use graph::{AudioGraph, InputPort, NodeId, OutputPort, PortId};
use iir_filter_node::IIRFilterNode;
use media_element_source_node::MediaElementSourceNode;
use media_stream_destination_node::MediaStreamDestinationNode;
use media_stream_source_node::MediaStreamSourceNode;
use node::{AudioNodeEngine, AudioNodeInit, AudioNodeMessage};
use node::{BlockInfo, ChannelInfo};
use offline_sink::OfflineAudioSink;
use oscillator_node::OscillatorNode;
use panner_node::PannerNode;
use servo_media_streams::{MediaSocket, MediaStreamId};
use sink::{AudioSink, AudioSinkError};
use std::sync::mpsc::{Receiver, Sender};
use stereo_panner::StereoPannerNode;
use wave_shaper_node::WaveShaperNode;
use {AudioBackend, AudioStreamReader};

pub enum AudioRenderThreadMsg {
    CreateNode(AudioNodeInit, Sender<NodeId>, ChannelInfo),
    ConnectPorts(PortId<OutputPort>, PortId<InputPort>),
    MessageNode(NodeId, AudioNodeMessage),
    Resume(Sender<StateChangeResult>),
    Suspend(Sender<StateChangeResult>),
    Close(Sender<StateChangeResult>),
    SinkNeedData,
    GetCurrentTime(Sender<f64>),

    DisconnectAllFrom(NodeId),
    DisconnectOutput(PortId<OutputPort>),
    DisconnectBetween(NodeId, NodeId),
    DisconnectTo(NodeId, PortId<InputPort>),
    DisconnectOutputBetween(PortId<OutputPort>, NodeId),
    DisconnectOutputBetweenTo(PortId<OutputPort>, PortId<InputPort>),

    SetSinkEosCallback(Box<dyn Fn(Box<dyn AsRef<[f32]>>) + Send + Sync + 'static>),

    SetMute(bool),
}

pub enum Sink {
    RealTime(Box<dyn AudioSink>),
    Offline(OfflineAudioSink),
}

impl AudioSink for Sink {
    fn init(
        &self,
        sample_rate: f32,
        sender: Sender<AudioRenderThreadMsg>,
    ) -> Result<(), AudioSinkError> {
        match *self {
            Sink::RealTime(ref sink) => sink.init(sample_rate, sender),
            Sink::Offline(ref sink) => Ok(sink.init(sample_rate, sender).unwrap()),
        }
    }

    fn init_stream(&self, _: u8, _: f32, _: Box<dyn MediaSocket>) -> Result<(), AudioSinkError> {
        unreachable!("Sink should never be used for MediaStreamDestinationNode")
    }

    fn play(&self) -> Result<(), AudioSinkError> {
        match *self {
            Sink::RealTime(ref sink) => sink.play(),
            Sink::Offline(ref sink) => Ok(sink.play().unwrap()),
        }
    }

    fn stop(&self) -> Result<(), AudioSinkError> {
        match *self {
            Sink::RealTime(ref sink) => sink.stop(),
            Sink::Offline(ref sink) => Ok(sink.stop().unwrap()),
        }
    }

    fn has_enough_data(&self) -> bool {
        match *self {
            Sink::RealTime(ref sink) => sink.has_enough_data(),
            Sink::Offline(ref sink) => sink.has_enough_data(),
        }
    }

    fn push_data(&self, chunk: Chunk) -> Result<(), AudioSinkError> {
        match *self {
            Sink::RealTime(ref sink) => sink.push_data(chunk),
            Sink::Offline(ref sink) => Ok(sink.push_data(chunk).unwrap()),
        }
    }

    fn set_eos_callback(
        &self,
        callback: Box<dyn Fn(Box<dyn AsRef<[f32]>>) + Send + Sync + 'static>,
    ) {
        match *self {
            Sink::RealTime(ref sink) => sink.set_eos_callback(callback),
            Sink::Offline(ref sink) => sink.set_eos_callback(callback),
        }
    }
}

pub struct AudioRenderThread {
    pub graph: AudioGraph,
    pub sink: Sink,
    pub sink_factory: Box<dyn Fn() -> Result<Box<dyn AudioSink + 'static>, AudioSinkError>>,
    pub reader_factory: Box<dyn Fn(MediaStreamId, f32) -> Box<dyn AudioStreamReader + Send>>,
    pub state: ProcessingState,
    pub sample_rate: f32,
    pub current_time: f64,
    pub current_frame: Tick,
    pub muted: bool,
}

impl AudioRenderThread {
    /// Initializes the AudioRenderThread object
    ///
    /// You must call .event_loop() on this to run it!
    fn prepare_thread<B: AudioBackend>(
        sender: Sender<AudioRenderThreadMsg>,
        sample_rate: f32,
        graph: AudioGraph,
        options: AudioContextOptions,
    ) -> Result<Self, AudioSinkError> {
        let sink_factory = Box::new(|| B::make_sink().map(|s| Box::new(s) as Box<dyn AudioSink>));
        let reader_factory = Box::new(|id, sample_rate| B::make_streamreader(id, sample_rate));
        let sink = match options {
            AudioContextOptions::RealTimeAudioContext(_) => Sink::RealTime(sink_factory()?),
            AudioContextOptions::OfflineAudioContext(options) => Sink::Offline(
                OfflineAudioSink::new(options.channels as usize, options.length),
            ),
        };

        sink.init(sample_rate, sender)?;

        Ok(Self {
            graph,
            sink,
            sink_factory,
            reader_factory,
            state: ProcessingState::Suspended,
            sample_rate,
            current_time: 0.,
            current_frame: Tick(0),
            muted: false,
        })
    }

    /// Start the audio render thread
    ///
    /// In case something fails, it will instead start a thread with a dummy backend
    pub fn start<B: AudioBackend>(
        event_queue: Receiver<AudioRenderThreadMsg>,
        sender: Sender<AudioRenderThreadMsg>,
        sample_rate: f32,
        graph: AudioGraph,
        options: AudioContextOptions,
        init_sender: Sender<Result<(), AudioSinkError>>,
    ) {
        let mut thread =
            match Self::prepare_thread::<B>(sender.clone(), sample_rate, graph, options) {
                Ok(thread) => {
                    let _ = init_sender.send(Ok(()));
                    thread
                }
                Err(e) => {
                    let _ = init_sender.send(Err(e));
                    return;
                }
            };

        thread.event_loop(event_queue);
    }

    make_render_thread_state_change!(resume, Running, play);

    make_render_thread_state_change!(suspend, Suspended, stop);

    fn create_node(&mut self, node_type: AudioNodeInit, ch: ChannelInfo) -> NodeId {
        let mut needs_listener = false;
        let mut is_dest = false;
        let node: Box<dyn AudioNodeEngine> = match node_type {
            AudioNodeInit::AnalyserNode(sender) => Box::new(AnalyserNode::new(sender, ch)),
            AudioNodeInit::AudioBufferSourceNode(options) => {
                Box::new(AudioBufferSourceNode::new(options, ch))
            }
            AudioNodeInit::BiquadFilterNode(options) => {
                Box::new(BiquadFilterNode::new(options, ch, self.sample_rate))
            }
            AudioNodeInit::GainNode(options) => Box::new(GainNode::new(options, ch)),
            AudioNodeInit::StereoPannerNode(options) => {
                Box::new(StereoPannerNode::new(options, ch))
            }
            AudioNodeInit::PannerNode(options) => {
                needs_listener = true;
                Box::new(PannerNode::new(options, ch))
            }
            AudioNodeInit::MediaStreamSourceNode(id) => {
                let reader = (self.reader_factory)(id, self.sample_rate);
                Box::new(MediaStreamSourceNode::new(reader, ch))
            }
            AudioNodeInit::OscillatorNode(options) => Box::new(OscillatorNode::new(options, ch)),
            AudioNodeInit::ChannelMergerNode(options) => {
                Box::new(ChannelMergerNode::new(options, ch))
            }
            AudioNodeInit::ConstantSourceNode(options) => {
                Box::new(ConstantSourceNode::new(options, ch))
            }
            AudioNodeInit::MediaStreamDestinationNode(socket) => {
                is_dest = true;
                Box::new(MediaStreamDestinationNode::new(
                    socket,
                    self.sample_rate,
                    (self.sink_factory)().unwrap(),
                    ch,
                ))
            }
            AudioNodeInit::ChannelSplitterNode => Box::new(ChannelSplitterNode::new(ch)),
            AudioNodeInit::WaveShaperNode(options) => Box::new(WaveShaperNode::new(options, ch)),
            AudioNodeInit::MediaElementSourceNode => Box::new(MediaElementSourceNode::new(ch)),
            AudioNodeInit::IIRFilterNode(options) => Box::new(IIRFilterNode::new(options, ch)),
            _ => unimplemented!(),
        };
        let id = self.graph.add_node(node);
        if needs_listener {
            let listener = self.graph.listener_id().output(0);
            self.graph.add_edge(listener, id.listener());
        }
        if is_dest {
            self.graph.add_extra_dest(id);
        }
        id
    }

    fn connect_ports(&mut self, output: PortId<OutputPort>, input: PortId<InputPort>) {
        self.graph.add_edge(output, input)
    }

    fn process(&mut self) -> Chunk {
        if self.muted {
            return Chunk::explicit_silence();
        }

        let info = BlockInfo {
            sample_rate: self.sample_rate,
            frame: self.current_frame,
            time: self.current_time,
        };
        self.graph.process(&info)
    }

    fn set_mute(&mut self, val: bool) -> () {
        self.muted = val;
    }

    fn event_loop(&mut self, event_queue: Receiver<AudioRenderThreadMsg>) {
        let sample_rate = self.sample_rate;
        let handle_msg = move |context: &mut Self, msg: AudioRenderThreadMsg| -> bool {
            let mut break_loop = false;
            match msg {
                AudioRenderThreadMsg::CreateNode(node_type, tx, ch) => {
                    let _ = tx.send(context.create_node(node_type, ch));
                }
                AudioRenderThreadMsg::ConnectPorts(output, input) => {
                    context.connect_ports(output, input);
                }
                AudioRenderThreadMsg::Resume(tx) => {
                    let _ = tx.send(context.resume());
                }
                AudioRenderThreadMsg::Suspend(tx) => {
                    let _ = tx.send(context.suspend());
                }
                AudioRenderThreadMsg::Close(tx) => {
                    let _ = tx.send(context.suspend());
                    break_loop = true;
                }
                AudioRenderThreadMsg::GetCurrentTime(response) => {
                    response.send(context.current_time).unwrap()
                }
                AudioRenderThreadMsg::MessageNode(id, msg) => {
                    context.graph.node_mut(id).message(msg, sample_rate)
                }
                AudioRenderThreadMsg::SinkNeedData => {
                    // Do nothing. This will simply unblock the thread so we
                    // can restart the non-blocking event loop.
                }
                AudioRenderThreadMsg::DisconnectAllFrom(id) => {
                    context.graph.disconnect_all_from(id)
                }
                AudioRenderThreadMsg::DisconnectOutput(out) => context.graph.disconnect_output(out),
                AudioRenderThreadMsg::DisconnectBetween(from, to) => {
                    context.graph.disconnect_between(from, to)
                }
                AudioRenderThreadMsg::DisconnectTo(from, to) => {
                    context.graph.disconnect_to(from, to)
                }
                AudioRenderThreadMsg::DisconnectOutputBetween(from, to) => {
                    context.graph.disconnect_output_between(from, to)
                }
                AudioRenderThreadMsg::DisconnectOutputBetweenTo(from, to) => {
                    context.graph.disconnect_output_between_to(from, to)
                }
                AudioRenderThreadMsg::SetSinkEosCallback(callback) => {
                    context.sink.set_eos_callback(callback);
                }
                AudioRenderThreadMsg::SetMute(val) => {
                    context.set_mute(val);
                }
            };

            break_loop
        };

        loop {
            if self.sink.has_enough_data() || self.state == ProcessingState::Suspended {
                // If we are not processing audio or
                // if we have already pushed enough data into the audio sink
                // we wait for messages coming from the control thread or
                // the audio sink. The audio sink will notify whenever it
                // needs more data.
                if let Ok(msg) = event_queue.recv() {
                    if handle_msg(self, msg) {
                        break;
                    }
                }
            } else {
                // If we have not pushed enough data into the audio sink yet,
                // we process the control message queue
                if let Ok(msg) = event_queue.try_recv() {
                    if handle_msg(self, msg) {
                        break;
                    }
                }

                if self.state == ProcessingState::Suspended {
                    // Bail out if we just suspended processing.
                    continue;
                }

                // push into the audio sink the result of processing a
                // render quantum.
                let data = self.process();
                if self.sink.push_data(data).is_ok() {
                    // increment current frame by the render quantum size.
                    self.current_frame += FRAMES_PER_BLOCK;
                    self.current_time = self.current_frame / self.sample_rate as f64;
                } else {
                    eprintln!("Could not push data to audio sink");
                }
            }
        }
    }
}