Skip to main content

audio/
device.rs

1use alloc::boxed::Box;
2use core::{mem::align_of, pin::Pin};
3
4use file_system::{
5    BaseOperations, CharacterDevice, Context, ControlCommand, ControlCommandIdentifier,
6    IoErrorKind, MountOperations, Result, Size,
7};
8use shared::AnyByLayout;
9
10use crate::{
11    AudioSystem, GET_CONFIGURATION, GET_VOLUME, GET_WRITABLE, SET_CONFIGURATION, SET_VOLUME, START,
12    STOP, StreamHandle,
13};
14
15fn validate_payload<T>(payload: &AnyByLayout) -> Result<()> {
16    let address = core::ptr::from_ref(payload).cast::<u8>() as usize;
17    if payload.get_size() != size_of::<T>() || !address.is_multiple_of(align_of::<T>()) {
18        return Err(IoErrorKind::InvalidArgument);
19    }
20    Ok(())
21}
22
23fn validate_command<C: ControlCommand>(input: &AnyByLayout, output: &AnyByLayout) -> Result<()> {
24    validate_payload::<C::Input>(input)?;
25    validate_payload::<C::Output>(output)
26}
27
28/// The local `/dev/audio/playback` character device.
29///
30/// The device borrows a pinned static audio service. Every successful VFS open
31/// reserves a separate stream and stores that reservation in its `Context`.
32/// Cloning an open context is unsupported; the VFS receives
33/// [`IoErrorKind::Unsupported`] rather than two contexts sharing one stream.
34pub struct AudioStreamDevice<
35    const STREAMS: usize = 4,
36    const STREAM_BYTES: usize = 2048,
37    const MIX_FRAMES: usize = 128,
38    const OUTPUTS: usize = 2,
39    const SINK_BYTES: usize = 3072,
40> {
41    system: Pin<&'static AudioSystem<STREAMS, STREAM_BYTES, MIX_FRAMES, OUTPUTS, SINK_BYTES>>,
42}
43
44impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize>
45    AudioStreamDevice<S, B, F, O, Q>
46{
47    /// Borrows the pinned, static mixer service used to create per-open streams.
48    pub const fn new(system: Pin<&'static AudioSystem<S, B, F, O, Q>>) -> Self {
49        Self { system }
50    }
51
52    fn stream<'c>(&self, context: &'c Context) -> Result<&'c StreamHandle<'static, S, B, F, O, Q>> {
53        context
54            .get_private_data_of_type::<StreamHandle<'static, S, B, F, O, Q>>()
55            .ok_or(IoErrorKind::BadDescriptor)
56    }
57}
58
59impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize> BaseOperations
60    for AudioStreamDevice<S, B, F, O, Q>
61{
62    fn open(&self, context: &mut Context) -> Result<()> {
63        if context.get_private_data().is_some() {
64            return Err(IoErrorKind::BadDescriptor);
65        }
66        let stream = self.system.get_ref().open_stream()?;
67        context.set_private_data(Box::new(stream));
68        Ok(())
69    }
70
71    fn close(&self, context: &mut Context) -> Result<()> {
72        context
73            .take_private_data_of_type::<StreamHandle<'static, S, B, F, O, Q>>()
74            .map(drop)
75            .ok_or(IoErrorKind::BadDescriptor)
76    }
77
78    fn read(
79        &self,
80        _context: &mut Context,
81        _cx: &mut core::task::Context<'_>,
82        _buffer: &mut [u8],
83        _absolute_position: Size,
84    ) -> core::task::Poll<Result<usize>> {
85        file_system::ready(|| Err(IoErrorKind::Unsupported))
86    }
87
88    fn write(
89        &self,
90        context: &mut Context,
91        _cx: &mut core::task::Context<'_>,
92        buffer: &[u8],
93        _absolute_position: Size,
94    ) -> core::task::Poll<Result<usize>> {
95        file_system::ready(|| self.stream(context)?.write(buffer))
96    }
97
98    fn flush(
99        &self,
100        context: &mut Context,
101        _cx: &mut core::task::Context<'_>,
102    ) -> core::task::Poll<Result<()>> {
103        file_system::ready(|| self.stream(context)?.flush())
104    }
105
106    fn control(
107        &self,
108        context: &mut Context,
109        _cx: &mut core::task::Context<'_>,
110        command: ControlCommandIdentifier,
111        input: &AnyByLayout,
112        output: &mut AnyByLayout,
113    ) -> core::task::Poll<Result<()>> {
114        file_system::ready(|| {
115            let stream = self.stream(context)?;
116            match command {
117                SET_CONFIGURATION::IDENTIFIER => {
118                    validate_command::<SET_CONFIGURATION>(input, output)?;
119                    let configuration = SET_CONFIGURATION::cast_input(input)?;
120                    configuration.validate()?;
121                    if *configuration != stream.configuration() {
122                        return Err(IoErrorKind::Unsupported);
123                    }
124                }
125                GET_CONFIGURATION::IDENTIFIER => {
126                    validate_command::<GET_CONFIGURATION>(input, output)?;
127                    *GET_CONFIGURATION::cast_output(output)? = stream.configuration();
128                }
129                GET_WRITABLE::IDENTIFIER => {
130                    validate_command::<GET_WRITABLE>(input, output)?;
131                    *GET_WRITABLE::cast_output(output)? =
132                        stream.writable().min(u32::MAX as usize) as u32;
133                }
134                SET_VOLUME::IDENTIFIER => {
135                    validate_command::<SET_VOLUME>(input, output)?;
136                    stream.set_volume(*SET_VOLUME::cast_input(input)?)?;
137                }
138                GET_VOLUME::IDENTIFIER => {
139                    validate_command::<GET_VOLUME>(input, output)?;
140                    *GET_VOLUME::cast_output(output)? = stream.volume()?;
141                }
142                START::IDENTIFIER => {
143                    validate_command::<START>(input, output)?;
144                    stream.start()?;
145                }
146                STOP::IDENTIFIER => {
147                    validate_command::<STOP>(input, output)?;
148                    stream.stop()?;
149                }
150                _ => return Err(IoErrorKind::Unsupported),
151            }
152            Ok(())
153        })
154    }
155
156    fn clone_context(&self, _context: &Context) -> Result<Context> {
157        Err(IoErrorKind::Unsupported)
158    }
159}
160
161impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize> MountOperations
162    for AudioStreamDevice<S, B, F, O, Q>
163{
164}
165
166impl<const S: usize, const B: usize, const F: usize, const O: usize, const Q: usize> CharacterDevice
167    for AudioStreamDevice<S, B, F, O, Q>
168{
169}