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
//! Device callbacks move interleaved PCM through a bounded SPSC queue. Rate conversion
//! and graph rendering both run on the application's side of that queue.

extern crate alloc;

use self::alloc::{sync::Arc, vec, vec::Vec};
use crate::{Block, FRAMES, Submission};
use ::cpal::{
    BufferSize, Device, ErrorKind, FromSample, Sample, SampleFormat, SizedSample, Stream,
    StreamConfig, SupportedBufferSize, SupportedStreamConfig,
    traits::{DeviceTrait as _, StreamTrait as _},
};
use core::{
    num::NonZeroU32,
    sync::atomic::{AtomicBool, Ordering},
};
use rtrb::{Consumer, Producer, RingBuffer};
use rubato::{Async, FixedAsync, Resampler, audioadapter_buffers::direct::InterleavedSlice};
use std::io;

type Frame = [i32; 2];
const MIN_Q23: i32 = -(1 << 23);
const MAX_Q23: i32 = (1 << 23) - 1;
// Two periods of this size occupy 1 MiB of stereo queue storage.
const MAX_PERIOD: u32 = 65_536;

fn alsa_period(size: SupportedBufferSize) -> io::Result<u32> {
    // ALSA's default period can be u32::MAX on an unconstrained virtual PCM.
    match size {
        SupportedBufferSize::Unknown => Ok(256),
        SupportedBufferSize::Range { min, max } => {
            let min = min.max(1);
            let max = max.min(MAX_PERIOD);
            if min > max {
                return Err(io::Error::new(
                    io::ErrorKind::Unsupported,
                    "no supported ALSA period within 1..=65536 frames",
                ));
            }
            Ok(256_u32.clamp(min, max))
        }
    }
}

// CPAL reports the negotiated period only after the stream has been built. Transfer
// the sized queue endpoint to the callback once, before starting the stream.
struct Handoff<Q> {
    initial: Consumer<Q>,
    active: Option<Q>,
}

impl<Q> Handoff<Q> {
    fn new() -> (impl FnOnce(Q), Self) {
        let (mut send, initial) = RingBuffer::new(1);
        (
            move |queue| assert!(send.push(queue).is_ok(), "one writer, one unused slot"),
            Self {
                initial,
                active: None,
            },
        )
    }

    fn get(&mut self) -> Option<&mut Q> {
        if self.active.is_none() {
            self.active = self.initial.pop().ok();
        }
        self.active.as_mut()
    }
}

enum Callback {
    Output(Handoff<Consumer<Frame>>),
    Input(Handoff<Producer<Frame>>),
}

impl Callback {
    fn build(
        self,
        device: &Device,
        config: &SupportedStreamConfig,
        channels: (usize, usize),
        failed: Arc<AtomicBool>,
    ) -> io::Result<Stream> {
        let mut stream_config = config.config();
        if cfg!(target_os = "linux") {
            stream_config.buffer_size = BufferSize::Fixed(alsa_period(*config.buffer_size())?);
        }
        macro_rules! build {
            ($sample:ty) => {
                self.build_typed::<$sample>(device, stream_config, channels, failed)
            };
        }
        match config.sample_format() {
            SampleFormat::I8 => build!(i8),
            SampleFormat::I16 => build!(i16),
            SampleFormat::I24 => build!(::cpal::I24),
            SampleFormat::I32 => build!(i32),
            SampleFormat::I64 => build!(i64),
            SampleFormat::U8 => build!(u8),
            SampleFormat::U16 => build!(u16),
            SampleFormat::U24 => build!(::cpal::U24),
            SampleFormat::U32 => build!(u32),
            SampleFormat::U64 => build!(u64),
            SampleFormat::F32 => build!(f32),
            SampleFormat::F64 => build!(f64),
            _ => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "unsupported device sample format",
            )),
        }
    }

    fn build_typed<T>(
        self,
        device: &Device,
        config: StreamConfig,
        channels: (usize, usize),
        failed: Arc<AtomicBool>,
    ) -> io::Result<Stream>
    where
        T: SizedSample + FromSample<i32>,
        i32: FromSample<T>,
    {
        let width = usize::from(config.channels);
        let on_error = move |error: ::cpal::Error| {
            if !matches!(
                error.kind(),
                ErrorKind::Xrun | ErrorKind::DeviceChanged | ErrorKind::RealtimeDenied
            ) {
                failed.store(true, Ordering::Relaxed);
            }
        };
        match self {
            Self::Output(mut handoff) => device.build_output_stream(
                config,
                move |data: &mut [T], _| {
                    write_output(handoff.get(), data, width, channels);
                },
                on_error,
                None,
            ),
            Self::Input(mut handoff) => device.build_input_stream(
                config,
                move |data: &[T], _| {
                    if let Some(sink) = handoff.get() {
                        read_input(sink, data, width, channels);
                    }
                },
                on_error,
                None,
            ),
        }
        .map_err(io::Error::other)
    }
}

