cpal 0.18.0

Low-level cross-platform audio I/O library.
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! Web Audio backend implementation.
//!
//! Default backend on WebAssembly.

extern crate js_sys;
extern crate wasm_bindgen;
extern crate web_sys;

use std::{
    fmt,
    ops::DerefMut,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, Mutex, RwLock,
    },
    time::Duration,
};

type OutputDataCallbackArc = Arc<Mutex<dyn FnMut(&mut Data, &OutputCallbackInfo) + Send>>;

use self::{
    wasm_bindgen::{prelude::*, JsCast},
    web_sys::{AudioContext, AudioContextOptions},
};
use crate::{
    host::ErrorCallbackArc,
    traits::{DeviceTrait, HostTrait, StreamTrait},
    BufferSize, ChannelCount, Data, DeviceDescription, DeviceDescriptionBuilder, DeviceDirection,
    DeviceId, Error, ErrorKind, FrameCount, InputCallbackInfo, OutputCallbackInfo,
    OutputStreamTimestamp, SampleFormat, SampleRate, StreamConfig, StreamInstant,
    SupportedBufferSize, SupportedStreamConfig, SupportedStreamConfigRange,
};

/// Type alias for shared closure handles used in audio callbacks
type ClosureHandle = Arc<RwLock<Option<Closure<dyn FnMut()>>>>;

/// Content is false if the iterator is empty.
pub struct Devices(bool);

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Device;

impl fmt::Display for Device {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = self.description().map_err(|_| fmt::Error)?;
        f.write_str(desc.name())
    }
}

pub struct Host;

pub struct Stream {
    ctx: Arc<AudioContext>,
    on_ended_closures: Vec<ClosureHandle>,
    config: StreamConfig,
    buffer_size_frames: usize,
    is_started: Arc<AtomicBool>,
}

// WASM runs in a single-threaded environment, so Send and Sync are safe by design.
unsafe impl Send for Stream {}
unsafe impl Sync for Stream {}

// Compile-time assertion that Stream is Send and Sync
crate::assert_stream_send!(Stream);
crate::assert_stream_sync!(Stream);

pub use crate::iter::{SupportedInputConfigs, SupportedOutputConfigs};

// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
const MIN_CHANNELS: ChannelCount = 1;
const MAX_CHANNELS: ChannelCount = 32;

// https://webaudio.github.io/web-audio-api/#supported-sample-rates
const MIN_SAMPLE_RATE: SampleRate = 3_000;
const MAX_SAMPLE_RATE: SampleRate = 768_000;

// https://webaudio.github.io/web-audio-api/#audio-processing-model
const SUPPORTED_SAMPLE_FORMAT: SampleFormat = SampleFormat::F32;

const DEFAULT_BUFFER_SIZE: usize = 2048;

impl Host {
    pub fn new() -> Result<Self, Error> {
        Ok(Self)
    }
}

impl HostTrait for Host {
    type Devices = Devices;
    type Device = Device;

    fn is_available() -> bool {
        // Assume this host is always available on webaudio.
        true
    }

    fn devices(&self) -> Result<Self::Devices, Error> {
        Self::Devices::new()
    }

    fn default_input_device(&self) -> Option<Self::Device> {
        default_input_device()
    }

    fn default_output_device(&self) -> Option<Self::Device> {
        default_output_device()
    }
}

impl Devices {
    fn new() -> Result<Self, Error> {
        Ok(Devices(is_webaudio_available()))
    }
}

impl Device {
    fn description(&self) -> Result<DeviceDescription, Error> {
        Ok(DeviceDescriptionBuilder::new("Default Device")
            .direction(DeviceDirection::Output)
            .build())
    }

    fn id(&self) -> Result<DeviceId, Error> {
        Ok(DeviceId::new(crate::platform::HostId::WebAudio, "default"))
    }

    fn supported_input_configs(&self) -> Result<SupportedInputConfigs, Error> {
        // TODO
        Ok(Vec::new().into_iter())
    }

    fn supported_output_configs(&self) -> Result<SupportedOutputConfigs, Error> {
        let buffer_size = SupportedBufferSize::Range {
            min: 1,
            max: FrameCount::MAX,
        };
        let configs: Vec<_> = (MIN_CHANNELS..=MAX_CHANNELS)
            .flat_map(|channels| {
                crate::COMMON_SAMPLE_RATES
                    .iter()
                    .copied()
                    .filter(|&r| (MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&r))
                    .map(move |rate| SupportedStreamConfigRange {
                        channels,
                        min_sample_rate: rate,
                        max_sample_rate: rate,
                        buffer_size,
                        sample_format: SUPPORTED_SAMPLE_FORMAT,
                    })
            })
            .collect();
        Ok(configs.into_iter())
    }

