wavegraph-audio 0.1.1

Audio device routing and block I/O for WaveGraph
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
561
562
563
564
565
566
567
568
569
570
571
572
//! Desktop audio I/O through CoreAudio, ALSA or WASAPI.
extern crate alloc;

mod pcm;

use self::alloc::{
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};
use crate::{Block, Capture, DeviceHost, Direction, Endpoint, Playback, Submission};
use ::cpal::{
    Device, DeviceDirection, DeviceId, ErrorKind, HostId, SupportedStreamConfig,
    SupportedStreamConfigRange,
    traits::{DeviceTrait, HostTrait},
};
use core::{
    cell::RefCell,
    fmt,
    num::NonZeroU32,
    sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
use std::{collections::HashMap, io};

/// Identity of an endpoint within a host. Display names can collide.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Id(usize);

impl fmt::Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Recording and playback endpoints observed during a scan.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Devices {
    endpoints: Vec<Endpoint<Id, String>>,
    // Parallel to endpoints. Keep the exact native identity and configuration
    // so opening a route never depends on the order of a subsequent scan.
    configs: Vec<(DeviceId, SupportedStreamConfig)>,
    defaults: [Option<Id>; 2],
    /// Current default recording device's display name, when available.
    pub default_input: Option<String>,
    /// Current default playback device's display name, when available.
    pub default_output: Option<String>,
}

struct Selection<'a> {
    id: Id,
    native: &'a DeviceId,
    config: SupportedStreamConfig,
    channels: (usize, usize),
}

impl Devices {
    /// Endpoints in stable instance-ID order, including duplicate display names.
    #[must_use]
    pub fn endpoints(&self) -> &[Endpoint<Id, String>] {
        &self.endpoints
    }

    fn resolve(&self, route: Route, direction: Direction) -> Option<Selection<'_>> {
        let id = match route {
            Route::Default => self.defaults[index(direction)]?,
            Route::Device(id, _) => id,
        };
        let i = self
            .endpoints
            .iter()
            .position(|e| e.id == id && e.direction == direction)?;
        let (native, config) = &self.configs[i];
        let channels = match route {
            Route::Default if config.channels() == 1 => Channels::Mono(0),
            Route::Default => Channels::Pair(0),
            Route::Device(_, channels) => channels,
        };
        Some(Selection {
            id,
            native,
            config: *config,
            channels: channels.indices(config.channels())?,
        })
    }
}

impl AsRef<[Endpoint<Id, String>]> for Devices {
    fn as_ref(&self) -> &[Endpoint<Id, String>] {
        self.endpoints()
    }
}

/// System default or an explicit channel selection on a specific device.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Route {
    /// Follow the system default on subsequent scans.
    Default,
    /// Pin to one device. A missing device or channel leaves the route offline.
    Device(Id, Channels),
}

/// Zero-based channel selection on a physical endpoint.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Channels {
    /// Duplicate mono input to L/R or average L/R into the mono output.
    Mono(u16),
    /// Left channel of an adjacent stereo pair.
    Pair(u16),
}

impl Channels {
    fn indices(self, width: u16) -> Option<(usize, usize)> {
        let (l, r) = match self {
            Self::Mono(i) => (i, i),
            Self::Pair(i) => (i, i.checked_add(1)?),
        };
        (r < width).then_some((usize::from(l), usize::from(r)))
    }
}

fn index(direction: Direction) -> usize {
    match direction {
        Direction::Input => 0,
        Direction::Output => 1,
    }
}

#[derive(Debug)]
struct Known {
    id: Id,
    device: Device,
    configs: [Option<SupportedStreamConfig>; 2],
}

/// Owns the native host and its session-local device identities.
pub struct Host {
    backend: ::cpal::Host,
    known: RefCell<HashMap<DeviceId, Known>>,
}

impl fmt::Debug for Host {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Host").field(&self.backend.id()).finish()
    }
}

impl Host {
    /// Initialize the native desktop audio backend.
    ///
    /// # Errors
    /// Returns backend initialization errors.
    pub fn new() -> io::Result<Self> {
        #[cfg(target_os = "linux")]
        let id = HostId::Alsa;
        #[cfg(target_os = "macos")]
        let id = HostId::CoreAudio;
        #[cfg(windows)]
        let id = HostId::Wasapi;
        Ok(Self {
            backend: ::cpal::host_from_id(id).map_err(io::Error::other)?,
            known: RefCell::default(),
        })
    }