// Unrouted channels and underrun frames use digital silence, including unsigned PCM.
fn write_output<T: Sample + FromSample<i32>>(
    source: Option<&mut Consumer<Frame>>,
    data: &mut [T],
    width: usize,
    (left, right): (usize, usize),
) {
    data.fill(T::EQUILIBRIUM);
    let Some(source) = source else { return };
    let frames = data.chunks_exact_mut(width);
    let available = frames.len().min(source.slots());
    let chunk = source
        .read_chunk(available)
        .expect("single consumer owns the available frames");
    let encode = |sample: i32| T::from_sample(sample.clamp(MIN_Q23, MAX_Q23) << 8);
    for (out, [l, r]) in frames.zip(chunk) {
        if left == right {
            out[left] = encode(l.midpoint(r));
        } else {
            out[left] = encode(l);
            out[right] = encode(r);
        }
    }
}

fn read_input<T: Sample>(
    sink: &mut Producer<Frame>,
    data: &[T],
    width: usize,
    (left, right): (usize, usize),
) where
    i32: FromSample<T>,
{
    let frames = data.chunks_exact(width);
    let available = frames.len().min(sink.slots());
    let chunk = sink
        .write_chunk_uninit(available)
        .expect("single producer owns the free slots");
    chunk.fill_from_iter(
        frames.map(|frame| [frame[left], frame[right]].map(|sample| i32::from_sample(sample) >> 8)),
    );
}

struct Converter {
    sinc: Async<f32>,
    input: Vec<[f32; 2]>,
    output: Vec<[f32; 2]>,
}

impl Converter {
    fn new(input_rate: u32, output_rate: u32, fixed: FixedAsync) -> io::Result<Option<Self>> {
        if input_rate == output_rate {
            return Ok(None);
        }
        let ratio = f64::from(output_rate) / f64::from(input_rate);
        // Bound rubato's own allocations before construction. A 256:1 range covers
        // conversions between 8 kHz telephony and 1.536 MHz audio in both directions.
        if !(1.0 / 256.0..=256.0).contains(&ratio) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "sample-rate conversion ratio exceeds 256:1",
            ));
        }
        let sinc = Async::new_sinc(ratio, 1.0, &Default::default(), FRAMES, 2, fixed)
            .map_err(io::Error::other)?;
        let input = vec![[0.; 2]; sinc.input_frames_max()];
        let output = vec![[0.; 2]; sinc.output_frames_max()];
        Ok(Some(Self {
            sinc,
            input,
            output,
        }))
    }

    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        reason = "f32 represents Q23 exactly. Filtered samples round back to signed PCM."
    )]
    fn process(
        &mut self,
        frames: impl IntoIterator<Item = Frame>,
    ) -> io::Result<impl Iterator<Item = Frame> + '_> {
        for (dest, frame) in self.input.iter_mut().zip(frames) {
            *dest = frame.map(|s| s as f32);
        }
        let input = InterleavedSlice::new(self.input.as_flattened(), 2, self.input.len())
            .map_err(io::Error::other)?;
        let capacity = self.output.len();
        let mut output = InterleavedSlice::new_mut(self.output.as_flattened_mut(), 2, capacity)
            .map_err(io::Error::other)?;
        let (_, written) = self
            .sinc
            .process_into_buffer(&input, &mut output, None)
            .map_err(io::Error::other)?;
        Ok(self.output[..written]
            .iter()
            .map(|frame| frame.map(|s| s.round() as i32)))
    }
}

pub(super) struct OutputQueue {
    queue: Producer<Frame>,
    converter: Option<Converter>,
}

impl OutputQueue {
    pub(super) fn render(&mut self, render: impl FnOnce(&mut Block, ())) -> io::Result<Submission> {
        let frames = self
            .converter
            .as_ref()
            .map_or(FRAMES, |c| c.sinc.output_frames_next());
        let Ok(chunk) = self.queue.write_chunk_uninit(frames) else {
            return Ok(Submission::WouldBlock);
        };
        let mut block = [[0; 2]; FRAMES];
        render(&mut block, ());
        if let Some(converter) = &mut self.converter {
            chunk.fill_from_iter(converter.process(block)?);
        } else {
            chunk.fill_from_iter(block);
        }
        Ok(Submission::Written)
    }
}