    fn default_input_config(&self) -> Result<SupportedStreamConfig, Error> {
        Err(Error::with_message(
            ErrorKind::UnsupportedOperation,
            "Device does not support input",
        ))
    }

    fn default_output_config(&self) -> Result<SupportedStreamConfig, Error> {
        let range = self
            .supported_output_configs()?
            .max_by(|a, b| a.cmp_default_heuristics(b))
            .ok_or_else(|| {
                Error::with_message(
                    ErrorKind::UnsupportedConfig,
                    "No supported output configuration",
                )
            })?;
        let config = range
            .try_with_standard_sample_rate()
            .unwrap_or_else(|| range.with_max_sample_rate());

        Ok(config)
    }
}

impl DeviceTrait for Device {
    type SupportedInputConfigs = SupportedInputConfigs;
    type SupportedOutputConfigs = SupportedOutputConfigs;
    type Stream = Stream;

    fn description(&self) -> Result<DeviceDescription, Error> {
        Self::description(self)
    }

    fn id(&self) -> Result<DeviceId, Error> {
        Self::id(self)
    }

    fn supported_input_configs(&self) -> Result<Self::SupportedInputConfigs, Error> {
        Self::supported_input_configs(self)
    }

    fn supported_output_configs(&self) -> Result<Self::SupportedOutputConfigs, Error> {
        Self::supported_output_configs(self)
    }

    fn default_input_config(&self) -> Result<SupportedStreamConfig, Error> {
        Self::default_input_config(self)
    }

    fn default_output_config(&self) -> Result<SupportedStreamConfig, Error> {
        Self::default_output_config(self)
    }

    fn build_input_stream_raw<D, E>(
        &self,
        _config: StreamConfig,
        _sample_format: SampleFormat,
        _data_callback: D,
        _error_callback: E,
        _timeout: Option<Duration>,
    ) -> Result<Self::Stream, Error>
    where
        D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
        E: FnMut(Error) + Send + 'static,
    {
        Err(Error::with_message(
            ErrorKind::UnsupportedOperation,
            "Device does not support input",
        ))
    }

    /// Create an output stream.
    fn build_output_stream_raw<D, E>(
        &self,
        config: StreamConfig,
        sample_format: SampleFormat,
        data_callback: D,
        error_callback: E,
        _timeout: Option<Duration>,
    ) -> Result<Self::Stream, Error>
    where
        D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
        E: FnMut(Error) + Send + 'static,
    {
        crate::validate_stream_config(&config)?;
        if config.channels > MAX_CHANNELS {
            return Err(Error::with_message(
                ErrorKind::UnsupportedConfig,
                format!(
                    "Channel count {} exceeds the maximum of {MAX_CHANNELS}",
                    config.channels
                ),
            ));
        }
        if sample_format != SUPPORTED_SAMPLE_FORMAT {
            return Err(Error::with_message(
                ErrorKind::UnsupportedConfig,
                format!(
                    "Sample format {sample_format} is not supported; required format is {SUPPORTED_SAMPLE_FORMAT}"
                ),
            ));
        }
        if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&config.sample_rate) {
            return Err(Error::with_message(
                ErrorKind::UnsupportedConfig,
                format!(
                    "Sample rate {} Hz is not in the supported range {MIN_SAMPLE_RATE}..={MAX_SAMPLE_RATE} Hz",
                    config.sample_rate
                ),
            ));
        }

        let n_channels = config.channels as usize;

        let buffer_size_frames = match config.buffer_size {
            BufferSize::Fixed(v) => v as usize,
            BufferSize::Default => DEFAULT_BUFFER_SIZE,
        };
        let buffer_size_samples = buffer_size_frames.checked_mul(n_channels).ok_or_else(|| {
            Error::with_message(
                ErrorKind::UnsupportedConfig,
                format!(
                    "Buffer size {} * channel count {} overflows on this platform",
                    buffer_size_frames, config.channels
                ),
            )
        })?;
        let buffer_time_step_secs = buffer_time_step_secs(buffer_size_frames, config.sample_rate);

        let data_callback: OutputDataCallbackArc = Arc::new(Mutex::new(data_callback));
        let error_callback: ErrorCallbackArc = Arc::new(Mutex::new(error_callback));
        let is_started = Arc::new(AtomicBool::new(false));

