cpal 0.18.1

Low-level cross-platform audio I/O library.
Documentation
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
//! Audio Worklet backend implementation.
//!
//! Available on WebAssembly with the `audioworklet` feature. Requires atomics support.
//! See the `audioworklet-beep` example for setup instructions.

use std::{
    fmt,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
    time::Duration,
};

use js_sys::wasm_bindgen;
use wasm_bindgen::prelude::*;

use crate::{
    host::frames_to_duration,
    traits::{DeviceTrait, HostTrait, StreamTrait},
    BufferSize, ChannelCount, Data, DeviceDescription, DeviceDescriptionBuilder, DeviceDirection,
    DeviceId, Error, ErrorKind, FrameCount, InputCallbackInfo, OutputCallbackInfo,
    OutputStreamTimestamp, SampleFormat, SampleRate, StreamConfig, StreamInstant,
    SupportedBufferSize, SupportedStreamConfig, SupportedStreamConfigRange,
};

mod dependent_module;
use crate::dependent_module;

/// 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 {
    audio_context: web_sys::AudioContext,
    buffer_size_frames: Arc<AtomicU64>,
}

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

// https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-audioworkletnode
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;

// https://webaudio.github.io/web-audio-api/#render-quantum-size
const DEFAULT_RENDER_SIZE: u64 = 128;

fn render_quantum_size_supported() -> bool {
    (|| -> Option<bool> {
        let global = js_sys::global();
        let ctor = js_sys::Reflect::get(&global, &JsValue::from("AudioContext")).ok()?;
        let proto = js_sys::Reflect::get(&ctor, &JsValue::from("prototype")).ok()?;
        js_sys::Reflect::has(&proto, &JsValue::from("renderQuantumSize")).ok()
    })()
    .unwrap_or(false)
}

fn supported_render_quantum_range(sample_rate: SampleRate) -> SupportedBufferSize {
    // https://webaudio.github.io/web-audio-api/#supported-render-quantum-sizes
    if render_quantum_size_supported() {
        SupportedBufferSize::Range {
            min: 1,
            max: sample_rate.saturating_mul(6),
        }
    } else {
        SupportedBufferSize::Range {
            min: DEFAULT_RENDER_SIZE as FrameCount,
            max: DEFAULT_RENDER_SIZE as FrameCount,
        }
    }
}

