Skip to main content

audio/
playback.rs

1use core::cell::RefCell;
2use file_system::{
3    ControlCommand, ControlCommandIdentifier, DirectBaseOperations, DirectCharacterDevice,
4    IoErrorKind, MountOperations, Result, Size,
5};
6use nanoaudio::{Consumer, Producer, RingBuffer, Sample, Stream, Volume};
7use portable_atomic::{AtomicBool, AtomicU8, Ordering};
8use shared::AnyByLayout;
9use synchronization::blocking_mutex::{Mutex, raw::CriticalSectionRawMutex};
10
11use crate::{
12    Configuration, GET_CONFIGURATION, GET_VOLUME, GET_WRITABLE, SET_CONFIGURATION, SET_VOLUME,
13    START, STOP,
14};
15
16fn validate_payload<T>(payload: &AnyByLayout) -> Result<()> {
17    let pointer = core::ptr::from_ref(payload).cast::<u8>() as usize;
18    if payload.get_size() != size_of::<T>() || !pointer.is_multiple_of(align_of::<T>()) {
19        return Err(IoErrorKind::InvalidArgument);
20    }
21    Ok(())
22}
23
24fn validate_command<C: ControlCommand>(input: &AnyByLayout, output: &AnyByLayout) -> Result<()> {
25    validate_payload::<C::Input>(input)?;
26    validate_payload::<C::Output>(output)
27}
28
29struct State {
30    started: AtomicBool,
31    failed: AtomicBool,
32    volume: AtomicU8,
33}
34
35impl State {
36    const fn new() -> Self {
37        Self {
38            started: AtomicBool::new(false),
39            failed: AtomicBool::new(false),
40            volume: AtomicU8::new(100),
41        }
42    }
43
44    fn check(&self) -> Result<()> {
45        if self.failed.load(Ordering::Acquire) {
46            Err(IoErrorKind::InputOutput)
47        } else {
48            Ok(())
49        }
50    }
51}
52
53/// Caller-owned storage, including exactly `N` PCM bytes plus control/cursor state.
54///
55/// Allocate it once, or put it in static memory for an interrupt/host callback.
56/// `N` must be nonzero and divisible by the configured frame size.
57pub struct PlaybackBuffer<const N: usize> {
58    ring: RingBuffer<N>,
59    state: State,
60}
61
62impl<const N: usize> Default for PlaybackBuffer<N> {
63    fn default() -> Self {
64        Self::new()
65    }
66}
67
68impl<const N: usize> PlaybackBuffer<N> {
69    pub const fn new() -> Self {
70        Self {
71            ring: RingBuffer::new(),
72            state: State::new(),
73        }
74    }
75
76    /// Create a paused device and its single consumer, emptying previous data.
77    /// The configuration is fixed until both halves have been dropped.
78    pub fn split(
79        &mut self,
80        configuration: Configuration,
81    ) -> Result<(OutputDevice<'_, N>, Renderer<'_, N>)> {
82        let frame_size = configuration.frame_size()?;
83        if N > u32::MAX as usize || !N.is_multiple_of(frame_size) {
84            return Err(IoErrorKind::InvalidArgument);
85        }
86        self.state = State::new();
87        let (producer, consumer) = self.ring.split();
88        Ok((
89            OutputDevice {
90                producer: Mutex::new(RefCell::new(producer)),
91                configuration,
92                frame_size,
93                state: &self.state,
94            },
95            Renderer {
96                consumer,
97                configuration,
98                frame_size,
99                format: crate::configuration::native_format(configuration.sample_format()?),
100                state: &self.state,
101            },
102        ))
103    }
104}
105
106/// Serializes writers; the callback never takes this lock.
107pub struct OutputDevice<'a, const N: usize> {
108    producer: Mutex<CriticalSectionRawMutex, RefCell<Producer<'a, N>>>,
109    configuration: Configuration,
110    frame_size: usize,
111    state: &'a State,
112}
113
114impl<const N: usize> DirectBaseOperations for OutputDevice<'_, N> {
115    fn read(
116        &self,
117        _cx: &mut core::task::Context<'_>,
118        _: &mut [u8],
119        _: Size,
120    ) -> core::task::Poll<Result<usize>> {
121        file_system::ready(|| Err(IoErrorKind::Unsupported))
122    }
123
124    /// Enqueues whole frames, returning zero immediately when full. No alignment
125    /// requirement on the byte slice; incomplete frames are rejected.
126    fn write(
127        &self,
128        _cx: &mut core::task::Context<'_>,
129        buffer: &[u8],
130        _: Size,
131    ) -> core::task::Poll<Result<usize>> {
132        file_system::ready(|| {
133            self.state.check()?;
134            if !buffer.len().is_multiple_of(self.frame_size) {
135                return Err(IoErrorKind::InvalidArgument);
136            }
137            Ok(self.producer.lock(|producer| {
138                let mut producer = producer.borrow_mut();
139                let free = producer.free() / self.frame_size * self.frame_size;
140                producer.write(&buffer[..buffer.len().min(free)])
141            }))
142        })
143    }
144
145    /// Polls for queued PCM to be consumed. Success means submitted to the
146    /// callback, not physically played by the hardware. Never waits or spins.
147    fn flush(&self, _cx: &mut core::task::Context<'_>) -> core::task::Poll<Result<()>> {
148        file_system::ready(|| {
149            self.state.check()?;
150            if self.producer.lock(|producer| producer.borrow().free()) == N {
151                Ok(())
152            } else {
153                Err(IoErrorKind::WouldBlock)
154            }
155        })
156    }
157
158    fn control(
159        &self,
160        _cx: &mut core::task::Context<'_>,
161        command: ControlCommandIdentifier,
162        input: &AnyByLayout,
163        output: &mut AnyByLayout,
164    ) -> core::task::Poll<Result<()>> {
165        file_system::ready(|| {
166            self.state.check()?;
167            match command {
168                SET_CONFIGURATION::IDENTIFIER => {
169                    validate_command::<SET_CONFIGURATION>(input, output)?;
170                    let configuration = SET_CONFIGURATION::cast_input(input)?;
171                    configuration.validate()?;
172                    if *configuration != self.configuration {
173                        return Err(IoErrorKind::Unsupported);
174                    }
175                }
176                GET_CONFIGURATION::IDENTIFIER => {
177                    validate_command::<GET_CONFIGURATION>(input, output)?;
178                    *GET_CONFIGURATION::cast_output(output)? = self.configuration;
179                }
180                GET_WRITABLE::IDENTIFIER => {
181                    validate_command::<GET_WRITABLE>(input, output)?;
182                    let free = self.producer.lock(|producer| producer.borrow().free());
183                    *GET_WRITABLE::cast_output(output)? =
184                        (free / self.frame_size * self.frame_size) as u32;
185                }
186                SET_VOLUME::IDENTIFIER => {
187                    validate_command::<SET_VOLUME>(input, output)?;
188                    let volume = *SET_VOLUME::cast_input(input)?;
189                    if volume > 100 {
190                        return Err(IoErrorKind::InvalidArgument);
191                    }
192                    self.state.volume.store(volume, Ordering::Release);
193                }
194                GET_VOLUME::IDENTIFIER => {
195                    validate_command::<GET_VOLUME>(input, output)?;
196                    *GET_VOLUME::cast_output(output)? = self.state.volume.load(Ordering::Acquire);
197                }
198                START::IDENTIFIER => {
199                    validate_command::<START>(input, output)?;
200                    self.state.started.store(true, Ordering::Release);
201                }
202                STOP::IDENTIFIER => {
203                    validate_command::<STOP>(input, output)?;
204                    self.state.started.store(false, Ordering::Release);
205                }
206                _ => return Err(IoErrorKind::Unsupported),
207            }
208            Ok(())
209        })
210    }
211}
212
213impl<const N: usize> MountOperations for OutputDevice<'_, N> {}
214impl<const N: usize> DirectCharacterDevice for OutputDevice<'_, N> {}
215
216/// A cheap handle for host error callbacks and backend teardown.
217#[derive(Clone, Copy)]
218pub struct FailureReporter<'a>(&'a AtomicBool);
219
220impl FailureReporter<'_> {
221    /// Marks this stream unusable. No allocation, locks or logging.
222    pub fn fail(self) {
223        self.0.store(true, Ordering::Release);
224    }
225}
226
227/// The only consumer of a playback queue, owned by the hardware callback.
228/// All render methods return frames consumed and fill the remainder with silence.
229pub struct Renderer<'a, const N: usize> {
230    consumer: Consumer<'a, N>,
231    configuration: Configuration,
232    frame_size: usize,
233    format: nanoaudio::Format,
234    state: &'a State,
235}
236
237impl<'a, const N: usize> Renderer<'a, N> {
238    pub fn failure_reporter(&self) -> FailureReporter<'a> {
239        FailureReporter(&self.state.failed)
240    }
241
242    pub fn render_f32(&mut self, output: &mut [f32]) -> usize {
243        self.render(output)
244    }
245
246    pub fn render_i16(&mut self, output: &mut [i16]) -> usize {
247        self.render(output)
248    }
249
250    pub fn render_i32(&mut self, output: &mut [i32]) -> usize {
251        self.render(output)
252    }
253
254    pub fn render_u8(&mut self, output: &mut [u8]) -> usize {
255        self.render(output)
256    }
257
258    fn render<S: Sample>(&mut self, output: &mut [S]) -> usize {
259        output.fill(S::SILENCE);
260        if self.state.check().is_err() || !self.state.started.load(Ordering::Acquire) {
261            return 0;
262        }
263        let channels = self.configuration.channels as usize;
264        let volume = Volume::from_percent(self.state.volume.load(Ordering::Acquire));
265        let mut frames = 0;
266        while output.len() - frames * channels >= channels {
267            let bytes = self.consumer.readable();
268            if bytes.is_empty() {
269                break;
270            }
271            // Configuration and frame alignment were checked at split/write.
272            let count = nanoaudio::source(bytes, self.format, self.configuration.channels)
273                .expect("validated PCM configuration")
274                .volume(volume)
275                .write_samples(&mut output[frames * channels..]);
276            self.consumer.release(count * self.frame_size);
277            frames += count;
278        }
279        frames
280    }
281}
282
283impl<const N: usize> Drop for Renderer<'_, N> {
284    fn drop(&mut self) {
285        self.failure_reporter().fail();
286    }
287}