        // Create the WebAudio stream.
        let stream_opts = AudioContextOptions::new();
        stream_opts.set_sample_rate(config.sample_rate as f32);
        let ctx = AudioContext::new_with_context_options(&stream_opts).map_err(|_| {
            Error::with_message(
                ErrorKind::UnsupportedConfig,
                "Failed to create audio context",
            )
        })?;

        let destination = ctx.destination();

        if config.channels as u32 > destination.max_channel_count() {
            return Err(Error::with_message(
                ErrorKind::UnsupportedConfig,
                format!(
                    "Channel count {} exceeds the destination's maximum of {}",
                    config.channels,
                    destination.max_channel_count()
                ),
            ));
        }
        destination.set_channel_count(config.channels as u32);

        // SAFETY: WASM is single-threaded, so Arc is safe even though AudioContext is not Send/Sync
        #[allow(clippy::arc_with_non_send_sync)]
        let ctx = Arc::new(ctx);

        // A container for managing the lifecycle of the audio callbacks.
        let mut on_ended_closures: Vec<ClosureHandle> = Vec::new();

        // A cursor keeping track of the current time at which new frames should be scheduled.
        let time = Arc::new(RwLock::new(0f64));

        // baseLatency is fixed for the lifetime of the AudioContext.
        let base_latency_secs = js_sys::Reflect::get(ctx.as_ref(), &JsValue::from("baseLatency"))
            .ok()
            .and_then(|v| v.as_f64())
            .unwrap_or(0.0);