impl Host {
    pub fn new() -> Result<Self, Error> {
        if Self::is_available() {
            Ok(Host)
        } else {
            Err(Error::with_message(
                ErrorKind::HostUnavailable,
                "AudioWorklet is not available",
            ))
        }
    }
}

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

    fn is_available() -> bool {
        if let Some(window) = web_sys::window() {
            let has_audio_worklet =
                js_sys::Reflect::has(&window, &JsValue::from_str("AudioWorklet")).unwrap_or(false);

            let cross_origin_isolated =
                js_sys::Reflect::get(&window, &JsValue::from_str("crossOriginIsolated"))
                    .ok()
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);

            has_audio_worklet && cross_origin_isolated
        } else {
            false
        }
    }

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

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

    fn default_output_device(&self) -> Option<Self::Device> {
        if Self::is_available() {
            Some(Device)
        } else {
            None
        }
    }
}

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

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

    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::AudioWorklet,
            "default",
        ))
    }

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

    fn supported_output_configs(&self) -> Result<Self::SupportedOutputConfigs, Error> {
        // In actuality the number of supported channels cannot be fully known until
        // the browser attempts to initialized the AudioWorklet.

        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: supported_render_quantum_range(rate),
                        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)
    }

    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.
    ///
    /// # Async completion
    ///
    /// This function returns `Ok` synchronously once the [`AudioContext`] is created, before the
    /// AudioWorklet module has been loaded or the [`AudioWorkletNode`] has been initialized. The
    /// actual worklet setup runs asynchronously via [`wasm_bindgen_futures::spawn_local`]. If
    /// setup fails (e.g. `add_module` or `AudioWorkletNode` construction throws), the error is
    /// delivered to `error_callback` after the caller already holds a [`Stream`]. There is no
    /// way to surface such errors synchronously given the Web Audio API's design.
    ///
    /// [`AudioContext`]: web_sys::AudioContext
    /// [`AudioWorkletNode`]: web_sys::AudioWorkletNode
    fn build_output_stream_raw<D, E>(
        &self,
        config: StreamConfig,
        sample_format: SampleFormat,
        mut data_callback: D,
        mut 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
                ),
            ));
        }

        if let BufferSize::Fixed(n) = config.buffer_size {
            if let SupportedBufferSize::Range { min, max } =
                supported_render_quantum_range(config.sample_rate)
            {
                if !(min..=max).contains(&n) {
                    return Err(Error::with_message(
                        ErrorKind::UnsupportedConfig,
                        format!(
                            "Buffer size {n} is not in the supported render quantum range {min}..={max}"
                        ),
                    ));
                }
            }
        }

        let stream_opts = web_sys::AudioContextOptions::new();
        stream_opts.set_sample_rate(config.sample_rate as f32);
        if let BufferSize::Fixed(n) = config.buffer_size {
            let _ = js_sys::Reflect::set(
                stream_opts.as_ref(),
                &JsValue::from_str("renderSizeHint"),
                &JsValue::from_f64(n as f64),
            );
        }

        let audio_context =
            web_sys::AudioContext::new_with_context_options(&stream_opts).map_err(|_| {
                Error::with_message(
                    ErrorKind::UnsupportedConfig,
                    "Failed to create audio context",
                )
            })?;

        let destination = audio_context.destination();

        // Chrome rounds renderSizeHint to a power of two; read back the actual quantum.
        let actual_render_quantum =
            js_sys::Reflect::get(audio_context.as_ref(), &JsValue::from("renderQuantumSize"))
                .ok()
                .and_then(|v| v.as_f64())
                .map(|v| v as u64);

        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);

        let initial_quantum = actual_render_quantum.unwrap_or(match config.buffer_size {
            BufferSize::Fixed(n) => n as u64,
            BufferSize::Default => DEFAULT_RENDER_SIZE,
        });
        let buffer_size_frames = Arc::new(AtomicU64::new(initial_quantum));
        let buffer_size_frames_cb = buffer_size_frames.clone();
        let ctx = audio_context.clone();
        wasm_bindgen_futures::spawn_local(async move {
            let result: Result<(), JsValue> = async move {
                let mod_url = dependent_module!("worklet.js")?;
                wasm_bindgen_futures::JsFuture::from(ctx.audio_worklet()?.add_module(&mod_url)?)
                    .await?;

                let options = web_sys::AudioWorkletNodeOptions::new();

                let js_array = js_sys::Array::new();
                js_array.push(&JsValue::from_f64(destination.channel_count() as _));

                options.set_output_channel_count(&js_array);
                options.set_number_of_inputs(0);

                // Capture audio output latency here: the closure runs in a separate worker and cannot access AudioContext properties directly.
                // While baseLatency is fixed for the context lifetime, outputLatency can change but not be re-read from inside the worklet;
                // we snapshot it here.
                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);
                let output_latency_secs =
                    js_sys::Reflect::get(ctx.as_ref(), &JsValue::from("outputLatency"))
                        .ok()
                        .and_then(|v| v.as_f64())
                        .unwrap_or(0.0);
                let total_output_latency_secs = {
                    let sum = base_latency_secs + output_latency_secs;
                    if sum.is_finite() {
                        sum.max(0.0)
                    } else {
                        0.0
                    }
                };

                options.set_processor_options(Some(&js_sys::Array::of3(
                    &wasm_bindgen::module(),
                    &wasm_bindgen::memory(),
                    &WasmAudioProcessor::new(Box::new(
                        move |interleaved_data, frame_size, sample_rate, now| {
                            buffer_size_frames_cb.store(frame_size as u64, Ordering::Relaxed);
                            let data = interleaved_data.as_mut_ptr() as *mut ();
                            let mut data = unsafe {
                                Data::from_parts(data, interleaved_data.len(), sample_format)
                            };

                            let callback = StreamInstant::from_secs_f64(now);
                            let buffer_duration =
                                frames_to_duration(frame_size as FrameCount, sample_rate);
                            let playback = callback
                                + (buffer_duration
                                    + Duration::from_secs_f64(total_output_latency_secs));
                            let timestamp = OutputStreamTimestamp { callback, playback };
                            let info = OutputCallbackInfo { timestamp };
                            (data_callback)(&mut data, &info);
                        },
                    ))
                    .pack()
                    .into(),
                )));
                // This name 'CpalProcessor' must match the name registered in worklet.js
                let audio_worklet_node =
                    web_sys::AudioWorkletNode::new_with_options(&ctx, "CpalProcessor", &options)?;

                audio_worklet_node.connect_with_audio_node(&destination)?;
                Ok(())
            }
            .await;

            if let Err(err) = result {
                let message = err
                    .as_string()
                    .unwrap_or_else(|| "Failed to initialize audio worklet".to_string());
                error_callback(Error::with_message(
                    ErrorKind::UnsupportedOperation,
                    message,
                ))
            }
        });

        Ok(Self::Stream {
            audio_context,
            buffer_size_frames,
        })
    }
}

