device_virtio_snd/sys/
linux.rs

1// Copyright 2022 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#[cfg(feature = "audio_aaudio")]
6use std::io;
7#[cfg(feature = "audio_aaudio")]
8use std::io::Read;
9#[cfg(feature = "audio_aaudio")]
10use std::io::Write;
11#[cfg(feature = "audio_aaudio")]
12use std::os::unix::net::UnixStream;
13#[cfg(feature = "audio_cras")]
14use std::path::Path;
15#[cfg(feature = "audio_aaudio")]
16use std::sync::Arc;
17#[cfg(feature = "audio_aaudio")]
18use std::task::Poll;
19
20#[cfg(feature = "audio_aaudio")]
21use android_audio::AndroidAudioStreamSourceGenerator;
22#[cfg(feature = "audio_aaudio")]
23use android_audio::AudioPermissionDelegate;
24use async_trait::async_trait;
25use audio_streams::capture::AsyncCaptureBuffer;
26use audio_streams::capture::AsyncCaptureBufferStream;
27use audio_streams::capture::NoopCaptureStream;
28use audio_streams::AsyncPlaybackBufferStream;
29use audio_streams::BoxError;
30use audio_streams::SampleFormat;
31use audio_streams::StreamEffect;
32use audio_streams::StreamSource;
33use audio_streams::StreamSourceGenerator;
34use base::error;
35#[cfg(feature = "audio_aaudio")]
36use base::safe_descriptor_from_cmdline_fd;
37use base::set_rt_prio_limit;
38use base::set_rt_round_robin;
39#[cfg(feature = "audio_aaudio")]
40use base::AsRawDescriptor;
41use base::RawDescriptor;
42use cros_async::Executor;
43use futures::channel::mpsc::UnboundedSender;
44use jail::create_sandbox_minijail;
45use jail::JailConfig;
46use jail::RunAsUser;
47use jail::SandboxConfig;
48use jail::MAX_OPEN_FILES_DEFAULT;
49#[cfg(feature = "audio_cras")]
50use libcras::CrasStreamSourceGenerator;
51#[cfg(feature = "audio_cras")]
52use libcras::CrasStreamType;
53use minijail::Minijail;
54use serde::Deserialize;
55use serde::Serialize;
56#[cfg(feature = "audio_aaudio")]
57use sync::Mutex;
58#[cfg(feature = "audio_aaudio")]
59use vm_control::AudioPermissionRequest;
60#[cfg(feature = "audio_aaudio")]
61use vm_control::AudioPermissionResponse;
62
63use crate::common_backend::async_funcs::CaptureBufferReader;
64use crate::common_backend::async_funcs::PlaybackBufferWriter;
65use crate::common_backend::stream_info::StreamInfo;
66use crate::common_backend::DirectionalStream;
67use crate::common_backend::Error;
68use crate::common_backend::PcmResponse;
69use crate::common_backend::SndData;
70use crate::parameters::Error as ParametersError;
71use crate::parameters::Parameters;
72use crate::parameters::StreamSourceBackend as Backend;
73
74const AUDIO_THREAD_RTPRIO: u16 = 10; // Matches other cros audio clients.
75
76pub(crate) type SysAudioStreamSourceGenerator = Box<dyn StreamSourceGenerator>;
77pub(crate) type SysAudioStreamSource = Box<dyn StreamSource>;
78pub(crate) type SysBufferReader = UnixBufferReader;
79
80pub struct SysDirectionOutput {
81    pub async_playback_buffer_stream: Box<dyn audio_streams::AsyncPlaybackBufferStream>,
82    pub buffer_writer: Box<dyn PlaybackBufferWriter>,
83}
84
85pub(crate) struct SysAsyncStreamObjects {
86    pub(crate) stream: DirectionalStream,
87    pub(crate) pcm_sender: UnboundedSender<PcmResponse>,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
91pub enum StreamSourceBackend {
92    #[cfg(feature = "audio_aaudio")]
93    AAUDIO,
94    #[cfg(feature = "audio_cras")]
95    CRAS,
96}
97
98// Implemented to make backend serialization possible, since we deserialize from str.
99impl From<StreamSourceBackend> for String {
100    fn from(backend: StreamSourceBackend) -> Self {
101        match backend {
102            #[cfg(feature = "audio_aaudio")]
103            StreamSourceBackend::AAUDIO => "aaudio".to_owned(),
104            #[cfg(feature = "audio_cras")]
105            StreamSourceBackend::CRAS => "cras".to_owned(),
106        }
107    }
108}
109
110impl TryFrom<&str> for StreamSourceBackend {
111    type Error = ParametersError;
112
113    fn try_from(s: &str) -> Result<Self, Self::Error> {
114        match s {
115            #[cfg(feature = "audio_aaudio")]
116            "aaudio" => Ok(StreamSourceBackend::AAUDIO),
117            #[cfg(feature = "audio_cras")]
118            "cras" => Ok(StreamSourceBackend::CRAS),
119            _ => Err(ParametersError::InvalidBackend),
120        }
121    }
122}
123
124/// Asks the host for audio capture permission over the socket passed with the
125/// `permission_socket_fd` parameter, using the 1-byte `vm_control` protocol.
126///
127/// One socket is shared by all capture streams of the card. At most one `Check` is outstanding at
128/// a time, and its answer is shared by every stream waiting on it. A `start()` joins the
129/// outstanding request, even if its answer is already buffered; bytes buffered with no request
130/// outstanding are unsolicited and are discarded. The host must answer each `Check`
131/// exactly once (a dismissed dialog is `Denied`); until then capture stays silent. The socket is
132/// non-blocking, so this never blocks the audio executor.
133#[cfg(feature = "audio_aaudio")]
134pub struct FdPermissionDelegate {
135    socket: Mutex<PermissionSocket>,
136}
137
138#[cfg(feature = "audio_aaudio")]
139struct PermissionSocket {
140    stream: UnixStream,
141    /// A `Check` was sent and its answer has not been read yet.
142    in_flight: bool,
143    /// Answer to the last completed request.
144    answer: Option<bool>,
145}
146
147#[cfg(feature = "audio_aaudio")]
148impl PermissionSocket {
149    /// Reads one byte without blocking, or returns `None` if none is buffered.
150    fn try_read(&mut self) -> io::Result<Option<u8>> {
151        let mut buf = [0u8; 1];
152        loop {
153            return match self.stream.read(&mut buf) {
154                Ok(0) => Err(io::Error::new(
155                    io::ErrorKind::UnexpectedEof,
156                    "permission socket closed",
157                )),
158                Ok(_) => Ok(Some(buf[0])),
159                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
160                Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(None),
161                Err(e) => Err(e),
162            };
163        }
164    }
165
166    /// Discards buffered bytes.
167    fn drain(&mut self) -> io::Result<()> {
168        while let Some(byte) = self.try_read()? {
169            base::warn!("Discarding unsolicited audio permission response byte: {byte}");
170        }
171        Ok(())
172    }
173}
174
175#[cfg(feature = "audio_aaudio")]
176impl FdPermissionDelegate {
177    pub fn new(stream: UnixStream) -> io::Result<Self> {
178        stream.set_nonblocking(true)?;
179        Ok(Self {
180            socket: Mutex::new(PermissionSocket {
181                stream,
182                in_flight: false,
183                answer: None,
184            }),
185        })
186    }
187}
188
189#[cfg(feature = "audio_aaudio")]
190impl AudioPermissionDelegate for FdPermissionDelegate {
191    fn request_permission(&self) -> Result<(), BoxError> {
192        let mut socket = self.socket.lock();
193        if socket.in_flight {
194            // Join the outstanding Check; poll_permission() hands its answer to every waiter.
195            return Ok(());
196        }
197        // Nothing is outstanding, so anything buffered is unsolicited.
198        socket.drain()?;
199        socket.answer = None;
200        // Rust ignores SIGPIPE, so a closed peer makes this return EPIPE instead of killing us.
201        socket
202            .stream
203            .write_all(&[AudioPermissionRequest::Check.to_wire()])?;
204        socket.in_flight = true;
205        Ok(())
206    }
207
208    fn poll_permission(&self) -> Poll<Result<bool, BoxError>> {
209        let mut socket = self.socket.lock();
210        if !socket.in_flight {
211            return Poll::Ready(
212                socket
213                    .answer
214                    .ok_or_else(|| "no permission request outstanding".into()),
215            );
216        }
217        let result = match socket.try_read() {
218            Ok(None) => return Poll::Pending,
219            Ok(Some(byte)) => match AudioPermissionResponse::try_from(byte) {
220                Ok(AudioPermissionResponse::Granted) => {
221                    base::info!("Audio capture permission granted by host");
222                    Ok(true)
223                }
224                Ok(AudioPermissionResponse::Denied) => {
225                    base::warn!("Audio capture permission denied by host");
226                    Ok(false)
227                }
228                Err(unknown) => {
229                    base::error!("Received invalid audio permission response byte: {unknown}");
230                    Err(io::Error::new(
231                        io::ErrorKind::InvalidData,
232                        format!("Invalid audio permission response byte: {unknown}"),
233                    ))
234                }
235            },
236            Err(e) => Err(e),
237        };
238        socket.in_flight = false;
239        socket.answer = result.as_ref().ok().copied();
240        Poll::Ready(result.map_err(BoxError::from))
241    }
242}
243
244#[cfg(feature = "audio_aaudio")]
245pub(crate) fn create_aaudio_stream_source_generators(
246    params: &Parameters,
247    snd_data: &SndData,
248    keep_rds: &mut Vec<RawDescriptor>,
249) -> Result<Vec<SysAudioStreamSourceGenerator>, Error> {
250    // A bad fd is an error rather than falling back to no delegate, which would capture without
251    // asking the host.
252    let permission_delegate: Option<Arc<dyn AudioPermissionDelegate>> =
253        match params.permission_socket_fd {
254            Some(fd) => {
255                let socket = safe_descriptor_from_cmdline_fd(&fd)
256                    .map_err(|e| Error::PermissionSocket(e.into()))?;
257                keep_rds.push(socket.as_raw_descriptor());
258                let delegate = FdPermissionDelegate::new(UnixStream::from(socket))
259                    .map_err(Error::PermissionSocket)?;
260                Some(Arc::new(delegate))
261            }
262            None => None,
263        };
264    let mut generators: Vec<Box<dyn StreamSourceGenerator>> =
265        Vec::with_capacity(snd_data.pcm_info_len());
266    for pcm_info in snd_data.pcm_info_iter() {
267        assert_eq!(pcm_info.features, 0); // Should be 0. Android audio backend does not support any
268                                          // features.
269        let generator = match &permission_delegate {
270            Some(delegate) => {
271                AndroidAudioStreamSourceGenerator::with_permission_delegate(delegate.clone())
272            }
273            None => AndroidAudioStreamSourceGenerator::new(),
274        };
275        generators.push(Box::new(generator));
276    }
277    Ok(generators)
278}
279
280#[cfg(feature = "audio_cras")]
281pub(crate) fn create_cras_stream_source_generators(
282    params: &Parameters,
283    snd_data: &SndData,
284) -> Vec<Box<dyn StreamSourceGenerator>> {
285    let mut generators: Vec<Box<dyn StreamSourceGenerator>> =
286        Vec::with_capacity(snd_data.pcm_info_len());
287    for pcm_info in snd_data.pcm_info_iter() {
288        let device_params = params.get_device_params(pcm_info).unwrap_or_else(|err| {
289            error!("Create cras stream source generator error: {}", err);
290            Default::default()
291        });
292        generators.push(Box::new(CrasStreamSourceGenerator::with_stream_type(
293            params.capture,
294            device_params.client_type.unwrap_or(params.client_type),
295            params.socket_type,
296            device_params
297                .stream_type
298                .unwrap_or(CrasStreamType::CRAS_STREAM_TYPE_DEFAULT),
299        )));
300    }
301    generators
302}
303
304// Suppress `ptr_arg`: `keep_rds` must remain `&mut Vec` for cross-platform signature consistency
305// and descriptor accumulation when `feature = "audio_aaudio"` is enabled.
306#[allow(unused_variables, clippy::ptr_arg)]
307pub(crate) fn create_stream_source_generators(
308    backend: StreamSourceBackend,
309    params: &Parameters,
310    snd_data: &SndData,
311    keep_rds: &mut Vec<RawDescriptor>,
312) -> Result<Vec<Box<dyn StreamSourceGenerator>>, Error> {
313    match backend {
314        #[cfg(feature = "audio_aaudio")]
315        StreamSourceBackend::AAUDIO => {
316            create_aaudio_stream_source_generators(params, snd_data, keep_rds)
317        }
318        #[cfg(feature = "audio_cras")]
319        StreamSourceBackend::CRAS => Ok(create_cras_stream_source_generators(params, snd_data)),
320    }
321}
322
323pub(crate) fn set_audio_thread_priority() -> Result<(), base::Error> {
324    set_rt_prio_limit(u64::from(AUDIO_THREAD_RTPRIO))
325        .and_then(|_| set_rt_round_robin(i32::from(AUDIO_THREAD_RTPRIO)))
326}
327
328impl StreamInfo {
329    /// (*)
330    /// `buffer_size` in `audio_streams` API indicates the buffer size in bytes that the stream
331    /// consumes (or transmits) each time (next_playback/capture_buffer).
332    /// `period_bytes` in virtio-snd device (or ALSA) indicates the device transmits (or
333    /// consumes) for each PCM message.
334    /// Therefore, `buffer_size` in `audio_streams` == `period_bytes` in virtio-snd.
335    async fn set_up_async_playback_stream(
336        &mut self,
337        frame_size: usize,
338        ex: &Executor,
339    ) -> Result<Box<dyn AsyncPlaybackBufferStream>, Error> {
340        Ok(self
341            .stream_source
342            .as_mut()
343            .ok_or(Error::EmptyStreamSource)?
344            .async_new_async_playback_stream(
345                self.channels as usize,
346                self.format,
347                self.frame_rate,
348                // See (*)
349                self.period_bytes / frame_size,
350                ex,
351            )
352            .await
353            .map_err(Error::CreateStream)?
354            .1)
355    }
356
357    pub(crate) async fn set_up_async_capture_stream(
358        &mut self,
359        frame_size: usize,
360        _ex: &Executor,
361    ) -> Result<SysBufferReader, Error> {
362        // The host capture stream is created by UnixBufferReader once the stream is started, so
363        // that a PREPARE without START (e.g. a guest ALSA probe, after which the Linux virtio_snd
364        // driver never sends RELEASE) does not keep a host capture stream open.
365        let stream_source = self.stream_source.take().ok_or(Error::EmptyStreamSource)?;
366        Ok(SysBufferReader::new(
367            stream_source,
368            self.channels as usize,
369            self.format,
370            self.frame_rate,
371            // See (*)
372            self.period_bytes / frame_size,
373            self.effects.clone(),
374            self.card_index,
375        ))
376    }
377
378    pub(crate) async fn create_directionstream_output(
379        &mut self,
380        frame_size: usize,
381        ex: &Executor,
382    ) -> Result<DirectionalStream, Error> {
383        let async_playback_buffer_stream =
384            self.set_up_async_playback_stream(frame_size, ex).await?;
385
386        let buffer_writer = UnixBufferWriter::new(self.period_bytes);
387
388        Ok(DirectionalStream::Output(SysDirectionOutput {
389            async_playback_buffer_stream,
390            buffer_writer: Box::new(buffer_writer),
391        }))
392    }
393}
394
395/// State of the host capture stream owned by [`UnixBufferReader`].
396enum UnixCaptureStreamState {
397    /// No host capture stream. This is the initial state and the state after `stop()`.
398    Stopped,
399    /// `start()` was called. The host capture stream is created on the next capture period.
400    Starting,
401    /// The host capture stream is open.
402    Started(Box<dyn AsyncCaptureBufferStream>),
403    /// Creating the host capture stream failed. Paced silence is returned until `stop()`.
404    StartFailed(NoopCaptureStream),
405}
406
407/// Reads capture periods from a host capture stream that is only open between `start()` and
408/// `stop()`, so that host privacy indicators (e.g. the ChromeOS microphone indicator driven by
409/// CRAS input streams) reflect actual guest capture.
410pub(crate) struct UnixBufferReader {
411    // Declared before `stream_source` so that an open capture stream is dropped before its source.
412    state: UnixCaptureStreamState,
413    stream_source: SysAudioStreamSource,
414    num_channels: usize,
415    format: SampleFormat,
416    frame_rate: u32,
417    period_frames: usize,
418    effects: Vec<StreamEffect>,
419    card_index: usize,
420}
421
422impl UnixBufferReader {
423    fn new(
424        stream_source: SysAudioStreamSource,
425        num_channels: usize,
426        format: SampleFormat,
427        frame_rate: u32,
428        period_frames: usize,
429        effects: Vec<StreamEffect>,
430        card_index: usize,
431    ) -> Self {
432        UnixBufferReader {
433            state: UnixCaptureStreamState::Stopped,
434            stream_source,
435            num_channels,
436            format,
437            frame_rate,
438            period_frames,
439            effects,
440            card_index,
441        }
442    }
443
444    async fn create_and_start_stream(
445        &mut self,
446        ex: &Executor,
447    ) -> Result<Box<dyn AsyncCaptureBufferStream>, BoxError> {
448        let (_, mut async_stream) = self
449            .stream_source
450            .async_new_async_capture_stream(
451                self.num_channels,
452                self.format,
453                self.frame_rate,
454                self.period_frames,
455                &self.effects,
456                ex,
457            )
458            .await?;
459        async_stream.start()?;
460        Ok(async_stream)
461    }
462}
463
464#[async_trait(?Send)]
465impl CaptureBufferReader for UnixBufferReader {
466    async fn get_next_capture_period(
467        &mut self,
468        ex: &Executor,
469    ) -> Result<AsyncCaptureBuffer, BoxError> {
470        // Only open the host capture stream after start().
471        if matches!(self.state, UnixCaptureStreamState::Starting) {
472            self.state = match self.create_and_start_stream(ex).await {
473                Ok(async_stream) => UnixCaptureStreamState::Started(async_stream),
474                Err(e) => {
475                    error!(
476                        "[Card {}] Failed to create capture stream, capturing silence: {}",
477                        self.card_index, e
478                    );
479                    UnixCaptureStreamState::StartFailed(NoopCaptureStream::new(
480                        self.num_channels,
481                        self.format,
482                        self.frame_rate,
483                        self.period_frames,
484                    ))
485                }
486            };
487        }
488
489        match &mut self.state {
490            UnixCaptureStreamState::Started(async_stream) => {
491                async_stream.next_capture_buffer(ex).await
492            }
493            UnixCaptureStreamState::StartFailed(noop_stream) => {
494                noop_stream.next_capture_buffer(ex).await
495            }
496            UnixCaptureStreamState::Stopped | UnixCaptureStreamState::Starting => {
497                Err("capture stream is not started".into())
498            }
499        }
500    }
501
502    fn start(&mut self) -> Result<(), BoxError> {
503        // Don't replace an open stream, and don't retry a failed one until stop().
504        if matches!(self.state, UnixCaptureStreamState::Stopped) {
505            self.state = UnixCaptureStreamState::Starting;
506        }
507        Ok(())
508    }
509
510    fn stop(&mut self) -> Result<(), BoxError> {
511        // Switch to Stopped first so that the stream is dropped even if stopping it fails.
512        match std::mem::replace(&mut self.state, UnixCaptureStreamState::Stopped) {
513            UnixCaptureStreamState::Started(mut async_stream) => async_stream.stop(),
514            _ => Ok(()),
515        }
516    }
517}
518
519pub(crate) struct UnixBufferWriter {
520    guest_period_bytes: usize,
521}
522
523#[async_trait(?Send)]
524impl PlaybackBufferWriter for UnixBufferWriter {
525    fn new(guest_period_bytes: usize) -> Self {
526        UnixBufferWriter { guest_period_bytes }
527    }
528    fn endpoint_period_bytes(&self) -> usize {
529        self.guest_period_bytes
530    }
531}
532
533pub fn create_jail(
534    params: &Parameters,
535    jail_config: &JailConfig,
536) -> anyhow::Result<Option<Minijail>> {
537    let backend = params.backend;
538    let policy = match backend {
539        Backend::NULL | Backend::FILE => "snd_null_device",
540        #[cfg(feature = "audio_aaudio")]
541        Backend::Sys(StreamSourceBackend::AAUDIO) => "snd_aaudio_device",
542        #[cfg(feature = "audio_cras")]
543        Backend::Sys(StreamSourceBackend::CRAS) => "snd_cras_device",
544        #[cfg(not(any(feature = "audio_cras", feature = "audio_aaudio")))]
545        _ => unreachable!(),
546    };
547
548    let mut config = SandboxConfig::new(jail_config, policy);
549    #[cfg(feature = "audio_cras")]
550    if backend == Backend::Sys(StreamSourceBackend::CRAS) {
551        config.bind_mounts = true;
552    }
553    // TODO(b/267574679): running as current_user may not be required for snd device.
554    config.run_as = RunAsUser::CurrentUser;
555    #[allow(unused_mut)]
556    let mut jail =
557        create_sandbox_minijail(&jail_config.pivot_root, MAX_OPEN_FILES_DEFAULT, &config)?;
558    #[cfg(feature = "audio_cras")]
559    if backend == Backend::Sys(StreamSourceBackend::CRAS) {
560        let run_cras_path = Path::new("/run/cras");
561        jail.mount_bind(run_cras_path, run_cras_path, true)?;
562    }
563    Ok(Some(jail))
564}
565
566#[cfg(test)]
567#[cfg(feature = "audio_aaudio")]
568mod tests {
569    use std::os::unix::io::IntoRawFd;
570
571    use super::*;
572
573    fn setup() -> (FdPermissionDelegate, UnixStream) {
574        let (client, host) = UnixStream::pair().expect("failed to create socketpair");
575        (FdPermissionDelegate::new(client).unwrap(), host)
576    }
577
578    fn read_request(host: &mut UnixStream) {
579        let mut req = [0u8; 1];
580        host.read_exact(&mut req).expect("host failed to read req");
581        assert_eq!(req[0], AudioPermissionRequest::Check.to_wire());
582    }
583
584    fn assert_no_request(host: &mut UnixStream) {
585        host.set_nonblocking(true).unwrap();
586        let err = host.read(&mut [0u8; 1]).unwrap_err();
587        assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
588    }
589
590    /// Sends a request, has the host answer with `resp`, and polls for the answer.
591    fn answer(resp: u8) -> Poll<Result<bool, BoxError>> {
592        let (delegate, mut host) = setup();
593        delegate.request_permission().unwrap();
594        read_request(&mut host);
595        host.write_all(&[resp]).unwrap();
596        delegate.poll_permission()
597    }
598
599    #[test]
600    fn test_permission_delegate_granted() {
601        let resp = answer(AudioPermissionResponse::Granted.to_wire());
602        assert!(matches!(resp, Poll::Ready(Ok(true))));
603    }
604
605    #[test]
606    fn test_permission_delegate_denied() {
607        let resp = answer(AudioPermissionResponse::Denied.to_wire());
608        assert!(matches!(resp, Poll::Ready(Ok(false))));
609    }
610
611    #[test]
612    fn test_permission_delegate_invalid_response() {
613        assert!(matches!(answer(99), Poll::Ready(Err(_))));
614    }
615
616    #[test]
617    fn test_permission_delegate_peer_closed() {
618        let (delegate, mut host) = setup();
619        delegate.request_permission().unwrap();
620        read_request(&mut host);
621        drop(host);
622        assert!(matches!(delegate.poll_permission(), Poll::Ready(Err(_))));
623    }
624
625    #[test]
626    fn test_permission_delegate_pending() {
627        let (delegate, _host) = setup();
628        delegate.request_permission().unwrap();
629        assert!(delegate.poll_permission().is_pending());
630    }
631
632    #[test]
633    fn test_permission_delegate_dedups_requests() {
634        let (delegate, mut host) = setup();
635        delegate.request_permission().unwrap();
636        delegate.request_permission().unwrap();
637        read_request(&mut host);
638        assert_no_request(&mut host);
639    }
640
641    #[test]
642    fn test_permission_delegate_shares_answer() {
643        let (delegate, mut host) = setup();
644        delegate.request_permission().unwrap();
645        read_request(&mut host);
646        host.write_all(&[AudioPermissionResponse::Granted.to_wire()])
647            .unwrap();
648        assert!(matches!(delegate.poll_permission(), Poll::Ready(Ok(true))));
649        // A second stream waiting on the same request gets the same answer.
650        assert!(matches!(delegate.poll_permission(), Poll::Ready(Ok(true))));
651        // The next start() asks again.
652        delegate.request_permission().unwrap();
653        read_request(&mut host);
654    }
655
656    #[test]
657    fn test_permission_delegate_late_answer_applies_to_next_start() {
658        let (delegate, mut host) = setup();
659        delegate.request_permission().unwrap();
660        read_request(&mut host);
661        // The host answers after the stream that asked has stopped.
662        host.write_all(&[AudioPermissionResponse::Denied.to_wire()])
663            .unwrap();
664        // The next start() joins the outstanding request and gets its answer.
665        delegate.request_permission().unwrap();
666        assert_no_request(&mut host);
667        assert!(matches!(delegate.poll_permission(), Poll::Ready(Ok(false))));
668    }
669
670    #[test]
671    fn test_permission_delegate_join_keeps_buffered_answer() {
672        let (delegate, mut host) = setup();
673        delegate.request_permission().unwrap(); // Stream A asks.
674        read_request(&mut host);
675        delegate.request_permission().unwrap(); // Stream B joins.
676        host.write_all(&[AudioPermissionResponse::Granted.to_wire()])
677            .unwrap();
678        // Stream C starts before A or B polls: it must not discard the answer or ask again.
679        delegate.request_permission().unwrap();
680        assert_no_request(&mut host);
681        assert!(matches!(delegate.poll_permission(), Poll::Ready(Ok(true))));
682        // The other waiters get the same answer.
683        assert!(matches!(delegate.poll_permission(), Poll::Ready(Ok(true))));
684    }
685
686    #[test]
687    fn test_permission_delegate_discards_unsolicited_byte() {
688        let (delegate, mut host) = setup();
689        // A byte sent with no request outstanding must not answer the next Check.
690        host.write_all(&[AudioPermissionResponse::Granted.to_wire()])
691            .unwrap();
692        delegate.request_permission().unwrap();
693        read_request(&mut host);
694        assert!(delegate.poll_permission().is_pending());
695        host.write_all(&[AudioPermissionResponse::Denied.to_wire()])
696            .unwrap();
697        assert!(matches!(delegate.poll_permission(), Poll::Ready(Ok(false))));
698    }
699
700    #[test]
701    fn test_create_aaudio_generators_with_and_without_permission_socket() {
702        let mut keep_rds = Vec::new();
703        let params_default = Parameters {
704            backend: Backend::Sys(StreamSourceBackend::AAUDIO),
705            ..Default::default()
706        };
707        let snd_data = crate::common_backend::hardcoded_snd_data(&params_default);
708
709        // Without permission socket
710        let generators =
711            create_aaudio_stream_source_generators(&params_default, &snd_data, &mut keep_rds)
712                .unwrap();
713        assert!(keep_rds.is_empty());
714        assert_eq!(generators.len(), snd_data.pcm_info_len());
715
716        // With permission socket parsed from key-values. Inherited fds are not close-on-exec.
717        let (client, _host) = UnixStream::pair().expect("failed to create socketpair");
718        base::clear_descriptor_cloexec(&client).unwrap();
719        let client_fd = client.into_raw_fd();
720        let params_with_socket: Parameters = serde_keyvalue::from_key_values(&format!(
721            "backend=aaudio,permission_socket_fd={client_fd}"
722        ))
723        .expect("failed to parse Parameters with permission_socket_fd");
724        assert_eq!(params_with_socket.permission_socket_fd, Some(client_fd));
725
726        let generators =
727            create_aaudio_stream_source_generators(&params_with_socket, &snd_data, &mut keep_rds)
728                .unwrap();
729        // The delegate owns a validated duplicate of the fd.
730        assert_eq!(keep_rds.len(), 1);
731        assert_eq!(generators.len(), snd_data.pcm_info_len());
732    }
733}
734
735#[cfg(test)]
736mod capture_tests {
737    use std::io::Read;
738    use std::sync::atomic::AtomicBool;
739    use std::sync::atomic::Ordering;
740    use std::sync::Arc;
741    use std::sync::Mutex;
742    use std::sync::MutexGuard;
743    use std::time::Duration;
744
745    use audio_streams::AudioStreamsExecutor;
746    use audio_streams::NoopStreamControl;
747    use audio_streams::NoopStreamSource;
748    use audio_streams::PlaybackBufferStream;
749    use audio_streams::StreamControl;
750    use cros_async::TimerAsync;
751    use futures::channel::mpsc;
752
753    use super::*;
754    use crate::common_backend::stream_info::SetParams;
755    use crate::constants::VIRTIO_SND_D_INPUT;
756    use crate::constants::VIRTIO_SND_R_PCM_PREPARE;
757
758    const CHANNELS: usize = 2;
759    const FORMAT: SampleFormat = SampleFormat::S16LE;
760    const FRAME_RATE: u32 = 48000;
761    // 1 ms periods keep the paced tests fast.
762    const PERIOD_FRAMES: usize = 48;
763    const FRAME_SIZE: usize = 4;
764    const PERIOD_BYTES: usize = PERIOD_FRAMES * FRAME_SIZE;
765
766    #[derive(Default)]
767    struct Log {
768        create_count: usize,
769        start_count: usize,
770        stop_count: usize,
771        active_streams: usize,
772        events: Vec<&'static str>,
773    }
774
775    #[derive(Clone, Default)]
776    struct Shared {
777        log: Arc<Mutex<Log>>,
778        fail_create: Arc<AtomicBool>,
779    }
780
781    impl Shared {
782        fn log(&self) -> MutexGuard<'_, Log> {
783            self.log.lock().unwrap()
784        }
785    }
786
787    /// Generates `CountingStreamSource`s for `StreamInfo` tests.
788    struct CountingStreamSourceGenerator(Shared);
789
790    impl StreamSourceGenerator for CountingStreamSourceGenerator {
791        fn generate(&self) -> Result<Box<dyn StreamSource>, BoxError> {
792            Ok(Box::new(CountingStreamSource {
793                shared: self.0.clone(),
794                inner: NoopStreamSource::new(),
795            }))
796        }
797    }
798
799    /// Stream source that records capture stream creation and its own drop.
800    struct CountingStreamSource {
801        shared: Shared,
802        inner: NoopStreamSource,
803    }
804
805    impl Drop for CountingStreamSource {
806        fn drop(&mut self) {
807            self.shared.log().events.push("source_drop");
808        }
809    }
810
811    impl StreamSource for CountingStreamSource {
812        fn new_playback_stream(
813            &mut self,
814            num_channels: usize,
815            format: SampleFormat,
816            frame_rate: u32,
817            buffer_size: usize,
818        ) -> Result<(Box<dyn StreamControl>, Box<dyn PlaybackBufferStream>), BoxError> {
819            self.inner
820                .new_playback_stream(num_channels, format, frame_rate, buffer_size)
821        }
822
823        fn new_async_capture_stream(
824            &mut self,
825            num_channels: usize,
826            format: SampleFormat,
827            frame_rate: u32,
828            buffer_size: usize,
829            _effects: &[StreamEffect],
830            _ex: &dyn AudioStreamsExecutor,
831        ) -> Result<(Box<dyn StreamControl>, Box<dyn AsyncCaptureBufferStream>), BoxError> {
832            if self.shared.fail_create.load(Ordering::SeqCst) {
833                return Err("create failed".into());
834            }
835            let mut log = self.shared.log();
836            log.create_count += 1;
837            log.active_streams += 1;
838            Ok((
839                Box::new(NoopStreamControl::new()),
840                Box::new(CountingCaptureStream {
841                    shared: self.shared.clone(),
842                    // Paces periods, so a running PCM worker yields to the executor.
843                    inner: NoopCaptureStream::new(num_channels, format, frame_rate, buffer_size),
844                }),
845            ))
846        }
847    }
848
849    /// Capture stream that records start/stop calls and its drop.
850    struct CountingCaptureStream {
851        shared: Shared,
852        inner: NoopCaptureStream,
853    }
854
855    impl Drop for CountingCaptureStream {
856        fn drop(&mut self) {
857            let mut log = self.shared.log();
858            log.active_streams -= 1;
859            log.events.push("stream_drop");
860        }
861    }
862
863    #[async_trait(?Send)]
864    impl AsyncCaptureBufferStream for CountingCaptureStream {
865        async fn next_capture_buffer<'a>(
866            &'a mut self,
867            ex: &dyn AudioStreamsExecutor,
868        ) -> Result<AsyncCaptureBuffer<'a>, BoxError> {
869            self.inner.next_capture_buffer(ex).await
870        }
871
872        fn start(&mut self) -> Result<(), BoxError> {
873            let mut log = self.shared.log();
874            log.start_count += 1;
875            log.events.push("stream_start");
876            Ok(())
877        }
878
879        fn stop(&mut self) -> Result<(), BoxError> {
880            let mut log = self.shared.log();
881            log.stop_count += 1;
882            log.events.push("stream_stop");
883            Ok(())
884        }
885    }
886
887    fn new_reader(shared: &Shared) -> UnixBufferReader {
888        UnixBufferReader::new(
889            Box::new(CountingStreamSource {
890                shared: shared.clone(),
891                inner: NoopStreamSource::new(),
892            }),
893            CHANNELS,
894            FORMAT,
895            FRAME_RATE,
896            PERIOD_FRAMES,
897            Vec::new(),
898            0,
899        )
900    }
901
902    /// Reads one capture period and returns its bytes.
903    fn read_period(ex: &Executor, reader: &mut UnixBufferReader) -> Result<Vec<u8>, BoxError> {
904        ex.run_until(async {
905            let mut buf = reader.get_next_capture_period(ex).await?;
906            let mut data = vec![0xa5u8; PERIOD_BYTES * 2];
907            let n = buf.read(&mut data)?;
908            data.truncate(n);
909            buf.commit().await;
910            Ok::<_, BoxError>(data)
911        })
912        .unwrap()
913    }
914
915    /// Runs the executor until `cond` holds, or panics after a timeout.
916    fn wait_until(ex: &Executor, shared: &Shared, cond: impl Fn(&Log) -> bool) {
917        let met = ex
918            .run_until(async {
919                for _ in 0..1000 {
920                    if cond(&shared.log()) {
921                        return true;
922                    }
923                    TimerAsync::sleep(ex, Duration::from_millis(2))
924                        .await
925                        .unwrap();
926                }
927                false
928            })
929            .unwrap();
930        assert!(met, "timed out waiting for condition");
931    }
932
933    fn new_prepared_capture_stream(ex: &Executor, shared: &Shared) -> StreamInfo {
934        let mut stream = StreamInfo::builder(
935            Arc::new(Box::new(CountingStreamSourceGenerator(shared.clone()))),
936            0,
937        )
938        .build();
939        ex.run_until(stream.set_params(SetParams {
940            channels: CHANNELS as u8,
941            format: FORMAT,
942            frame_rate: FRAME_RATE,
943            buffer_bytes: PERIOD_BYTES * 4,
944            period_bytes: PERIOD_BYTES,
945            dir: VIRTIO_SND_D_INPUT,
946        }))
947        .unwrap()
948        .unwrap();
949        let (tx_send, _) = mpsc::unbounded();
950        let (rx_send, _) = mpsc::unbounded();
951        ex.run_until(stream.prepare(ex, &tx_send, &rx_send))
952            .unwrap()
953            .unwrap();
954        assert_eq!(stream.state, VIRTIO_SND_R_PCM_PREPARE);
955        stream
956    }
957
958    #[test]
959    fn test_prepare_without_start_does_not_open_capture_stream() {
960        let ex = Executor::new().unwrap();
961        let shared = Shared::default();
962        let mut stream = new_prepared_capture_stream(&ex, &shared);
963
964        // Let the PCM worker run for a few periods.
965        ex.run_until(TimerAsync::sleep(&ex, Duration::from_millis(10)))
966            .unwrap()
967            .unwrap();
968        assert_eq!(shared.log().create_count, 0);
969
970        ex.run_until(stream.release()).unwrap().unwrap();
971        let log = shared.log();
972        assert_eq!(log.create_count, 0);
973        assert_eq!(log.events, ["source_drop"]);
974    }
975
976    #[test]
977    fn test_stream_info_capture_opens_on_start_closes_on_stop() {
978        let ex = Executor::new().unwrap();
979        let shared = Shared::default();
980        let mut stream = new_prepared_capture_stream(&ex, &shared);
981
982        ex.run_until(stream.start()).unwrap().unwrap();
983        wait_until(&ex, &shared, |log| log.active_streams == 1);
984        assert_eq!(shared.log().create_count, 1);
985        assert_eq!(shared.log().start_count, 1);
986
987        ex.run_until(stream.stop()).unwrap().unwrap();
988        wait_until(&ex, &shared, |log| log.active_streams == 0);
989        assert_eq!(shared.log().stop_count, 1);
990
991        // START after STOP, without a new PREPARE, opens a new stream.
992        ex.run_until(stream.start()).unwrap().unwrap();
993        wait_until(&ex, &shared, |log| log.active_streams == 1);
994        assert_eq!(shared.log().create_count, 2);
995
996        ex.run_until(stream.stop()).unwrap().unwrap();
997        ex.run_until(stream.release()).unwrap().unwrap();
998        let log = shared.log();
999        assert_eq!(log.active_streams, 0);
1000        assert_eq!(log.events.last(), Some(&"source_drop"));
1001    }
1002
1003    #[test]
1004    fn test_reader_period_while_stopped_errors_without_opening() {
1005        let ex = Executor::new().unwrap();
1006        let shared = Shared::default();
1007        let mut reader = new_reader(&shared);
1008        assert!(matches!(reader.state, UnixCaptureStreamState::Stopped));
1009
1010        assert!(read_period(&ex, &mut reader).is_err());
1011        assert!(matches!(reader.state, UnixCaptureStreamState::Stopped));
1012        assert_eq!(shared.log().create_count, 0);
1013    }
1014
1015    #[test]
1016    fn test_reader_lazy_lifecycle_start_period_stop() {
1017        let ex = Executor::new().unwrap();
1018        let shared = Shared::default();
1019        let mut reader = new_reader(&shared);
1020        assert!(matches!(reader.state, UnixCaptureStreamState::Stopped));
1021
1022        reader.start().unwrap();
1023        assert!(matches!(reader.state, UnixCaptureStreamState::Starting));
1024        // The stream is only created on the first period.
1025        assert_eq!(shared.log().create_count, 0);
1026
1027        for _ in 0..3 {
1028            let data = read_period(&ex, &mut reader).unwrap();
1029            assert_eq!(data.len(), PERIOD_BYTES);
1030        }
1031        assert!(matches!(reader.state, UnixCaptureStreamState::Started(_)));
1032        {
1033            let log = shared.log();
1034            assert_eq!(log.create_count, 1);
1035            assert_eq!(log.start_count, 1);
1036            assert_eq!(log.active_streams, 1);
1037        }
1038
1039        reader.stop().unwrap();
1040        assert!(matches!(reader.state, UnixCaptureStreamState::Stopped));
1041        let log = shared.log();
1042        assert_eq!(log.active_streams, 0);
1043        assert_eq!(log.events, ["stream_start", "stream_stop", "stream_drop"]);
1044    }
1045
1046    #[test]
1047    fn test_reader_start_is_idempotent() {
1048        let ex = Executor::new().unwrap();
1049        let shared = Shared::default();
1050        let mut reader = new_reader(&shared);
1051
1052        reader.start().unwrap();
1053        read_period(&ex, &mut reader).unwrap();
1054        reader.start().unwrap();
1055        read_period(&ex, &mut reader).unwrap();
1056
1057        let log = shared.log();
1058        assert_eq!(log.create_count, 1);
1059        assert_eq!(log.start_count, 1);
1060    }
1061
1062    #[test]
1063    fn test_reader_restart_reuses_source() {
1064        let ex = Executor::new().unwrap();
1065        let shared = Shared::default();
1066        let mut reader = new_reader(&shared);
1067
1068        for _ in 0..2 {
1069            reader.start().unwrap();
1070            read_period(&ex, &mut reader).unwrap();
1071            reader.stop().unwrap();
1072        }
1073
1074        let log = shared.log();
1075        assert_eq!(log.create_count, 2);
1076        assert_eq!(log.active_streams, 0);
1077        assert!(!log.events.contains(&"source_drop"));
1078    }
1079
1080    #[test]
1081    fn test_reader_create_failure_falls_back_to_silence() {
1082        let ex = Executor::new().unwrap();
1083        let shared = Shared::default();
1084        let mut reader = new_reader(&shared);
1085
1086        shared.fail_create.store(true, Ordering::SeqCst);
1087        reader.start().unwrap();
1088        assert!(matches!(reader.state, UnixCaptureStreamState::Starting));
1089        for _ in 0..2 {
1090            let data = read_period(&ex, &mut reader).unwrap();
1091            assert_eq!(data.len(), PERIOD_BYTES);
1092            assert!(data.iter().all(|&b| b == 0));
1093        }
1094        assert!(matches!(
1095            reader.state,
1096            UnixCaptureStreamState::StartFailed(_)
1097        ));
1098        assert_eq!(shared.log().create_count, 0);
1099
1100        // The next START retries.
1101        shared.fail_create.store(false, Ordering::SeqCst);
1102        reader.stop().unwrap();
1103        assert!(matches!(reader.state, UnixCaptureStreamState::Stopped));
1104        reader.start().unwrap();
1105        assert!(matches!(reader.state, UnixCaptureStreamState::Starting));
1106        read_period(&ex, &mut reader).unwrap();
1107        assert!(matches!(reader.state, UnixCaptureStreamState::Started(_)));
1108        let log = shared.log();
1109        assert_eq!(log.create_count, 1);
1110        assert_eq!(log.active_streams, 1);
1111    }
1112
1113    #[test]
1114    fn test_reader_drop_while_started_drops_stream_before_source() {
1115        let ex = Executor::new().unwrap();
1116        let shared = Shared::default();
1117        let mut reader = new_reader(&shared);
1118
1119        reader.start().unwrap();
1120        read_period(&ex, &mut reader).unwrap();
1121        drop(reader);
1122
1123        let log = shared.log();
1124        assert_eq!(log.stop_count, 0);
1125        assert_eq!(log.events, ["stream_start", "stream_drop", "source_drop"]);
1126    }
1127}