    fn default_device(&self, direction: Direction) -> Option<Device> {
        match direction {
            Direction::Input => self.backend.default_input_device(),
            Direction::Output => self.backend.default_output_device(),
        }
    }
}

impl DeviceHost for Host {
    type Id = Id;
    type Name = String;
    type Devices = Devices;
    type Error = io::Error;

    fn devices(&self) -> io::Result<Devices> {
        static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
        let defaults = [
            self.backend.default_input_device(),
            self.backend.default_output_device(),
        ];
        let default_ids = defaults
            .each_ref()
            .map(|d| d.as_ref().and_then(|d| d.id().ok()));
        let mut snapshot = Devices::default();
        let mut entries = Vec::new();
        let mut previous = self.known.borrow_mut();
        let mut current = HashMap::new();
        // ALSA's synthetic "default" PCM need not appear in the list of hints.
        let devices = self.backend.devices().map_err(io::Error::other)?;
        for device in devices.chain(defaults.into_iter().flatten()) {
            let Ok(native) = device.id() else { continue };
            if current.contains_key(&native) {
                continue;
            }
            let Ok(description) = device.description() else {
                continue;
            };
            let mut known = match previous.remove(&native) {
                Some(known) => Known { device, ..known },
                None => Known {
                    id: Id(NEXT_ID.fetch_add(1, Ordering::Relaxed)),
                    device,
                    configs: [None; 2],
                },
            };
            for direction in [Direction::Input, Direction::Output] {
                let i = index(direction);
                if matches!(
                    (description.direction(), direction),
                    (DeviceDirection::Input, Direction::Output)
                        | (DeviceDirection::Output, Direction::Input)
                ) {
                    known.configs[i] = None;
                    continue;
                }
                // ALSA needs to open a PCM to probe its format. Reuse its last
                // successful probe while attached, including while it is busy.
                let cached = known.configs[i];
                let config = if cfg!(target_os = "linux") && cached.is_some() {
                    cached
                } else {
                    match configuration(&known.device, direction) {
                        Ok(c) if c.channels() > 0 && c.sample_rate() > 0 => Some(c),
                        Err(e) if e.kind() == ErrorKind::DeviceBusy => cached,
                        _ => None,
                    }
                };
                known.configs[i] = config;
                let Some(config) = config else { continue };
                let name = description.name().to_string();
                if default_ids[i].as_ref() == Some(&native) {
                    snapshot.defaults[i] = Some(known.id);
                    match direction {
                        Direction::Input => snapshot.default_input = Some(name.clone()),
                        Direction::Output => snapshot.default_output = Some(name.clone()),
                    }
                }
                entries.push((
                    Endpoint {
                        id: known.id,
                        name,
                        direction,
                        channels: config.channels(),
                        rate: (config.sample_rate(), 1),
                    },
                    (native.clone(), config),
                ));
            }
            current.insert(native, known);
        }
        *previous = current;
        entries.sort_by_key(|(e, _)| (e.id.0, index(e.direction)));
        (snapshot.endpoints, snapshot.configs) = entries.into_iter().unzip();
        Ok(snapshot)
    }
}

fn configuration(
    device: &Device,
    direction: Direction,
) -> Result<SupportedStreamConfig, ::cpal::Error> {
    let default = match direction {
        Direction::Input => device.default_input_config(),
        Direction::Output => device.default_output_config(),
    };
    // CoreAudio may describe just its first stream, or reject its physical
    // sample format even though its Audio Unit accepts multichannel float PCM.
    if cfg!(target_os = "macos") {
        let ranges: Vec<_> = match direction {
            Direction::Input => device.supported_input_configs().map(Iterator::collect),
            Direction::Output => device.supported_output_configs().map(Iterator::collect),
        }
        .unwrap_or_default();
        if let Ok(c) = &default {
            if let Some(wider) = ranges
                .iter()
                .filter(|r| r.channels() > c.channels())
                .filter_map(|r| r.try_with_sample_rate(c.sample_rate()))
                .max_by_key(|c| c.channels())
            {
                return Ok(wider);
            }
        } else if let Some(r) = ranges
            .into_iter()
            .max_by(SupportedStreamConfigRange::cmp_default_heuristics)
        {
            return Ok(r
                .try_with_standard_sample_rate()
                .unwrap_or_else(|| r.with_max_sample_rate()));
        }
    }
    default
}

