2017-10-22 12:17:25 +00:00
|
|
|
use std::mem;
|
2017-10-18 18:24:05 +00:00
|
|
|
use std::os::raw::c_void;
|
2017-10-22 12:17:25 +00:00
|
|
|
use std::slice::from_raw_parts;
|
2019-06-22 15:47:31 +00:00
|
|
|
use std::sync::{Arc, Mutex};
|
2017-10-22 12:17:25 +00:00
|
|
|
use stdweb;
|
|
|
|
use stdweb::Reference;
|
|
|
|
use stdweb::unstable::TryInto;
|
|
|
|
use stdweb::web::TypedArray;
|
2017-10-23 14:41:38 +00:00
|
|
|
use stdweb::web::set_timeout;
|
2017-10-18 18:24:05 +00:00
|
|
|
|
2019-06-20 19:31:15 +00:00
|
|
|
use BuildStreamError;
|
2018-02-12 13:10:24 +00:00
|
|
|
use DefaultFormatError;
|
2019-06-20 22:53:11 +00:00
|
|
|
use DeviceNameError;
|
2019-06-20 20:37:36 +00:00
|
|
|
use DevicesError;
|
2017-10-18 18:24:05 +00:00
|
|
|
use Format;
|
2019-06-21 01:03:03 +00:00
|
|
|
use PauseStreamError;
|
|
|
|
use PlayStreamError;
|
2019-06-20 19:16:39 +00:00
|
|
|
use SupportedFormatsError;
|
2019-06-22 15:47:31 +00:00
|
|
|
use StreamCloseCause;
|
2018-02-12 13:10:24 +00:00
|
|
|
use StreamData;
|
2019-06-22 01:53:51 +00:00
|
|
|
use StreamEvent;
|
2017-10-20 19:18:40 +00:00
|
|
|
use SupportedFormat;
|
2018-02-12 13:10:24 +00:00
|
|
|
use UnknownTypeOutputBuffer;
|
2017-10-18 18:24:05 +00:00
|
|
|
|
|
|
|
// The emscripten backend works by having a global variable named `_cpal_audio_contexts`, which
|
2018-02-12 13:10:24 +00:00
|
|
|
// is an array of `AudioContext` objects. A stream ID corresponds to an entry in this array.
|
2017-10-18 18:24:05 +00:00
|
|
|
//
|
2018-02-12 13:10:24 +00:00
|
|
|
// Creating a stream creates a new `AudioContext`. Destroying a stream destroys it.
|
2017-10-18 18:24:05 +00:00
|
|
|
|
|
|
|
// TODO: handle latency better ; right now we just use setInterval with the amount of sound data
|
|
|
|
// that is in each buffer ; this is obviously bad, and also the schedule is too tight and there may
|
|
|
|
// be underflows
|
|
|
|
|
2017-10-22 12:17:25 +00:00
|
|
|
pub struct EventLoop {
|
2018-02-12 13:10:24 +00:00
|
|
|
streams: Mutex<Vec<Option<Reference>>>,
|
2019-06-22 15:47:31 +00:00
|
|
|
// The `EventLoop` requires a handle to the callbacks in order to be able to emit necessary
|
|
|
|
// events for `Play`, `Pause` and `Close`.
|
|
|
|
user_callback: Arc<Mutex<UserCallback>>
|
|
|
|
}
|
|
|
|
|
|
|
|
enum UserCallback {
|
|
|
|
// When `run` is called with a callback, that callback will be stored here.
|
|
|
|
//
|
|
|
|
// It is essential for the safety of the program that this callback is removed before `run`
|
|
|
|
// returns (not possible with the current CPAL API).
|
|
|
|
Active(&'static mut (dyn FnMut(StreamId, StreamEvent) + Send)),
|
|
|
|
// A queue of events that have occurred but that have not yet been emitted to the user as we
|
|
|
|
// don't yet have a callback to do so.
|
|
|
|
Inactive {
|
|
|
|
pending_events: Vec<(StreamId, StreamEvent<'static>)>
|
|
|
|
},
|
2017-10-22 12:17:25 +00:00
|
|
|
}
|
|
|
|
|
2017-10-18 18:24:05 +00:00
|
|
|
impl EventLoop {
|
|
|
|
#[inline]
|
|
|
|
pub fn new() -> EventLoop {
|
2017-10-22 12:17:25 +00:00
|
|
|
stdweb::initialize();
|
2019-06-22 15:47:31 +00:00
|
|
|
EventLoop {
|
|
|
|
streams: Mutex::new(Vec::new()),
|
|
|
|
user_callback: Arc::new(Mutex::new(UserCallback::Inactive { pending_events: vec![] })),
|
|
|
|
}
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2019-06-22 15:47:31 +00:00
|
|
|
pub fn run<F>(&self, mut callback: F) -> !
|
|
|
|
where F: FnMut(StreamId, StreamEvent) + Send,
|
2017-10-18 18:24:05 +00:00
|
|
|
{
|
2019-06-22 15:47:31 +00:00
|
|
|
// Retrieve and process any pending events.
|
|
|
|
//
|
|
|
|
// Then, set the callback ready to be shared between audio processing and the event loop
|
|
|
|
// handle.
|
|
|
|
{
|
|
|
|
let mut guard = self.user_callback.lock().unwrap();
|
|
|
|
let pending_events = match *guard {
|
|
|
|
UserCallback::Inactive { ref mut pending_events } => {
|
|
|
|
mem::replace(pending_events, vec![])
|
|
|
|
}
|
|
|
|
UserCallback::Active(_) => {
|
|
|
|
panic!("`EventLoop::run` was called when the event loop was already running");
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let callback: &mut (dyn FnMut(StreamId, StreamEvent) + Send) = &mut callback;
|
|
|
|
for (stream_id, event) in pending_events {
|
|
|
|
callback(stream_id, event);
|
|
|
|
}
|
|
|
|
|
|
|
|
*guard = UserCallback::Active(unsafe { mem::transmute(callback) });
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2017-10-22 12:17:25 +00:00
|
|
|
// The `run` function uses `set_timeout` to invoke a Rust callback repeatidely. The job
|
|
|
|
// of this callback is to fill the content of the audio buffers.
|
|
|
|
|
|
|
|
// The first argument of the callback function (a `void*`) is a casted pointer to `self`
|
|
|
|
// and to the `callback` parameter that was passed to `run`.
|
|
|
|
|
|
|
|
fn callback_fn<F>(user_data_ptr: *mut c_void)
|
2019-06-22 01:53:51 +00:00
|
|
|
where F: FnMut(StreamId, StreamEvent)
|
2017-10-22 12:17:25 +00:00
|
|
|
{
|
|
|
|
unsafe {
|
|
|
|
let user_data_ptr2 = user_data_ptr as *mut (&EventLoop, F);
|
|
|
|
let user_data = &mut *user_data_ptr2;
|
|
|
|
let user_cb = &mut user_data.1;
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
let streams = user_data.0.streams.lock().unwrap().clone();
|
|
|
|
for (stream_id, stream) in streams.iter().enumerate() {
|
|
|
|
let stream = match stream.as_ref() {
|
2017-10-22 12:17:25 +00:00
|
|
|
Some(v) => v,
|
|
|
|
None => continue,
|
|
|
|
};
|
|
|
|
|
2019-04-30 06:43:47 +00:00
|
|
|
let mut temporary_buffer = vec![0.0; 44100 * 2 / 3];
|
|
|
|
|
|
|
|
{
|
|
|
|
let buffer = UnknownTypeOutputBuffer::F32(::OutputBuffer { buffer: &mut temporary_buffer });
|
|
|
|
let data = StreamData::Output { buffer: buffer };
|
2019-06-22 01:53:51 +00:00
|
|
|
let event = StreamEvent::Data(data);
|
|
|
|
user_cb(StreamId(stream_id), event);
|
2019-04-30 06:43:47 +00:00
|
|
|
// TODO: directly use a TypedArray<f32> once this is supported by stdweb
|
|
|
|
}
|
|
|
|
|
|
|
|
let typed_array = {
|
|
|
|
let f32_slice = temporary_buffer.as_slice();
|
2019-06-22 15:47:31 +00:00
|
|
|
let u8_slice: &[u8] = from_raw_parts(
|
|
|
|
f32_slice.as_ptr() as *const _,
|
|
|
|
f32_slice.len() * mem::size_of::<f32>(),
|
|
|
|
);
|
2019-04-30 06:43:47 +00:00
|
|
|
let typed_array: TypedArray<u8> = u8_slice.into();
|
|
|
|
typed_array
|
2017-10-22 12:17:25 +00:00
|
|
|
};
|
|
|
|
|
2019-04-30 06:43:47 +00:00
|
|
|
let num_channels = 2u32; // TODO: correct value
|
|
|
|
debug_assert_eq!(temporary_buffer.len() % num_channels as usize, 0);
|
|
|
|
|
|
|
|
js!(
|
|
|
|
var src_buffer = new Float32Array(@{typed_array}.buffer);
|
|
|
|
var context = @{stream};
|
|
|
|
var buf_len = @{temporary_buffer.len() as u32};
|
|
|
|
var num_channels = @{num_channels};
|
|
|
|
|
|
|
|
var buffer = context.createBuffer(num_channels, buf_len / num_channels, 44100);
|
|
|
|
for (var channel = 0; channel < num_channels; ++channel) {
|
|
|
|
var buffer_content = buffer.getChannelData(channel);
|
|
|
|
for (var i = 0; i < buf_len / num_channels; ++i) {
|
|
|
|
buffer_content[i] = src_buffer[i * num_channels + channel];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var node = context.createBufferSource();
|
|
|
|
node.buffer = buffer;
|
|
|
|
node.connect(context.destination);
|
|
|
|
node.start();
|
|
|
|
);
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
2017-10-22 12:17:25 +00:00
|
|
|
set_timeout(|| callback_fn::<F>(user_data_ptr), 330);
|
|
|
|
}
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
2017-10-22 12:17:25 +00:00
|
|
|
|
|
|
|
let mut user_data = (self, callback);
|
|
|
|
let user_data_ptr = &mut user_data as *mut (_, _);
|
|
|
|
|
|
|
|
set_timeout(|| callback_fn::<F>(user_data_ptr as *mut _), 10);
|
|
|
|
|
|
|
|
stdweb::event_loop();
|
2019-06-22 15:47:31 +00:00
|
|
|
|
|
|
|
// It is critical that we remove the callback before returning (currently not possible).
|
|
|
|
// *self.user_callback.lock().unwrap() = UserCallback::Inactive { pending_events: vec![] };
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2019-06-20 19:31:15 +00:00
|
|
|
pub fn build_input_stream(&self, _: &Device, _format: &Format) -> Result<StreamId, BuildStreamError> {
|
2018-02-12 13:10:24 +00:00
|
|
|
unimplemented!();
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2019-06-20 19:31:15 +00:00
|
|
|
pub fn build_output_stream(&self, _: &Device, _format: &Format) -> Result<StreamId, BuildStreamError> {
|
2018-02-12 13:10:24 +00:00
|
|
|
let stream = js!(return new AudioContext()).into_reference().unwrap();
|
2017-10-22 12:17:25 +00:00
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
let mut streams = self.streams.lock().unwrap();
|
|
|
|
let stream_id = if let Some(pos) = streams.iter().position(|v| v.is_none()) {
|
|
|
|
streams[pos] = Some(stream);
|
2017-10-22 12:17:25 +00:00
|
|
|
pos
|
|
|
|
} else {
|
2018-02-12 13:10:24 +00:00
|
|
|
let l = streams.len();
|
|
|
|
streams.push(Some(stream));
|
2017-10-22 12:17:25 +00:00
|
|
|
l
|
2017-10-18 18:24:05 +00:00
|
|
|
};
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
Ok(StreamId(stream_id))
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
2019-06-22 15:47:31 +00:00
|
|
|
fn emit_or_enqueue_event(&self, id: StreamId, event: StreamEvent<'static>) {
|
|
|
|
let mut guard = self.user_callback.lock().unwrap();
|
|
|
|
match *guard {
|
|
|
|
UserCallback::Active(ref mut callback) => callback(id, event),
|
|
|
|
UserCallback::Inactive { ref mut pending_events } => pending_events.push((id, event)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-18 18:24:05 +00:00
|
|
|
#[inline]
|
2018-02-12 13:10:24 +00:00
|
|
|
pub fn destroy_stream(&self, stream_id: StreamId) {
|
|
|
|
self.streams.lock().unwrap()[stream_id.0] = None;
|
2019-06-22 15:47:31 +00:00
|
|
|
let event = StreamEvent::Close(StreamCloseCause::UserDestroyed);
|
|
|
|
self.emit_or_enqueue_event(stream_id, event);
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2019-06-21 01:03:03 +00:00
|
|
|
pub fn play_stream(&self, stream_id: StreamId) -> Result<(), PlayStreamError> {
|
2018-02-12 13:10:24 +00:00
|
|
|
let streams = self.streams.lock().unwrap();
|
|
|
|
let stream = streams
|
|
|
|
.get(stream_id.0)
|
2017-10-23 14:41:38 +00:00
|
|
|
.and_then(|v| v.as_ref())
|
2018-02-12 13:10:24 +00:00
|
|
|
.expect("invalid stream ID");
|
2019-06-22 15:47:31 +00:00
|
|
|
self.emit_or_enqueue_event(stream_id, StreamEvent::Play);
|
2018-02-12 13:10:24 +00:00
|
|
|
js!(@{stream}.resume());
|
2019-06-21 01:03:03 +00:00
|
|
|
Ok(())
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2019-06-21 01:03:03 +00:00
|
|
|
pub fn pause_stream(&self, stream_id: StreamId) -> Result<(), PauseStreamError> {
|
2018-02-12 13:10:24 +00:00
|
|
|
let streams = self.streams.lock().unwrap();
|
|
|
|
let stream = streams
|
|
|
|
.get(stream_id.0)
|
2017-10-23 14:41:38 +00:00
|
|
|
.and_then(|v| v.as_ref())
|
2018-02-12 13:10:24 +00:00
|
|
|
.expect("invalid stream ID");
|
|
|
|
js!(@{stream}.suspend());
|
2019-06-22 15:47:31 +00:00
|
|
|
self.emit_or_enqueue_event(stream_id, StreamEvent::Pause);
|
2019-06-21 01:03:03 +00:00
|
|
|
Ok(())
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
// Index within the `streams` array of the events loop.
|
2017-10-18 18:24:05 +00:00
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
2018-02-12 13:10:24 +00:00
|
|
|
pub struct StreamId(usize);
|
2017-10-18 18:24:05 +00:00
|
|
|
|
|
|
|
// Detects whether the `AudioContext` global variable is available.
|
|
|
|
fn is_webaudio_available() -> bool {
|
2017-10-22 12:17:25 +00:00
|
|
|
stdweb::initialize();
|
|
|
|
|
2017-10-23 14:41:38 +00:00
|
|
|
js!(if (!AudioContext) {
|
|
|
|
return false;
|
|
|
|
} else {
|
|
|
|
return true;
|
|
|
|
}).try_into()
|
|
|
|
.unwrap()
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Content is false if the iterator is empty.
|
2018-02-12 13:10:24 +00:00
|
|
|
pub struct Devices(bool);
|
2019-06-20 20:37:36 +00:00
|
|
|
|
|
|
|
impl Devices {
|
|
|
|
pub fn new() -> Result<Self, DevicesError> {
|
|
|
|
Ok(Self::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
impl Default for Devices {
|
|
|
|
fn default() -> Devices {
|
2017-10-18 18:24:05 +00:00
|
|
|
// We produce an empty iterator if the WebAudio API isn't available.
|
2018-02-12 13:10:24 +00:00
|
|
|
Devices(is_webaudio_available())
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
}
|
2018-02-12 13:10:24 +00:00
|
|
|
impl Iterator for Devices {
|
|
|
|
type Item = Device;
|
2017-10-18 18:24:05 +00:00
|
|
|
#[inline]
|
2018-02-12 13:10:24 +00:00
|
|
|
fn next(&mut self) -> Option<Device> {
|
2017-10-18 18:24:05 +00:00
|
|
|
if self.0 {
|
|
|
|
self.0 = false;
|
2018-02-12 13:10:24 +00:00
|
|
|
Some(Device)
|
2017-10-18 18:24:05 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2018-02-12 13:10:24 +00:00
|
|
|
pub fn default_input_device() -> Option<Device> {
|
|
|
|
unimplemented!();
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn default_output_device() -> Option<Device> {
|
2017-10-18 18:24:05 +00:00
|
|
|
if is_webaudio_available() {
|
2018-02-12 13:10:24 +00:00
|
|
|
Some(Device)
|
2017-10-18 18:24:05 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
2018-02-12 13:10:24 +00:00
|
|
|
pub struct Device;
|
|
|
|
|
|
|
|
impl Device {
|
|
|
|
#[inline]
|
2019-06-20 22:53:11 +00:00
|
|
|
pub fn name(&self) -> Result<String, DeviceNameError> {
|
|
|
|
Ok("Default Device".to_owned())
|
2018-02-12 13:10:24 +00:00
|
|
|
}
|
2017-10-18 18:24:05 +00:00
|
|
|
|
|
|
|
#[inline]
|
2019-06-20 19:16:39 +00:00
|
|
|
pub fn supported_input_formats(&self) -> Result<SupportedInputFormats, SupportedFormatsError> {
|
2018-02-12 13:10:24 +00:00
|
|
|
unimplemented!();
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2019-06-20 19:16:39 +00:00
|
|
|
pub fn supported_output_formats(&self) -> Result<SupportedOutputFormats, SupportedFormatsError> {
|
2017-10-18 18:24:05 +00:00
|
|
|
// TODO: right now cpal's API doesn't allow flexibility here
|
|
|
|
// "44100" and "2" (channels) have also been hard-coded in the rest of the code ; if
|
|
|
|
// this ever becomes more flexible, don't forget to change that
|
2018-07-10 13:04:00 +00:00
|
|
|
// According to https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/createBuffer
|
|
|
|
// browsers must support 1 to 32 channels at leats and 8,000 Hz to 96,000 Hz.
|
2017-10-23 14:41:38 +00:00
|
|
|
Ok(
|
|
|
|
vec![
|
|
|
|
SupportedFormat {
|
2018-02-04 09:38:06 +00:00
|
|
|
channels: 2,
|
2018-02-04 12:02:16 +00:00
|
|
|
min_sample_rate: ::SampleRate(44100),
|
|
|
|
max_sample_rate: ::SampleRate(44100),
|
2017-10-23 14:41:38 +00:00
|
|
|
data_type: ::SampleFormat::F32,
|
|
|
|
},
|
|
|
|
].into_iter(),
|
|
|
|
)
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
pub fn default_input_format(&self) -> Result<Format, DefaultFormatError> {
|
|
|
|
unimplemented!();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn default_output_format(&self) -> Result<Format, DefaultFormatError> {
|
2018-07-10 13:04:00 +00:00
|
|
|
// TODO: because it is hard coded, see supported_output_formats.
|
|
|
|
Ok(
|
|
|
|
Format {
|
|
|
|
channels: 2,
|
|
|
|
sample_rate: ::SampleRate(44100),
|
|
|
|
data_type: ::SampleFormat::F32,
|
|
|
|
},
|
|
|
|
)
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
pub type SupportedInputFormats = ::std::vec::IntoIter<SupportedFormat>;
|
|
|
|
pub type SupportedOutputFormats = ::std::vec::IntoIter<SupportedFormat>;
|