impl StreamTrait for Stream {
    fn buffer_size(&self) -> Result<FrameCount, Error> {
        Ok(self.buffer_size_frames.load(Ordering::Relaxed) as FrameCount)
    }

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

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

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

impl Drop for Stream {
    fn drop(&mut self) {
        let _ = self.audio_context.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
        }
    }
}

type AudioProcessorCallback = Box<dyn FnMut(&mut [f32], u32, u32, f64)>;

/// WasmAudioProcessor provides an interface for the Javascript code
/// running in the AudioWorklet to interact with Rust.
#[wasm_bindgen]
pub struct WasmAudioProcessor {
    interleaved_buffer: Vec<f32>,
    // Passes in an interleaved scratch buffer, frame size, sample rate, and current time.
    callback: AudioProcessorCallback,
}

impl WasmAudioProcessor {
    pub fn new(callback: AudioProcessorCallback) -> Self {
        Self {
            interleaved_buffer: Vec::new(),
            callback,
        }
    }
}

#[wasm_bindgen]
impl WasmAudioProcessor {
    pub fn process(
        &mut self,
        channels: u32,
        frame_size: u32,
        sample_rate: u32,
        current_time: f64,
    ) -> u32 {
        let frame_size = frame_size as usize;

        // Ensure there's enough space in the output buffer
        // This likely only occurs once, or very few times.
        let interleaved_buffer_size = channels as usize * frame_size;
        self.interleaved_buffer.resize(
            interleaved_buffer_size.max(self.interleaved_buffer.len()),
            0.0,
        );

        (self.callback)(
            &mut self.interleaved_buffer[..interleaved_buffer_size],
            frame_size as u32,
            sample_rate,
            current_time,
        );

        // Returns a pointer to the raw interleaved buffer to Javascript so
        // it can deinterleave it into the output buffers.
        //
        // Deinterleaving is done on the Javascript side because it's simpler and it may be faster.
        // Doing it this way avoids an extra copy and the JS deinterleaving code
        // is likely heavily optimized by the browser's JS engine,
        // although I have not tested that assumption.
        self.interleaved_buffer.as_mut_ptr() as _
    }

    /// Converts this `WasmAudioProcessor` into a raw pointer (as `usize`) for FFI use.
    ///
    /// Transfers ownership of the processor to the caller. The returned pointer must be passed to
    /// [`unpack`] exactly once. Failing to call [`unpack`] will leak the allocation.
    ///
    /// [`unpack`]: Self::unpack
    pub fn pack(self) -> usize {
        Box::into_raw(Box::new(self)) as usize
    }
    /// # Safety
    ///
    /// The `val` parameter must be a value previously returned by `Self::pack`.
    /// It must not have already been unpacked or deallocated, and must not be used after this call.
    /// Using an invalid or already-consumed pointer will result in undefined behavior.
    pub unsafe fn unpack(val: usize) -> Self {
        *Box::from_raw(val as *mut _)
    }
}