pub(super) struct InputQueue {
    queue: Consumer<Frame>,
    converter: Option<Converter>,
}

impl InputQueue {
    pub(super) fn read(&mut self, block: &mut Block) -> io::Result<bool> {
        let Some(converter) = &mut self.converter else {
            return Ok(self.queue.pop_entire_slice(block).is_ok());
        };
        let Ok(chunk) = self.queue.read_chunk(converter.sinc.input_frames_next()) else {
            return Ok(false);
        };
        for (dest, frame) in block.iter_mut().zip(converter.process(chunk)?) {
            *dest = frame.map(|s| s.clamp(MIN_Q23, MAX_Q23));
        }
        Ok(true)
    }
}

fn queue_capacity(period: u32, block: usize) -> io::Result<usize> {
    if !(1..=MAX_PERIOD).contains(&period) {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "device period outside 1..=65536 frames",
        ));
    }
    let period = usize::try_from(period).map_err(io::Error::other)?;
    Ok(period.saturating_mul(2).max(block.saturating_mul(4)))
}

pub(super) fn open_output(
    device: &Device,
    config: SupportedStreamConfig,
    channels: (usize, usize),
    rate: NonZeroU32,
    failed: Arc<AtomicBool>,
) -> io::Result<(Stream, OutputQueue)> {
    let converter = Converter::new(rate.get(), config.sample_rate(), FixedAsync::Input)?;
    let (init, handoff) = Handoff::new();
    let stream = Callback::Output(handoff).build(device, &config, channels, failed)?;
    let block = converter
        .as_ref()
        .map_or(FRAMES, |c| c.sinc.output_frames_max());
    let (queue, consumer) =
        RingBuffer::new(queue_capacity(stream.buffer_size().unwrap_or(512), block)?);
    init(consumer);
    stream.play().map_err(io::Error::other)?;
    Ok((stream, OutputQueue { queue, converter }))
}