/// Result of reconciling a selected route with the available devices.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Status {
    /// A new stream is ready, with any old queued PCM discarded.
    Opened,
    /// The current stream can continue.
    Running,
    /// No compatible endpoint is available for the selected route.
    Offline,
}

struct Link<Q> {
    _stream: ::cpal::Stream,
    queue: Q,
    failed: Arc<AtomicBool>,
    route: Route,
    id: Id,
    config: SupportedStreamConfig,
}

struct Port<Q> {
    rate: NonZeroU32,
    link: Option<Link<Q>>,
}

impl<Q> Port<Q> {
    fn sync(
        &mut self,
        host: &Host,
        devices: &Devices,
        route: Route,
        direction: Direction,
        open: impl FnOnce(
            &Device,
            SupportedStreamConfig,
            (usize, usize),
            NonZeroU32,
            Arc<AtomicBool>,
        ) -> io::Result<(::cpal::Stream, Q)>,
    ) -> io::Result<Status> {
        let Some(Selection {
            id,
            native,
            config,
            channels,
        }) = devices.resolve(route, direction)
        else {
            self.link = None;
            return Ok(Status::Offline);
        };
        if self.link.as_ref().is_some_and(|link| {
            link.id == id
                && link.route == route
                && link.config == config
                && !link.failed.load(Ordering::Relaxed)
        }) {
            return Ok(Status::Running);
        }
        self.link = None;
        let device = match route {
            Route::Default => host
                .default_device(direction)
                .filter(|d| d.id().ok().as_ref() == Some(native)),
            Route::Device(_, _) => host
                .known
                .borrow()
                .get(native)
                .filter(|k| k.id == id)
                .map(|k| k.device.clone()),
        };
        let Some(device) = device else {
            return Ok(Status::Offline);
        };
        let failed = Arc::new(AtomicBool::new(false));
        let (stream, queue) = open(&device, config, channels, self.rate, failed.clone())
            .inspect_err(|_| {
                // Permit the next scan to renegotiate if the device's format changed.
                if let Some(k) = host.known.borrow_mut().get_mut(native) {
                    k.configs[index(direction)] = None;
                }
            })?;
        self.link = Some(Link {
            _stream: stream,
            queue,
            failed,
            route,
            id,
            config,
        });
        Ok(Status::Opened)
    }

    fn queue(&mut self) -> io::Result<Option<&mut Q>> {
        if self
            .link
            .as_ref()
            .is_some_and(|link| link.failed.load(Ordering::Relaxed))
        {
            self.link = None;
            return Err(io::Error::other("audio stream stopped"));
        }
        Ok(self.link.as_mut().map(|link| &mut link.queue))
    }
}

/// One graph master routed to a desktop output.
pub struct Output(Port<pcm::OutputQueue>);
/// One independent capture stream. Drop it to stop recording.
pub struct Input(Port<pcm::InputQueue>);

macro_rules! port {
    ($ty:ty, $direction:expr, $open:path) => {
        impl $ty {
            /// Create an offline port at the graph's sample rate.
            #[must_use]
            pub fn new(rate: NonZeroU32) -> Self {
                Self(Port { rate, link: None })
            }

            /// Apply the desired route after a scan or retry a failed open.
            ///
            /// # Errors
            /// Returns stream-open, format or permission errors. The port stays offline.
            pub fn sync(
                &mut self,
                host: &Host,
                devices: &Devices,
                route: Route,
            ) -> io::Result<Status> {
                self.0.sync(host, devices, route, $direction, $open)
            }
        }

        impl fmt::Debug for $ty {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_struct(stringify!($ty))
                    .field("route", &self.0.link.as_ref().map(|l| l.route))
                    .finish()
            }
        }
    };
}
port!(Output, Direction::Output, pcm::open_output);
port!(Input, Direction::Input, pcm::open_input);

