Skip to main content

audio/
system.rs

1use crate::{Configuration, SampleFormat};
2use core::{
3    cell::UnsafeCell,
4    marker::PhantomPinned,
5    ops::{Deref, DerefMut},
6    pin::Pin,
7};
8use file_system::{IoErrorKind, Result};
9use nanoaudio::{Consumer, Mixer, Producer, RingBuffer, Volume};
10use portable_atomic::{AtomicBool, AtomicUsize, Ordering};
11
12const MIX_CONFIGURATION: Configuration = Configuration::new(48_000, 2, SampleFormat::F32);
13const FRAME_BYTES: usize = 2 * size_of::<f32>();
14
15// Contention is reported immediately; audio work never waits for another caller.
16struct TryMutex<T> {
17    locked: AtomicBool,
18    value: UnsafeCell<T>,
19}
20
21// SAFETY: access to value requires the unique guard acquired with the atomic
22// flag; Release on drop pairs with Acquire on the next successful attempt.
23unsafe impl<T: Send> Sync for TryMutex<T> {}
24
25impl<T> TryMutex<T> {
26    fn new(value: T) -> Self {
27        Self {
28            locked: AtomicBool::new(false),
29            value: UnsafeCell::new(value),
30        }
31    }
32
33    fn lock(&self) -> Result<Guard<'_, T>> {
34        self.locked
35            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
36            .map_err(|_| IoErrorKind::WouldBlock)?;
37        Ok(Guard(self))
38    }
39}
40
41struct Guard<'a, T>(&'a TryMutex<T>);
42impl<T> Deref for Guard<'_, T> {
43    type Target = T;
44    fn deref(&self) -> &T {
45        // SAFETY: this guard exclusively owns the lock until drop.
46        unsafe { &*self.0.value.get() }
47    }
48}
49impl<T> DerefMut for Guard<'_, T> {
50    fn deref_mut(&mut self) -> &mut T {
51        // SAFETY: this guard exclusively owns the lock until drop.
52        unsafe { &mut *self.0.value.get() }
53    }
54}
55impl<T> Drop for Guard<'_, T> {
56    fn drop(&mut self) {
57        self.0.locked.store(false, Ordering::Release);
58    }
59}
60
61struct Stream<const N: usize> {
62    bytes: [u8; N],
63    read: usize,
64    length: usize,
65    started: bool,
66}
67impl<const N: usize> Stream<N> {
68    fn new() -> Self {
69        Self {
70            bytes: [0; N],
71            read: 0,
72            length: 0,
73            started: false,
74        }
75    }
76}
77
78struct OutputSlot<const N: usize> {
79    ring: UnsafeCell<RingBuffer<N>>,
80    dropped_blocks: AtomicUsize,
81    occupied: AtomicBool,
82}
83// SAFETY: splitting is serialized by `streams` and only allowed after the previous
84// consumer has been dropped. While occupied, only the SPSC halves touch the ring.
85unsafe impl<const N: usize> Sync for OutputSlot<N> {}
86
87/// A fixed pool of independent 48 kHz stereo interleaved F32 streams and outputs.
88///
89/// Defaults reserve 8 KiB for application PCM and 6 KiB for output PCM. The
90/// fifth generic is bytes per sink (3072 = three 128-frame stereo F32 blocks).
91/// Queue sizes must be frame-aligned; each output must hold a whole mix block.
92/// Pin the system before registering outputs or mixing, using `core::pin::pin!`
93/// for local storage or `alloc::boxed::Box::pin` for an owned platform service.
94///
95/// All storage is inline. Writes, controls, registration and mixing return
96/// [`IoErrorKind::WouldBlock`] immediately on contention; no operation waits or spins.
97/// Output consumption never takes the core lock.
98///
99/// ```compile_fail
100/// use audio::AudioSystem;
101/// let mut system: AudioSystem = AudioSystem::new().unwrap();
102/// // A registered queue may not move, even when its handle is forgotten.
103/// let pinned = core::pin::Pin::new(&mut system);
104/// ```
105pub struct AudioSystem<
106    const STREAMS: usize = 4,
107    const STREAM_BYTES: usize = 2048,
108    const MIX_FRAMES: usize = 128,
109    const OUTPUTS: usize = 2,
110    const SINK_BYTES: usize = 3072,
111> {
112    _pinned: PhantomPinned,
113    occupied: [AtomicBool; STREAMS],
114    streams: TryMutex<Core<STREAMS, STREAM_BYTES, OUTPUTS, SINK_BYTES>>,
115    outputs: [OutputSlot<SINK_BYTES>; OUTPUTS],
116}
117
118struct Core<const S: usize, const B: usize, const O: usize, const Q: usize> {
119    streams: [Stream<B>; S],
120    producers: [Option<Producer<'static, Q>>; O],
121    mixer: Mixer<S>,
122}
123
124impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize>
125    AudioSystem<S, B, F, O, Q>
126{
127    /// Creates empty, paused 48 kHz stereo F32 streams without allocation.
128    /// Invalid const capacities return `InvalidArgument`.
129    pub fn new() -> Result<Self> {
130        let block_bytes = F
131            .checked_mul(FRAME_BYTES)
132            .ok_or(IoErrorKind::InvalidArgument)?;
133        if B == 0
134            || !B.is_multiple_of(FRAME_BYTES)
135            || F == 0
136            || Q < block_bytes
137            || !Q.is_multiple_of(FRAME_BYTES)
138        {
139            return Err(IoErrorKind::InvalidArgument);
140        }
141        Ok(Self {
142            _pinned: PhantomPinned,
143            occupied: core::array::from_fn(|_| AtomicBool::new(false)),
144            streams: TryMutex::new(Core {
145                streams: core::array::from_fn(|_| Stream::new()),
146                producers: core::array::from_fn(|_| None),
147                mixer: Mixer::new(),
148            }),
149            outputs: core::array::from_fn(|_| OutputSlot {
150                ring: UnsafeCell::new(RingBuffer::new()),
151                dropped_blocks: AtomicUsize::new(0),
152                occupied: AtomicBool::new(false),
153            }),
154        })
155    }
156
157    /// Sets the master gain, from 0 to 100 percent.
158    pub fn set_master_volume(&self, volume: u8) -> Result<()> {
159        if volume > 100 {
160            return Err(IoErrorKind::InvalidArgument);
161        }
162        self.streams
163            .lock()?
164            .mixer
165            .set_master_volume(Volume::from_percent(volume));
166        Ok(())
167    }
168
169    /// Mixes one quantum and copies it to every output with room for a full block.
170    /// A full output drops this block without affecting any other output.
171    pub fn mix_next_block(self: Pin<&Self>) -> Result<()> {
172        let mut core = self.streams.lock()?;
173        let frame_size = FRAME_BYTES;
174        let format = nanoaudio::Format::F32;
175        let admitted: [bool; O] = core::array::from_fn(|index| {
176            let occupied = self.outputs[index].occupied.load(Ordering::Acquire);
177            if !occupied {
178                return false;
179            }
180            let ready = core.producers[index]
181                .as_ref()
182                .is_some_and(|producer| producer.free() >= F * frame_size);
183            if occupied && !ready {
184                self.outputs[index]
185                    .dropped_blocks
186                    .fetch_add(1, Ordering::Relaxed);
187            }
188            occupied && ready
189        });
190        let active: [bool; S] =
191            core::array::from_fn(|index| self.occupied[index].load(Ordering::Acquire));
192        let Core {
193            streams,
194            producers,
195            mixer,
196        } = &mut *core;
197        // One stereo F32 frame of scratch, independent of block length.
198        // This avoids an additional persistent block beyond the queue budget.
199        let mut frame = [0u8; FRAME_BYTES];
200        for _ in 0..F {
201            mixer.clear_bytes(&mut frame[..frame_size], format);
202            for (index, stream) in streams.iter_mut().enumerate() {
203                if !active[index] || !stream.started || stream.length == 0 {
204                    continue;
205                }
206                mixer
207                    .add_bytes(
208                        index,
209                        &mut frame[..frame_size],
210                        &stream.bytes[stream.read..stream.read + frame_size],
211                        format,
212                    )
213                    .map_err(|_| IoErrorKind::InvalidArgument)?;
214                stream.read = (stream.read + frame_size) % B;
215                stream.length -= frame_size;
216            }
217            for (index, producer) in producers.iter_mut().enumerate() {
218                if admitted[index] {
219                    producer
220                        .as_mut()
221                        .expect("occupied output has producer")
222                        .write(&frame[..frame_size]);
223                }
224            }
225        }
226        Ok(())
227    }
228
229    /// Reserves a sink and resets its queue and drop counter.
230    pub fn open_output(self: Pin<&Self>) -> Result<OutputHandle<'_, S, B, F, O, Q>> {
231        let this = self.get_ref();
232        let mut core = self.streams.lock()?;
233        let index = self
234            .outputs
235            .iter()
236            .position(|slot| !slot.occupied.load(Ordering::Acquire))
237            .ok_or(IoErrorKind::ResourceBusy)?;
238        // SAFETY: the core lock serializes registration and producer use. An
239        // unoccupied slot has no live consumer; handle drop destroys it before
240        // releasing the slot. Pinning prevents moves even if a handle is forgotten.
241        core.producers[index].take();
242        let ring = unsafe { &mut *this.outputs[index].ring.get() };
243        let (producer, consumer) = ring.split();
244        // SAFETY: this erased borrow is only used under the core lock while the
245        // slot is occupied and this system is pinned. The ring stays at its
246        // address until system drop, even if an output handle is forgotten.
247        // On reuse the previous producer is dropped before splitting again.
248        core.producers[index] = Some(unsafe {
249            core::mem::transmute::<Producer<'_, Q>, Producer<'static, Q>>(producer)
250        });
251        self.outputs[index]
252            .dropped_blocks
253            .store(0, Ordering::Relaxed);
254        self.outputs[index].occupied.store(true, Ordering::Release);
255        Ok(OutputHandle {
256            system: this,
257            index,
258            consumer: Some(consumer),
259        })
260    }
261
262    /// Reserves an empty, paused application stream at 100 percent volume.
263    pub fn open_stream(&self) -> Result<StreamHandle<'_, S, B, F, O, Q>> {
264        let mut streams = self.streams.lock()?;
265        let index = self
266            .occupied
267            .iter()
268            .position(|slot| !slot.load(Ordering::Acquire))
269            .ok_or(IoErrorKind::ResourceBusy)?;
270        streams.streams[index] = Stream::new();
271        streams
272            .mixer
273            .set_volume(index, Volume::UNITY)
274            .map_err(|_| IoErrorKind::InvalidArgument)?;
275        self.occupied[index].store(true, Ordering::Release);
276        Ok(StreamHandle {
277            system: self,
278            index,
279        })
280    }
281}
282
283/// An exclusive reservation of one application stream; dropping it frees the slot.
284pub struct StreamHandle<
285    'a,
286    const S: usize,
287    const B: usize,
288    const F: usize,
289    const O: usize,
290    const Q: usize,
291> {
292    system: &'a AudioSystem<S, B, F, O, Q>,
293    index: usize,
294}
295impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize>
296    StreamHandle<'_, S, B, F, O, Q>
297{
298    pub fn configuration(&self) -> Configuration {
299        MIX_CONFIGURATION
300    }
301    pub fn start(&self) -> Result<()> {
302        self.system.streams.lock()?.streams[self.index].started = true;
303        Ok(())
304    }
305    pub fn stop(&self) -> Result<()> {
306        self.system.streams.lock()?.streams[self.index].started = false;
307        Ok(())
308    }
309    pub fn flush(&self) -> Result<()> {
310        if self.system.streams.lock()?.streams[self.index].length == 0 {
311            Ok(())
312        } else {
313            Err(IoErrorKind::WouldBlock)
314        }
315    }
316    pub fn set_volume(&self, volume: u8) -> Result<()> {
317        if volume > 100 {
318            return Err(IoErrorKind::InvalidArgument);
319        }
320        self.system
321            .streams
322            .lock()?
323            .mixer
324            .set_volume(self.index, Volume::from_percent(volume))
325            .map_err(|_| IoErrorKind::InvalidArgument)
326    }
327    pub fn volume(&self) -> Result<u8> {
328        Ok(self
329            .system
330            .streams
331            .lock()?
332            .mixer
333            .volume(self.index)
334            .map_err(|_| IoErrorKind::InvalidArgument)?
335            .percent() as u8)
336    }
337    /// Returns frame-aligned writable bytes, or zero while the core is busy.
338    pub fn writable(&self) -> usize {
339        self.system
340            .streams
341            .lock()
342            .map(|streams| B - streams.streams[self.index].length)
343            .unwrap_or(0)
344    }
345    /// Writes as many whole frames as fit. An incomplete input frame is rejected;
346    /// the input byte slice does not need typed sample alignment.
347    pub fn write(&self, bytes: &[u8]) -> Result<usize> {
348        let frame_size = FRAME_BYTES;
349        if !bytes.len().is_multiple_of(frame_size) {
350            return Err(IoErrorKind::InvalidArgument);
351        }
352        let mut streams = self.system.streams.lock()?;
353        let stream = &mut streams.streams[self.index];
354        let count = bytes.len().min(B - stream.length);
355        let write = (stream.read + stream.length) % B;
356        let first = count.min(B - write);
357        stream.bytes[write..write + first].copy_from_slice(&bytes[..first]);
358        stream.bytes[..count - first].copy_from_slice(&bytes[first..count]);
359        stream.length += count;
360        Ok(count)
361    }
362}
363impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize> Drop
364    for StreamHandle<'_, S, B, F, O, Q>
365{
366    fn drop(&mut self) {
367        self.system.occupied[self.index].store(false, Ordering::Release);
368    }
369}
370
371/// One independently drained output queue. Dropping it releases its output slot.
372pub struct OutputHandle<
373    'a,
374    const S: usize,
375    const B: usize,
376    const F: usize,
377    const O: usize,
378    const Q: usize,
379> {
380    system: &'a AudioSystem<S, B, F, O, Q>,
381    index: usize,
382    consumer: Option<Consumer<'a, Q>>,
383}
384impl<'a, const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize>
385    OutputHandle<'a, S, B, F, O, Q>
386{
387    pub fn configuration(&self) -> Configuration {
388        MIX_CONFIGURATION
389    }
390    /// Counts incoming whole blocks dropped while this sink had insufficient space.
391    pub fn dropped_blocks(&self) -> usize {
392        self.system.outputs[self.index]
393            .dropped_blocks
394            .load(Ordering::Relaxed)
395    }
396    /// Borrows the sole consumer without allowing it to escape the reservation.
397    /// The callback executes without locking the audio core.
398    pub fn with_consumer<R>(
399        &mut self,
400        consume: impl for<'c> FnOnce(&mut Consumer<'c, Q>) -> R,
401    ) -> R {
402        consume(
403            self.consumer
404                .as_mut()
405                .expect("consumer exists until handle drop"),
406        )
407    }
408}
409
410/// Keeps a transferred native output slot reserved until the adapter is dropped.
411///
412/// This token is returned by [`OutputHandle::into_consumer_with_reservation`].
413/// Drop the transferred consumer or its adapter before this reservation.
414pub struct OutputReservation {
415    occupied: &'static AtomicBool,
416}
417
418impl Drop for OutputReservation {
419    fn drop(&mut self) {
420        self.occupied.store(false, Ordering::Release);
421    }
422}
423
424impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize> Drop
425    for OutputHandle<'_, S, B, F, O, Q>
426{
427    fn drop(&mut self) {
428        if self.consumer.take().is_some() {
429            self.system.outputs[self.index]
430                .occupied
431                .store(false, Ordering::Release);
432        }
433    }
434}
435
436impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize>
437    OutputHandle<'static, S, B, F, O, Q>
438{
439    /// Transfers a static system's consumer to an owning platform adapter.
440    /// This permanently reserves the output slot: the adapter does not return
441    /// its consumer, so the system cannot know when it is safe to reuse it.
442    pub fn into_consumer(mut self) -> Consumer<'static, Q> {
443        self.consumer
444            .take()
445            .expect("consumer exists until handle drop")
446    }
447
448    /// Transfers the consumer with a token that releases its output slot on drop.
449    ///
450    /// Unlike [`into_consumer`](Self::into_consumer), this permits the system to
451    /// reuse the output after the consumer's owner has been dropped. The adapter
452    /// must be destroyed before the returned reservation; a wrapper should own
453    /// both and explicitly drop the adapter first.
454    ///
455    /// # Safety
456    ///
457    /// The returned consumer must be dropped before the reservation. Releasing
458    /// the slot while the consumer is still live would allow the system to split
459    /// the same ring buffer again while that consumer still references it.
460    pub unsafe fn into_consumer_with_reservation(
461        mut self,
462    ) -> (Consumer<'static, Q>, OutputReservation) {
463        let consumer = self
464            .consumer
465            .take()
466            .expect("consumer exists until handle drop");
467        let reservation = OutputReservation {
468            occupied: &self.system.outputs[self.index].occupied,
469        };
470        (consumer, reservation)
471    }
472}