        // Create a set of closures / callbacks which will continuously fetch and schedule sample
        // playback. Starting with two workers, e.g. a front and back buffer so that audio frames
        // can be fetched in the background.
        for _i in 0..2 {
            let data_callback_handle = data_callback.clone();
            let error_callback_handle = error_callback.clone();
            let ctx_handle = ctx.clone();
            let time_handle = time.clone();

            // A set of temporary buffers to be used for intermediate sample transformation steps.
            let mut temporary_buffer = vec![0f32; buffer_size_samples];
            let mut temporary_channel_buffer = vec![0f32; buffer_size_frames];

            #[cfg(target_feature = "atomics")]
            let temporary_channel_array_view: js_sys::Float32Array;
            #[cfg(target_feature = "atomics")]
            {
                let temporary_channel_array = js_sys::ArrayBuffer::new(
                    (std::mem::size_of::<f32>() * buffer_size_frames) as u32,
                );
                temporary_channel_array_view = js_sys::Float32Array::new(&temporary_channel_array);
            }

            // Create a webaudio buffer which will be reused to avoid allocations.
            let ctx_buffer = ctx
                .create_buffer(
                    config.channels as u32,
                    buffer_size_frames as u32,
                    config.sample_rate as f32,
                )
                .map_err(|_| {
                    Error::with_message(
                        ErrorKind::UnsupportedConfig,
                        "Failed to create audio buffer",
                    )
                })?;

            // A self reference to this closure for passing to future audio event calls.
            // SAFETY: WASM is single-threaded, so Arc is safe even though Closure is not Send/Sync
            #[allow(clippy::arc_with_non_send_sync)]
            let on_ended_closure: ClosureHandle = Arc::new(RwLock::new(None));
            let on_ended_closure_handle = on_ended_closure.clone();

            on_ended_closure
                .write()
                .unwrap()
                .replace(Closure::wrap(Box::new(move || {
                    let now = ctx_handle.current_time();
                    let time_at_start_of_buffer = {
                        let time_at_start_of_buffer = time_handle
                            .read()
                            .expect("Unable to get a read lock on the time cursor");
                        // Synchronise first buffer as necessary (eg. keep the time value
                        // referenced to the context clock).
                        if *time_at_start_of_buffer > 0.0 {
                            *time_at_start_of_buffer
                        } else {
                            // Schedule the first buffer far enough ahead for the browser's
                            // internal audio pipeline (baseLatency) plus one full buffer of
                            // data, so playback starts underrun-free at any buffer size.
                            now + base_latency_secs + buffer_time_step_secs
                        }
                    };

                    // Populate the sample data into an interleaved temporary buffer.
                    {
                        let len = temporary_buffer.len();
                        let data = temporary_buffer.as_mut_ptr() as *mut ();
                        let mut data = unsafe { Data::from_parts(data, len, sample_format) };
                        match data_callback_handle.lock() {
                            Ok(mut data_callback) => {
                                // outputLatency can change at runtime, so read it each callback.
                                let output_latency_secs = js_sys::Reflect::get(
                                    ctx_handle.as_ref(),
                                    &JsValue::from("outputLatency"),
                                )
                                .ok()
                                .and_then(|v| v.as_f64())
                                .unwrap_or(0.0);
                                let total_hw_latency_secs = {
                                    let sum = base_latency_secs + output_latency_secs;
                                    if sum.is_finite() {
                                        sum.max(0.0)
                                    } else {
                                        0.0
                                    }
                                };
                                let callback = StreamInstant::from_secs_f64(now);
                                let playback = StreamInstant::from_secs_f64(
                                    time_at_start_of_buffer + total_hw_latency_secs,
                                );
                                let timestamp = OutputStreamTimestamp { callback, playback };
                                let info = OutputCallbackInfo { timestamp };
                                (data_callback.deref_mut())(&mut data, &info);
                            }
                            Err(_) => {
                                (error_callback_handle
                                    .lock()
                                    .unwrap_or_else(|e| e.into_inner()))(
                                    Error::with_message(
                                        ErrorKind::StreamInvalidated,
                                        "Stream lock poisoned",
                                    ),
                                );
                                return;
                            }
                        }
                    }

                    // Deinterleave the sample data and copy into the audio context buffer.
                    // We do not reference the audio context buffer directly e.g. getChannelData.
                    // As wasm-bindgen only gives us a copy, not a direct reference.
                    for channel in 0..n_channels {
                        for i in 0..buffer_size_frames {
                            temporary_channel_buffer[i] =
                                temporary_buffer[n_channels * i + channel];
                        }

                        #[cfg(not(target_feature = "atomics"))]
                        {
                            if ctx_buffer
                                .copy_to_channel(&temporary_channel_buffer, channel as i32)
                                .is_err()
                            {
                                (error_callback_handle
                                    .lock()
                                    .unwrap_or_else(|e| e.into_inner()))(
                                    Error::with_message(
                                        ErrorKind::StreamInvalidated,
                                        "Failed to copy audio data",
                                    ),
                                );
                                return;
                            }
                        }

                        // copyToChannel cannot be directly copied into from a SharedArrayBuffer,
                        // which WASM memory is backed by if the 'atomics' flag is enabled.
                        // This workaround copies the data into an intermediary buffer first.
                        // There's a chance browsers may eventually relax that requirement.
                        // See this issue: https://github.com/WebAudio/web-audio-api/issues/2565
                        #[cfg(target_feature = "atomics")]
                        {
                            temporary_channel_array_view.copy_from(&temporary_channel_buffer);
                            if ctx_buffer
                                .unchecked_ref::<ExternalArrayAudioBuffer>()
                                .copy_to_channel(&temporary_channel_array_view, channel as i32)
                                .is_err()
                            {
                                (error_callback_handle
                                    .lock()
                                    .unwrap_or_else(|e| e.into_inner()))(
                                    Error::with_message(
                                        ErrorKind::StreamInvalidated,
                                        "Failed to copy audio data",
                                    ),
                                );
                                return;
                            }
                        }
                    }

                    // Create an AudioBufferSourceNode, schedule it to playback the reused buffer
                    // in the future.
                    let source = match ctx_handle.create_buffer_source() {
                        Ok(s) => s,
                        Err(_) => {
                            // create_buffer_source is documented not to throw; defensive only.
                            (error_callback_handle
                                .lock()
                                .unwrap_or_else(|e| e.into_inner()))(
                                Error::with_message(
                                    ErrorKind::StreamInvalidated,
                                    "Failed to create audio buffer source",
                                ),
                            );
                            return;
                        }
                    };
                    source.set_buffer(Some(&ctx_buffer));
                    if source
                        .connect_with_audio_node(&ctx_handle.destination())
                        .is_err()
                    {
                        (error_callback_handle
                            .lock()
                            .unwrap_or_else(|e| e.into_inner()))(
                            Error::with_message(
                                ErrorKind::StreamInvalidated,
                                "Failed to connect audio node",
                            ),
                        );
                        return;
                    }
                    if source
                        .add_event_listener_with_callback(
                            "ended",
                            on_ended_closure_handle
                                .read()
                                .unwrap()
                                .as_ref()
                                .unwrap()
                                .as_ref()
                                .unchecked_ref(),
                        )
                        .is_err()
                    {
                        // addEventListener is documented not to throw; defensive only.
                        (error_callback_handle
                            .lock()
                            .unwrap_or_else(|e| e.into_inner()))(
                            Error::with_message(
                                ErrorKind::StreamInvalidated,
                                "Failed to register audio event listener",
                            ),
                        );
                        return;
                    }
                    if source.start_with_when(time_at_start_of_buffer).is_err() {
                        // InvalidStateError (already started) is the expected failure mode.
                        (error_callback_handle
                            .lock()
                            .unwrap_or_else(|e| e.into_inner()))(
                            Error::with_message(
                                ErrorKind::StreamInvalidated,
                                "Failed to start audio buffer source",
                            ),
                        );
                        return;
                    }

                    // Keep track of when the next buffer worth of samples should be played.
                    *time_handle.write().unwrap() = time_at_start_of_buffer + buffer_time_step_secs;
                }) as Box<dyn FnMut()>));

            on_ended_closures.push(on_ended_closure);
        }