impl Playback for Output {
    type Error = io::Error;
    type Timing = ();

    fn render(&mut self, render: impl FnOnce(&mut Block, ())) -> io::Result<Submission> {
        match self.0.queue()? {
            Some(queue) => queue.render(render),
            None => Ok(Submission::WouldBlock),
        }
    }
}

impl Capture for Input {
    type Error = io::Error;

    fn read(&mut self, out: &mut Block) -> io::Result<bool> {
        match self.0.queue()? {
            Some(queue) => queue.read(out),
            None => Ok(false),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::FRAMES;
    use core::time::Duration;
    use std::time::Instant;

    #[test]
    fn pair_must_fit_the_endpoint() {
        assert_eq!(Channels::Pair(2).indices(4), Some((2, 3)));
        assert_eq!(Channels::Pair(3).indices(4), None);
        assert_eq!(Channels::Pair(u16::MAX).indices(4), None);
        assert_eq!(Channels::Mono(0).indices(0), None);
    }

    #[test]
    fn default_moves_by_identity_and_pinned_pair_stays_put() {
        use ::cpal::{SampleFormat, SupportedBufferSize};
        let mut devices = Devices::default();
        let direction = Direction::Output;
        for (n, width) in [(1, 4), (2, 1)] {
            let config = SupportedStreamConfig::new(
                width,
                48_000,
                SupportedBufferSize::Unknown,
                SampleFormat::F32,
            );
            devices.endpoints.push(Endpoint {
                id: Id(n),
                name: "USB Audio".into(),
                direction,
                channels: width,
                rate: (48_000, 1),
            });
            devices
                .configs
                .push((DeviceId::new(::cpal::ALL_HOSTS[0], n.to_string()), config));
        }
        devices.defaults[index(direction)] = Some(Id(1));
        let first = devices
            .resolve(Route::Default, direction)
            .expect("first output");
        assert_eq!((first.id, first.channels), (Id(1), (0, 1)));
        devices.defaults[index(direction)] = Some(Id(2));
        let second = devices
            .resolve(Route::Default, direction)
            .expect("mono output");
        assert_eq!((second.id, second.channels), (Id(2), (0, 0)));
        let pinned = Route::Device(Id(1), Channels::Pair(2));
        assert_eq!(
            devices
                .resolve(pinned, direction)
                .expect("pinned pair")
                .channels,
            (2, 3)
        );
        assert!(devices.resolve(pinned, Direction::Input).is_none());
    }

    #[test]
    #[ignore = "requires a virtual default recording and playback device"]
    fn duplex_and_route_removal() -> io::Result<()> {
        let host = Host::new()?;
        let devices = host.devices()?;
        let rate = NonZeroU32::new(44_100).expect("positive rate");
        let mut output = Output::new(rate);
        let mut input = Input::new(rate);
        let id = devices.defaults[index(Direction::Output)].expect("virtual default output");
        let route = Route::Device(id, Channels::Mono(0));
        assert_eq!(output.sync(&host, &devices, route)?, Status::Opened);
        assert_eq!(
            output.sync(&host, &host.devices()?, route)?,
            Status::Running
        );
        assert_eq!(
            output.render(|block, ()| block.fill([42; 2]))?,
            Submission::Written
        );
        assert_eq!(
            output.sync(&host, &Devices::default(), route)?,
            Status::Offline
        );
        assert_eq!(
            output.render(|_, ()| unreachable!())?,
            Submission::WouldBlock
        );
        assert_eq!(
            output.sync(&host, &devices, Route::Default)?,
            Status::Opened
        );
        assert_eq!(input.sync(&host, &devices, Route::Default)?, Status::Opened);
        let mut block = [[42; 2]; FRAMES];
        let start = Instant::now();
        while !input.read(&mut block)? {
            assert_eq!(block, [[42; 2]; FRAMES]);
            assert!(start.elapsed() < Duration::from_secs(5));
            std::thread::sleep(Duration::from_millis(1));
        }
        assert_eq!(
            input.sync(&host, &Devices::default(), Route::Default)?,
            Status::Offline
        );
        assert!(!input.read(&mut block)?);
        Ok(())
    }
}