pub(super) fn open_input(
    device: &Device,
    config: SupportedStreamConfig,
    channels: (usize, usize),
    rate: NonZeroU32,
    failed: Arc<AtomicBool>,
) -> io::Result<(Stream, InputQueue)> {
    let converter = Converter::new(config.sample_rate(), rate.get(), FixedAsync::Output)?;
    let (init, handoff) = Handoff::new();
    let stream = Callback::Input(handoff).build(device, &config, channels, failed)?;
    let block = converter
        .as_ref()
        .map_or(FRAMES, |c| c.sinc.input_frames_max());
    let (producer, queue) =
        RingBuffer::new(queue_capacity(stream.buffer_size().unwrap_or(512), block)?);
    init(producer);
    stream.play().map_err(io::Error::other)?;
    Ok((stream, InputQueue { queue, converter }))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bound_alsa_requests_and_negotiated_periods() -> io::Result<()> {
        use SupportedBufferSize::{Range, Unknown};
        assert_eq!(alsa_period(Unknown)?, 256);
        assert_eq!(
            alsa_period(Range {
                min: 0,
                max: u32::MAX
            })?,
            256
        );
        assert_eq!(alsa_period(Range { min: 8, max: 64 })?, 64);
        assert_eq!(
            alsa_period(Range {
                min: 1024,
                max: u32::MAX
            })?,
            1024
        );
        assert!(
            alsa_period(Range {
                min: u32::MAX,
                max: u32::MAX
            })
            .is_err()
        );
        assert!(alsa_period(Range { min: 32, max: 16 }).is_err());
        assert!(queue_capacity(0, FRAMES).is_err());
        assert!(queue_capacity(u32::MAX, FRAMES).is_err());
        assert_eq!(queue_capacity(8192, FRAMES)?, 16_384);
        Ok(())
    }

    #[test]
    fn reject_extreme_resampling_ratios_before_constructing_the_filter() -> io::Result<()> {
        assert!(Converter::new(1, 192_000, FixedAsync::Input).is_err());
        assert!(Converter::new(44_100, u32::MAX, FixedAsync::Output).is_err());
        assert!(Converter::new(1_536_000, 8000, FixedAsync::Output)?.is_some());
        Ok(())
    }

    #[test]
    fn map_and_clip_only_the_selected_channels() {
        let (mut send, mut recv) = RingBuffer::new(5);
        send.push_entire_slice(&[[i32::MIN, i32::MAX], [-1, 1]])
            .expect("space");
        let mut device = [42_i32; 12];
        write_output(Some(&mut recv), &mut device, 4, (2, 3));
        assert_eq!(
            device,
            [0, 0, i32::MIN, MAX_Q23 << 8, 0, 0, -256, 256, 0, 0, 0, 0]
        );
        read_input(&mut send, &device, 4, (2, 3));
        assert_eq!(recv.pop(), Ok([MIN_Q23, MAX_Q23]));
        assert_eq!(recv.pop(), Ok([-1, 1]));
        assert_eq!(recv.pop(), Ok([0, 0]));

        send.push([12_000_000, -4_000_000]).expect("space");
        let mut mono = [0_u32; 4];
        write_output(Some(&mut recv), &mut mono, 2, (1, 1));
        assert_eq!(
            mono,
            [
                u32::EQUILIBRIUM,
                u32::from_sample(4_000_000 << 8),
                u32::EQUILIBRIUM,
                u32::EQUILIBRIUM
            ]
        );
        read_input(&mut send, &mono, 2, (1, 1));
        assert_eq!(recv.pop(), Ok([4_000_000; 2]));
        assert_eq!(recv.pop(), Ok([0; 2]));
    }

    #[test]
    fn callbacks_of_different_lengths_preserve_whole_graph_blocks() -> io::Result<()> {
        let (send, mut recv) = RingBuffer::new(FRAMES);
        let mut out = OutputQueue {
            queue: send,
            converter: None,
        };
        assert_eq!(
            out.render(|block, ()| {
                assert_eq!(*block, [[0; 2]; FRAMES]);
                for (index, frame) in (1..).zip(block) {
                    *frame = [index, -index];
                }
            })?,
            Submission::Written
        );
        let mut part = [1_f32; 6];
        write_output(Some(&mut recv), &mut part, 2, (0, 1));
        assert_eq!(part[0], f32::from_sample(1 << 8));
        assert_eq!(out.render(|_, ()| unreachable!())?, Submission::WouldBlock);
        let mut tail = [1_f32; 256];
        write_output(Some(&mut recv), &mut tail, 2, (0, 1));
        assert_eq!(tail[0], f32::from_sample(4 << 8));
        assert_eq!(tail[249], f32::from_sample(-128 << 8));
        assert_eq!(tail[250..], [0.; 6]);

        let (mut send, recv) = RingBuffer::new(FRAMES);
        let mut input = InputQueue {
            queue: recv,
            converter: None,
        };
        let mut block = [[42; 2]; FRAMES];
        read_input(&mut send, &[0.5_f32; 3], 1, (0, 0));
        assert!(!input.read(&mut block)?);
        assert_eq!(block, [[42; 2]; FRAMES]);
        read_input(&mut send, &[-0.25_f32; 220], 1, (0, 0));
        assert!(input.read(&mut block)?);
        assert_eq!(block[..3], [[1 << 22; 2]; 3]);
        assert_eq!(block[3..], [[-(1 << 21); 2]; 125]);
        assert!(!input.read(&mut block)?);
        Ok(())
    }

    #[test]
    fn sinc_conversion_preserves_stereo_and_the_graph_clock() -> io::Result<()> {
        let (send, recv) = RingBuffer::new(12 * FRAMES);
        let mut output = OutputQueue {
            queue: send,
            converter: Converter::new(44_100, 48_000, FixedAsync::Input)?,
        };
        let mut input = InputQueue {
            queue: recv,
            converter: Converter::new(48_000, 44_100, FixedAsync::Output)?,
        };
        let mut captured = [[0; 2]; FRAMES];
        let mut read = 0;
        let mut device_frames = 0;
        // Warm the filters, then measure 147 graph blocks (exactly 160 device blocks).
        for block in 0..151 {
            let before = input.queue.slots();
            assert_eq!(
                output.render(|b, ()| b.fill([1 << 20, -(1 << 21)]))?,
                Submission::Written
            );
            if block >= 4 {
                device_frames += input.queue.slots() - before;
            }
            while input.read(&mut captured)? {
                read += 1;
            }
        }
        assert!(device_frames.abs_diff(160 * FRAMES) <= 1);
        assert!((148..=151).contains(&read));
        for [left, right] in captured {
            assert!(left.abs_diff(1 << 20) < 32);
            assert!(right.abs_diff(-(1 << 21)) < 64);
        }
        Ok(())
    }
}