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
15struct TryMutex<T> {
17 locked: AtomicBool,
18 value: UnsafeCell<T>,
19}
20
21unsafe 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 unsafe { &*self.0.value.get() }
47 }
48}
49impl<T> DerefMut for Guard<'_, T> {
50 fn deref_mut(&mut self) -> &mut T {
51 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}
83unsafe impl<const N: usize> Sync for OutputSlot<N> {}
86
87pub 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 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 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 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 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 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 core.producers[index].take();
242 let ring = unsafe { &mut *this.outputs[index].ring.get() };
243 let (producer, consumer) = ring.split();
244 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 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
283pub 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 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 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
371pub 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 pub fn dropped_blocks(&self) -> usize {
392 self.system.outputs[self.index]
393 .dropped_blocks
394 .load(Ordering::Relaxed)
395 }
396 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
410pub 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 pub fn into_consumer(mut self) -> Consumer<'static, Q> {
443 self.consumer
444 .take()
445 .expect("consumer exists until handle drop")
446 }
447
448 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}