        Ok(Self::Stream {
            ctx,
            on_ended_closures,
            config,
            buffer_size_frames,
            is_started,
        })
    }
}

impl Stream {
    /// Return the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) used
    /// by this stream.
    pub fn audio_context(&self) -> &AudioContext {
        &self.ctx
    }
}

impl StreamTrait for Stream {
    fn play(&self) -> Result<(), Error> {
        let window = web_sys::window().unwrap();
        match self.ctx.resume() {
            Ok(_) => {
                // Only schedule the initial timeouts once.
                if self
                    .is_started
                    .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
                    .is_err()
                {
                    return Ok(());
                }
                // Begin webaudio playback, initially scheduling the closures to fire on a timeout
                // event. Minimum value as per spec: https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
                let mut offset_ms = 4;
                let time_step_secs =
                    buffer_time_step_secs(self.buffer_size_frames, self.config.sample_rate);
                let time_step_ms = ((time_step_secs * 1_000.0).ceil() as i32).max(1);
                for on_ended_closure in self.on_ended_closures.iter() {
                    window
                        .set_timeout_with_callback_and_timeout_and_arguments_0(
                            on_ended_closure
                                .read()
                                .unwrap()
                                .as_ref()
                                .unwrap()
                                .as_ref()
                                .unchecked_ref(),
                            offset_ms,
                        )
                        .unwrap();
                    offset_ms += time_step_ms;
                }
                Ok(())
            }
            Err(_) => Err(Error::with_message(
                ErrorKind::DeviceNotAvailable,
                "Failed to resume audio context",
            )),
        }
    }

    fn pause(&self) -> Result<(), Error> {
        match self.ctx.suspend() {
            Ok(_) => Ok(()),
            Err(_) => Err(Error::with_message(
                ErrorKind::DeviceNotAvailable,
                "Failed to suspend audio context",
            )),
        }
    }

    fn now(&self) -> StreamInstant {
        StreamInstant::from_secs_f64(self.ctx.current_time())
    }

    fn buffer_size(&self) -> Result<FrameCount, Error> {
        Ok(self.buffer_size_frames as FrameCount)
    }
}

impl Drop for Stream {
    fn drop(&mut self) {
        let _ = self.ctx.close();
    }
}

impl Iterator for Devices {
    type Item = Device;

    fn next(&mut self) -> Option<Self::Item> {
        if self.0 {
            self.0 = false;
            Some(Device)
        } else {
            None
        }
    }
}

fn default_input_device() -> Option<Device> {
    // TODO
    None
}

fn default_output_device() -> Option<Device> {
    if is_webaudio_available() {
        Some(Device)
    } else {
        None
    }
}

// Detects whether the `AudioContext` global variable is available.
fn is_webaudio_available() -> bool {
    js_sys::Reflect::get(&js_sys::global(), &JsValue::from("AudioContext"))
        .unwrap()
        .is_truthy()
}

fn buffer_time_step_secs(buffer_size_frames: usize, sample_rate: SampleRate) -> f64 {
    buffer_size_frames as f64 / sample_rate as f64
}

#[cfg(target_feature = "atomics")]
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_name = AudioBuffer)]
    type ExternalArrayAudioBuffer;

    # [wasm_bindgen(catch, method, structural, js_class = "AudioBuffer", js_name = copyToChannel)]
    pub fn copy_to_channel(
        this: &ExternalArrayAudioBuffer,
        source: &js_sys::Float32Array,
        channel_number: i32,
    ) -> Result<(), JsValue>;
}