device_virtio_snd/common_backend/
mod.rs

1// Copyright 2021 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// virtio-sound spec: https://github.com/oasis-tcs/virtio-spec/blob/master/virtio-sound.tex
6
7use std::collections::BTreeMap;
8use std::io;
9use std::rc::Rc;
10use std::sync::Arc;
11
12use anyhow::anyhow;
13use anyhow::Context;
14use audio_streams::BoxError;
15use base::debug;
16use base::error;
17use base::warn;
18use base::AsRawDescriptor;
19use base::Descriptor;
20use base::Error as SysError;
21use base::Event;
22use base::RawDescriptor;
23use base::Tube;
24use base::WorkerThread;
25use cros_async::block_on;
26use cros_async::sync::Condvar;
27use cros_async::sync::RwLock as AsyncRwLock;
28use cros_async::AsyncError;
29use cros_async::AsyncTube;
30use cros_async::EventAsync;
31use cros_async::Executor;
32use devices::virtio::async_utils;
33use devices::virtio::copy_config;
34use devices::virtio::device_constants::snd::virtio_snd_config;
35use devices::virtio::DescriptorChain;
36use devices::virtio::DeviceType;
37use devices::virtio::Interrupt;
38use devices::virtio::Queue;
39use devices::virtio::VirtioDevice;
40use futures::channel::mpsc;
41use futures::channel::oneshot;
42use futures::channel::oneshot::Canceled;
43use futures::future::FusedFuture;
44use futures::join;
45use futures::pin_mut;
46use futures::select;
47use futures::FutureExt;
48use serde::Deserialize;
49use serde::Serialize;
50use snapshot::AnySnapshot;
51use thiserror::Error as ThisError;
52use vm_memory::GuestMemory;
53use zerocopy::IntoBytes;
54
55use crate::common_backend::async_funcs::*;
56use crate::common_backend::stream_info::StreamInfo;
57use crate::common_backend::stream_info::StreamInfoBuilder;
58use crate::common_backend::stream_info::StreamInfoSnapshot;
59use crate::constants::*;
60use crate::file_backend::create_file_stream_source_generators;
61use crate::file_backend::Error as FileError;
62use crate::layout::*;
63use crate::null_backend::create_null_stream_source_generators;
64use crate::parameters::Parameters;
65use crate::parameters::StreamSourceBackend;
66use crate::sys::create_stream_source_generators as sys_create_stream_source_generators;
67use crate::sys::set_audio_thread_priority;
68use crate::sys::SysAsyncStreamObjects;
69use crate::sys::SysAudioStreamSourceGenerator;
70use crate::sys::SysDirectionOutput;
71
72pub mod async_funcs;
73pub mod stream_info;
74pub mod validation;
75
76// control + event + tx + rx queue
77pub const MAX_QUEUE_NUM: usize = 4;
78pub const MAX_VRING_LEN: u16 = 1024;
79
80#[derive(ThisError, Debug)]
81pub enum Error {
82    /// next_async failed.
83    #[error("Failed to read descriptor asynchronously: {0}")]
84    Async(AsyncError),
85    /// Creating stream failed.
86    #[error("Failed to create stream: {0}")]
87    CreateStream(BoxError),
88    /// Creating stream failed.
89    #[error("No stream source found.")]
90    EmptyStreamSource,
91    /// Creating kill event failed.
92    #[error("Failed to create kill event: {0}")]
93    CreateKillEvent(SysError),
94    /// Creating WaitContext failed.
95    #[error("Failed to create wait context: {0}")]
96    CreateWaitContext(SysError),
97    #[error("Failed to create file stream source generator")]
98    CreateFileStreamSourceGenerator(FileError),
99    /// The audio permission socket fd is invalid.
100    #[error("Invalid audio permission socket: {0}")]
101    PermissionSocket(io::Error),
102    /// Cloning kill event failed.
103    #[error("Failed to clone kill event: {0}")]
104    CloneKillEvent(SysError),
105    // Future error.
106    #[error("Unexpected error. Done was not triggered before dropped: {0}")]
107    DoneNotTriggered(Canceled),
108    /// Error reading message from queue.
109    #[error("Failed to read message: {0}")]
110    ReadMessage(io::Error),
111    /// Failed writing a response to a control message.
112    #[error("Failed to write message response: {0}")]
113    WriteResponse(io::Error),
114    // Mpsc read error.
115    #[error("Error in mpsc: {0}")]
116    MpscSend(futures::channel::mpsc::SendError),
117    // Oneshot send error.
118    #[error("Error in oneshot send")]
119    OneshotSend(()),
120    /// Failure in communicating with the host
121    #[error("Failed to send/receive to/from control tube")]
122    ControlTubeError(base::TubeError),
123    /// Stream not found.
124    #[error("stream id ({0}) < num_streams ({1})")]
125    StreamNotFound(usize, usize),
126    /// Fetch buffer error
127    #[error("Failed to get buffer from CRAS: {0}")]
128    FetchBuffer(BoxError),
129    /// Invalid buffer size
130    #[error("Invalid buffer size")]
131    InvalidBufferSize,
132    /// IoError
133    #[error("I/O failed: {0}")]
134    Io(io::Error),
135    /// Operation not supported.
136    #[error("Operation not supported")]
137    OperationNotSupported,
138    /// Writing to a buffer in the guest failed.
139    #[error("failed to write to buffer: {0}")]
140    WriteBuffer(io::Error),
141    // Invalid PCM worker state.
142    #[error("Invalid PCM worker state")]
143    InvalidPCMWorkerState,
144    // Invalid backend.
145    #[error("Backend is not implemented")]
146    InvalidBackend,
147    // Failed to generate StreamSource
148    #[error("Failed to generate stream source: {0}")]
149    GenerateStreamSource(BoxError),
150    // PCM worker unexpectedly quitted.
151    #[error("PCM worker quitted unexpectedly")]
152    PCMWorkerQuittedUnexpectedly,
153}
154
155pub enum DirectionalStream {
156    Input(
157        usize, // `period_size` in `usize`
158        Box<dyn CaptureBufferReader>,
159    ),
160    Output(SysDirectionOutput),
161}
162
163#[derive(Copy, Clone, std::cmp::PartialEq, Eq)]
164pub enum WorkerStatus {
165    Pause = 0,
166    Running = 1,
167    Quit = 2,
168}
169
170// Stores constant data
171#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
172pub struct SndData {
173    pub(crate) jack_info: Vec<virtio_snd_jack_info>,
174    pub(crate) pcm_info: Vec<virtio_snd_pcm_info>,
175    pub(crate) chmap_info: Vec<virtio_snd_chmap_info>,
176}
177
178impl SndData {
179    pub fn pcm_info_len(&self) -> usize {
180        self.pcm_info.len()
181    }
182
183    pub fn pcm_info_iter(&self) -> std::slice::Iter<'_, virtio_snd_pcm_info> {
184        self.pcm_info.iter()
185    }
186}
187
188pub(crate) const SUPPORTED_FORMATS: u64 = 1 << VIRTIO_SND_PCM_FMT_U8
189    | 1 << VIRTIO_SND_PCM_FMT_S16
190    | 1 << VIRTIO_SND_PCM_FMT_S24
191    | 1 << VIRTIO_SND_PCM_FMT_S32;
192pub(crate) const SUPPORTED_FRAME_RATES: u64 = 1 << VIRTIO_SND_PCM_RATE_8000
193    | 1 << VIRTIO_SND_PCM_RATE_11025
194    | 1 << VIRTIO_SND_PCM_RATE_16000
195    | 1 << VIRTIO_SND_PCM_RATE_22050
196    | 1 << VIRTIO_SND_PCM_RATE_32000
197    | 1 << VIRTIO_SND_PCM_RATE_44100
198    | 1 << VIRTIO_SND_PCM_RATE_48000;
199// AAudio has no 8-bit format, and AAUDIO_FORMAT_PCM_I32 is full scale, so S24 (24 bits in a
200// 32-bit container) would need a shift. The guest converts U8/S24 instead. S32 is advertised
201// along with S16 so 24/32-bit guest audio isn't truncated to 16 bits; AAudio maps it to PCM_I32
202// and AudioFlinger converts if the device path is 16-bit.
203#[cfg(all(unix, feature = "audio_aaudio"))]
204const AAUDIO_SUPPORTED_FORMATS: u64 = 1 << VIRTIO_SND_PCM_FMT_S16 | 1 << VIRTIO_SND_PCM_FMT_S32;
205
206/// Returns the PCM formats to advertise for `backend`.
207#[cfg_attr(not(all(unix, feature = "audio_aaudio")), allow(unused_variables))]
208fn supported_formats(backend: StreamSourceBackend) -> u64 {
209    #[cfg(all(unix, feature = "audio_aaudio"))]
210    if backend == StreamSourceBackend::Sys(crate::sys::StreamSourceBackend::AAUDIO) {
211        return AAUDIO_SUPPORTED_FORMATS;
212    }
213    SUPPORTED_FORMATS
214}
215
216// Response from pcm_worker to pcm_queue
217pub struct PcmResponse {
218    pub(crate) desc_chain: DescriptorChain,
219    pub(crate) status: virtio_snd_pcm_status, // response to the pcm message
220    pub(crate) done: Option<oneshot::Sender<()>>, // when pcm response is written to the queue
221}
222
223pub struct VirtioSnd {
224    control_tube: Option<Tube>,
225    cfg: virtio_snd_config,
226    snd_data: SndData,
227    stream_info_builders: Vec<StreamInfoBuilder>,
228    avail_features: u64,
229    acked_features: u64,
230    queue_sizes: Box<[u16]>,
231    worker_thread: Option<WorkerThread<WorkerReturn>>,
232    keep_rds: Vec<Descriptor>,
233    streams_state: Option<Vec<StreamInfoSnapshot>>,
234    card_index: usize,
235}
236
237#[derive(Serialize, Deserialize)]
238struct VirtioSndSnapshot {
239    avail_features: u64,
240    acked_features: u64,
241    queue_sizes: Vec<u16>,
242    streams_state: Option<Vec<StreamInfoSnapshot>>,
243    snd_data: SndData,
244}
245
246impl VirtioSnd {
247    pub fn new(
248        base_features: u64,
249        params: Parameters,
250        control_tube: Tube,
251    ) -> Result<VirtioSnd, Error> {
252        let params = resize_parameters_pcm_device_config(params);
253        let cfg = hardcoded_virtio_snd_config(&params);
254        let snd_data = hardcoded_snd_data(&params);
255        let avail_features = base_features;
256        let mut keep_rds: Vec<RawDescriptor> = Vec::new();
257        keep_rds.push(control_tube.as_raw_descriptor());
258
259        let stream_info_builders =
260            create_stream_info_builders(&params, &snd_data, &mut keep_rds, params.card_index)?;
261
262        Ok(VirtioSnd {
263            control_tube: Some(control_tube),
264            cfg,
265            snd_data,
266            stream_info_builders,
267            avail_features,
268            acked_features: 0,
269            queue_sizes: vec![MAX_VRING_LEN; MAX_QUEUE_NUM].into_boxed_slice(),
270            worker_thread: None,
271            keep_rds: keep_rds.iter().map(|rd| Descriptor(*rd)).collect(),
272            streams_state: None,
273            card_index: params.card_index,
274        })
275    }
276}
277
278fn create_stream_source_generators(
279    params: &Parameters,
280    snd_data: &SndData,
281    keep_rds: &mut Vec<RawDescriptor>,
282) -> Result<Vec<SysAudioStreamSourceGenerator>, Error> {
283    let generators = match params.backend {
284        StreamSourceBackend::NULL => create_null_stream_source_generators(snd_data),
285        StreamSourceBackend::FILE => {
286            create_file_stream_source_generators(params, snd_data, keep_rds)
287                .map_err(Error::CreateFileStreamSourceGenerator)?
288        }
289        StreamSourceBackend::Sys(backend) => {
290            sys_create_stream_source_generators(backend, params, snd_data, keep_rds)?
291        }
292    };
293    Ok(generators)
294}
295
296/// Creates [`StreamInfoBuilder`]s by calling [`create_stream_source_generators()`] then zip
297/// them with [`crate::parameters::PCMDeviceParameters`] from the params to set
298/// the parameters on each [`StreamInfoBuilder`] (e.g. effects).
299pub(crate) fn create_stream_info_builders(
300    params: &Parameters,
301    snd_data: &SndData,
302    keep_rds: &mut Vec<RawDescriptor>,
303    card_index: usize,
304) -> Result<Vec<StreamInfoBuilder>, Error> {
305    Ok(create_stream_source_generators(params, snd_data, keep_rds)?
306        .into_iter()
307        .map(Arc::new)
308        .zip(snd_data.pcm_info_iter())
309        .map(|(generator, pcm_info)| {
310            let device_params = params.get_device_params(pcm_info).unwrap_or_default();
311            StreamInfo::builder(generator, card_index)
312                .effects(device_params.effects.unwrap_or_default())
313        })
314        .collect())
315}
316
317// To be used with hardcoded_snd_data
318pub fn hardcoded_virtio_snd_config(params: &Parameters) -> virtio_snd_config {
319    virtio_snd_config {
320        jacks: 0.into(),
321        streams: params.get_total_streams().into(),
322        chmaps: (params.num_output_devices * 3 + params.num_input_devices).into(),
323        controls: 0.into(),
324    }
325}
326
327// To be used with hardcoded_virtio_snd_config
328pub fn hardcoded_snd_data(params: &Parameters) -> SndData {
329    let jack_info: Vec<virtio_snd_jack_info> = Vec::new();
330    let mut pcm_info: Vec<virtio_snd_pcm_info> = Vec::new();
331    let mut chmap_info: Vec<virtio_snd_chmap_info> = Vec::new();
332    let formats = supported_formats(params.backend);
333
334    for dev in 0..params.num_output_devices {
335        for _ in 0..params.num_output_streams {
336            pcm_info.push(virtio_snd_pcm_info {
337                hdr: virtio_snd_info {
338                    hda_fn_nid: dev.into(),
339                },
340                features: 0.into(), /* 1 << VIRTIO_SND_PCM_F_XXX */
341                formats: formats.into(),
342                rates: SUPPORTED_FRAME_RATES.into(),
343                direction: VIRTIO_SND_D_OUTPUT,
344                channels_min: 1,
345                channels_max: 6,
346                padding: [0; 5],
347            });
348        }
349    }
350    for dev in 0..params.num_input_devices {
351        for _ in 0..params.num_input_streams {
352            pcm_info.push(virtio_snd_pcm_info {
353                hdr: virtio_snd_info {
354                    hda_fn_nid: dev.into(),
355                },
356                features: 0.into(), /* 1 << VIRTIO_SND_PCM_F_XXX */
357                formats: formats.into(),
358                rates: SUPPORTED_FRAME_RATES.into(),
359                direction: VIRTIO_SND_D_INPUT,
360                channels_min: 1,
361                channels_max: 2,
362                padding: [0; 5],
363            });
364        }
365    }
366    // Use stereo channel map.
367    let mut positions = [VIRTIO_SND_CHMAP_NONE; VIRTIO_SND_CHMAP_MAX_SIZE];
368    positions[0] = VIRTIO_SND_CHMAP_FL;
369    positions[1] = VIRTIO_SND_CHMAP_FR;
370    for dev in 0..params.num_output_devices {
371        chmap_info.push(virtio_snd_chmap_info {
372            hdr: virtio_snd_info {
373                hda_fn_nid: dev.into(),
374            },
375            direction: VIRTIO_SND_D_OUTPUT,
376            channels: 2,
377            positions,
378        });
379    }
380    for dev in 0..params.num_input_devices {
381        chmap_info.push(virtio_snd_chmap_info {
382            hdr: virtio_snd_info {
383                hda_fn_nid: dev.into(),
384            },
385            direction: VIRTIO_SND_D_INPUT,
386            channels: 2,
387            positions,
388        });
389    }
390    positions[2] = VIRTIO_SND_CHMAP_RL;
391    positions[3] = VIRTIO_SND_CHMAP_RR;
392    for dev in 0..params.num_output_devices {
393        chmap_info.push(virtio_snd_chmap_info {
394            hdr: virtio_snd_info {
395                hda_fn_nid: dev.into(),
396            },
397            direction: VIRTIO_SND_D_OUTPUT,
398            channels: 4,
399            positions,
400        });
401    }
402    positions[2] = VIRTIO_SND_CHMAP_FC;
403    positions[3] = VIRTIO_SND_CHMAP_LFE;
404    positions[4] = VIRTIO_SND_CHMAP_RL;
405    positions[5] = VIRTIO_SND_CHMAP_RR;
406    for dev in 0..params.num_output_devices {
407        chmap_info.push(virtio_snd_chmap_info {
408            hdr: virtio_snd_info {
409                hda_fn_nid: dev.into(),
410            },
411            direction: VIRTIO_SND_D_OUTPUT,
412            channels: 6,
413            positions,
414        });
415    }
416
417    SndData {
418        jack_info,
419        pcm_info,
420        chmap_info,
421    }
422}
423
424fn resize_parameters_pcm_device_config(mut params: Parameters) -> Parameters {
425    if params.output_device_config.len() > params.num_output_devices as usize {
426        warn!("Truncating output device config due to length > number of output devices");
427    }
428    params
429        .output_device_config
430        .resize_with(params.num_output_devices as usize, Default::default);
431
432    if params.input_device_config.len() > params.num_input_devices as usize {
433        warn!("Truncating input device config due to length > number of input devices");
434    }
435    params
436        .input_device_config
437        .resize_with(params.num_input_devices as usize, Default::default);
438
439    params
440}
441
442impl VirtioDevice for VirtioSnd {
443    fn keep_rds(&self) -> Vec<RawDescriptor> {
444        self.keep_rds
445            .iter()
446            .map(|descr| descr.as_raw_descriptor())
447            .collect()
448    }
449
450    fn device_type(&self) -> DeviceType {
451        DeviceType::Sound
452    }
453
454    fn queue_max_sizes(&self) -> &[u16] {
455        &self.queue_sizes
456    }
457
458    fn features(&self) -> u64 {
459        self.avail_features
460    }
461
462    fn ack_features(&mut self, mut v: u64) {
463        // Check if the guest is ACK'ing a feature that we didn't claim to have.
464        let unrequested_features = v & !self.avail_features;
465        if unrequested_features != 0 {
466            warn!("virtio_fs got unknown feature ack: {:x}", v);
467
468            // Don't count these features as acked.
469            v &= !unrequested_features;
470        }
471        self.acked_features |= v;
472    }
473
474    fn read_config(&self, offset: u64, data: &mut [u8]) {
475        copy_config(data, 0, self.cfg.as_bytes(), offset)
476    }
477
478    fn activate(
479        &mut self,
480        _guest_mem: GuestMemory,
481        _interrupt: Interrupt,
482        queues: BTreeMap<usize, Queue>,
483    ) -> anyhow::Result<()> {
484        if queues.len() != self.queue_sizes.len() {
485            return Err(anyhow!(
486                "snd: expected {} queues, got {}",
487                self.queue_sizes.len(),
488                queues.len()
489            ));
490        }
491
492        let snd_data = self.snd_data.clone();
493        let stream_info_builders = self.stream_info_builders.to_vec();
494        let streams_state = self.streams_state.take();
495        let card_index = self.card_index;
496        let control_tube = self.control_tube.take().unwrap();
497        self.worker_thread = Some(WorkerThread::start("v_snd_common", move |kill_evt| {
498            let _thread_priority_handle = set_audio_thread_priority();
499            if let Err(e) = _thread_priority_handle {
500                warn!("Failed to set audio thread to real time: {}", e);
501            };
502            run_worker(
503                queues,
504                snd_data,
505                kill_evt,
506                stream_info_builders,
507                streams_state,
508                card_index,
509                control_tube,
510            )
511        }));
512
513        Ok(())
514    }
515
516    fn reset(&mut self) -> anyhow::Result<()> {
517        if let Some(worker_thread) = self.worker_thread.take() {
518            let worker = worker_thread.stop();
519            self.control_tube = Some(worker.control_tube);
520        }
521
522        Ok(())
523    }
524
525    fn virtio_sleep(&mut self) -> anyhow::Result<Option<BTreeMap<usize, Queue>>> {
526        if let Some(worker_thread) = self.worker_thread.take() {
527            let worker = worker_thread.stop();
528            self.control_tube = Some(worker.control_tube);
529            self.snd_data = worker.snd_data;
530            self.streams_state = Some(worker.streams_state);
531            return Ok(Some(BTreeMap::from_iter(
532                worker.queues.into_iter().enumerate(),
533            )));
534        }
535        Ok(None)
536    }
537
538    fn virtio_wake(
539        &mut self,
540        device_state: Option<(GuestMemory, Interrupt, BTreeMap<usize, Queue>)>,
541    ) -> anyhow::Result<()> {
542        match device_state {
543            None => Ok(()),
544            Some((mem, interrupt, queues)) => {
545                // TODO: activate is just what we want at the moment, but we should probably move
546                // it into a "start workers" function to make it obvious that it isn't strictly
547                // used for activate events.
548                self.activate(mem, interrupt, queues)?;
549                Ok(())
550            }
551        }
552    }
553
554    fn virtio_snapshot(&mut self) -> anyhow::Result<AnySnapshot> {
555        let streams_state = if let Some(states) = &self.streams_state {
556            let mut state_vec = Vec::new();
557            for state in states {
558                state_vec.push(state.clone());
559            }
560            Some(state_vec)
561        } else {
562            None
563        };
564        AnySnapshot::to_any(VirtioSndSnapshot {
565            avail_features: self.avail_features,
566            acked_features: self.acked_features,
567            queue_sizes: self.queue_sizes.to_vec(),
568            streams_state,
569            snd_data: self.snd_data.clone(),
570        })
571        .context("failed to Serialize Sound device")
572    }
573
574    fn virtio_restore(&mut self, data: AnySnapshot) -> anyhow::Result<()> {
575        let mut deser: VirtioSndSnapshot =
576            AnySnapshot::from_any(data).context("failed to Deserialize Sound device")?;
577        anyhow::ensure!(
578            deser.avail_features == self.avail_features,
579            "avail features doesn't match on restore: expected: {}, got: {}",
580            deser.avail_features,
581            self.avail_features
582        );
583        anyhow::ensure!(
584            deser.queue_sizes == self.queue_sizes.to_vec(),
585            "queue sizes doesn't match on restore: expected: {:?}, got: {:?}",
586            deser.queue_sizes,
587            self.queue_sizes.to_vec()
588        );
589        self.acked_features = deser.acked_features;
590        anyhow::ensure!(
591            deser.snd_data == self.snd_data,
592            "snd data doesn't match on restore: expected: {:?}, got: {:?}",
593            deser.snd_data,
594            self.snd_data
595        );
596        self.acked_features = deser.acked_features;
597        self.streams_state = deser.streams_state.take();
598        Ok(())
599    }
600}
601
602#[derive(PartialEq)]
603enum LoopState {
604    Continue,
605    Break,
606}
607
608fn run_worker(
609    queues: BTreeMap<usize, Queue>,
610    snd_data: SndData,
611    kill_evt: Event,
612    stream_info_builders: Vec<StreamInfoBuilder>,
613    streams_state: Option<Vec<StreamInfoSnapshot>>,
614    card_index: usize,
615    control_tube: Tube,
616) -> WorkerReturn {
617    let ex = Executor::new().expect("Failed to create an executor");
618    let control_tube = AsyncTube::new(&ex, control_tube).expect("failed to create async snd tube");
619
620    if snd_data.pcm_info_len() != stream_info_builders.len() {
621        error!(
622            "snd: expected {} streams, got {}",
623            snd_data.pcm_info_len(),
624            stream_info_builders.len(),
625        );
626    }
627    let streams: Vec<AsyncRwLock<StreamInfo>> = stream_info_builders
628        .into_iter()
629        .map(StreamInfoBuilder::build)
630        .map(AsyncRwLock::new)
631        .collect();
632
633    let (tx_send, mut tx_recv) = mpsc::unbounded();
634    let (rx_send, mut rx_recv) = mpsc::unbounded();
635    let tx_send_clone = tx_send.clone();
636    let rx_send_clone = rx_send.clone();
637    let restore_task = ex.spawn_local(async move {
638        if let Some(states) = &streams_state {
639            let ex = Executor::new().expect("Failed to create an executor");
640            for (stream, state) in streams.iter().zip(states.iter()) {
641                stream.lock().await.restore(state);
642                if state.state == VIRTIO_SND_R_PCM_START || state.state == VIRTIO_SND_R_PCM_PREPARE
643                {
644                    stream
645                        .lock()
646                        .await
647                        .prepare(&ex, &tx_send_clone, &rx_send_clone)
648                        .await
649                        .expect("failed to prepare PCM");
650                }
651                if state.state == VIRTIO_SND_R_PCM_START {
652                    stream
653                        .lock()
654                        .await
655                        .start()
656                        .await
657                        .expect("failed to start PCM");
658                }
659            }
660        }
661        streams
662    });
663    let streams = ex
664        .run_until(restore_task)
665        .expect("failed to restore streams");
666    let streams = Rc::new(AsyncRwLock::new(streams));
667
668    let mut queues: Vec<(Queue, EventAsync)> = queues
669        .into_values()
670        .map(|q| {
671            let e = q.event().try_clone().expect("Failed to clone queue event");
672            (
673                q,
674                EventAsync::new(e, &ex).expect("Failed to create async event for queue"),
675            )
676        })
677        .collect();
678
679    let (ctrl_queue, mut ctrl_queue_evt) = queues.remove(0);
680    let ctrl_queue = Rc::new(AsyncRwLock::new(ctrl_queue));
681    let (_event_queue, _event_queue_evt) = queues.remove(0);
682    let (tx_queue, tx_queue_evt) = queues.remove(0);
683    let (rx_queue, rx_queue_evt) = queues.remove(0);
684
685    let tx_queue = Rc::new(AsyncRwLock::new(tx_queue));
686    let rx_queue = Rc::new(AsyncRwLock::new(rx_queue));
687
688    // Exit if the kill event is triggered.
689    let f_kill = async_utils::await_and_exit(&ex, kill_evt).fuse();
690
691    pin_mut!(f_kill);
692
693    loop {
694        if run_worker_once(
695            &ex,
696            &streams,
697            &snd_data,
698            &mut f_kill,
699            ctrl_queue.clone(),
700            &mut ctrl_queue_evt,
701            tx_queue.clone(),
702            &tx_queue_evt,
703            tx_send.clone(),
704            &mut tx_recv,
705            rx_queue.clone(),
706            &rx_queue_evt,
707            rx_send.clone(),
708            &mut rx_recv,
709            card_index,
710            &control_tube,
711        ) == LoopState::Break
712        {
713            break;
714        }
715
716        if let Err(e) = reset_streams(
717            &ex,
718            &streams,
719            &tx_queue,
720            &mut tx_recv,
721            &rx_queue,
722            &mut rx_recv,
723        ) {
724            error!("Error reset streams: {}", e);
725            break;
726        }
727    }
728    let streams_state_task = ex.spawn_local(async move {
729        let mut v = Vec::new();
730        for stream in streams.read_lock().await.iter() {
731            v.push(stream.read_lock().await.snapshot());
732        }
733        v
734    });
735    let streams_state = ex
736        .run_until(streams_state_task)
737        .expect("failed to save streams state");
738    let ctrl_queue = match Rc::try_unwrap(ctrl_queue) {
739        Ok(q) => q.into_inner(),
740        Err(_) => panic!("Too many refs to ctrl_queue"),
741    };
742    let tx_queue = match Rc::try_unwrap(tx_queue) {
743        Ok(q) => q.into_inner(),
744        Err(_) => panic!("Too many refs to tx_queue"),
745    };
746    let rx_queue = match Rc::try_unwrap(rx_queue) {
747        Ok(q) => q.into_inner(),
748        Err(_) => panic!("Too many refs to rx_queue"),
749    };
750    let queues = vec![ctrl_queue, _event_queue, tx_queue, rx_queue];
751
752    WorkerReturn {
753        control_tube: control_tube.into(),
754        queues,
755        snd_data,
756        streams_state,
757    }
758}
759
760struct WorkerReturn {
761    control_tube: Tube,
762    queues: Vec<Queue>,
763    snd_data: SndData,
764    streams_state: Vec<StreamInfoSnapshot>,
765}
766
767async fn notify_reset_signal(reset_signal: &(AsyncRwLock<bool>, Condvar)) {
768    let (lock, cvar) = reset_signal;
769    *lock.lock().await = true;
770    cvar.notify_all();
771}
772
773/// Runs all workers once and exit if any worker exit.
774///
775/// Returns [`LoopState::Break`] if the worker `f_kill` exits, or something went
776/// wrong on shutdown process. The caller should not run the worker again and should exit the main
777/// loop.
778///
779/// If this function returns [`LoopState::Continue`], the caller can continue the main loop by
780/// resetting the streams and run the worker again.
781fn run_worker_once(
782    ex: &Executor,
783    streams: &Rc<AsyncRwLock<Vec<AsyncRwLock<StreamInfo>>>>,
784    snd_data: &SndData,
785    mut f_kill: &mut (impl FusedFuture<Output = anyhow::Result<()>> + Unpin),
786    ctrl_queue: Rc<AsyncRwLock<Queue>>,
787    ctrl_queue_evt: &mut EventAsync,
788    tx_queue: Rc<AsyncRwLock<Queue>>,
789    tx_queue_evt: &EventAsync,
790    tx_send: mpsc::UnboundedSender<PcmResponse>,
791    tx_recv: &mut mpsc::UnboundedReceiver<PcmResponse>,
792    rx_queue: Rc<AsyncRwLock<Queue>>,
793    rx_queue_evt: &EventAsync,
794    rx_send: mpsc::UnboundedSender<PcmResponse>,
795    rx_recv: &mut mpsc::UnboundedReceiver<PcmResponse>,
796    card_index: usize,
797    control_tube: &AsyncTube,
798) -> LoopState {
799    let tx_send2 = tx_send.clone();
800    let rx_send2 = rx_send.clone();
801
802    let reset_signal = (AsyncRwLock::new(false), Condvar::new());
803
804    let f_host_ctrl = handle_ctrl_tube(streams, control_tube, Some(&reset_signal)).fuse();
805
806    let f_ctrl = handle_ctrl_queue(
807        ex,
808        streams,
809        snd_data,
810        ctrl_queue,
811        ctrl_queue_evt,
812        tx_send,
813        rx_send,
814        card_index,
815        Some(&reset_signal),
816    )
817    .fuse();
818
819    // TODO(woodychow): Enable this when libcras sends jack connect/disconnect evts
820    // let f_event = handle_event_queue(
821    //     snd_state,
822    //     event_queue,
823    //     event_queue_evt,
824    // );
825    let f_tx = handle_pcm_queue(
826        streams,
827        tx_send2,
828        tx_queue.clone(),
829        tx_queue_evt,
830        card_index,
831        Some(&reset_signal),
832    )
833    .fuse();
834    let f_tx_response = send_pcm_response_worker(tx_queue, tx_recv, Some(&reset_signal)).fuse();
835    let f_rx = handle_pcm_queue(
836        streams,
837        rx_send2,
838        rx_queue.clone(),
839        rx_queue_evt,
840        card_index,
841        Some(&reset_signal),
842    )
843    .fuse();
844    let f_rx_response = send_pcm_response_worker(rx_queue, rx_recv, Some(&reset_signal)).fuse();
845
846    pin_mut!(
847        f_host_ctrl,
848        f_ctrl,
849        f_tx,
850        f_tx_response,
851        f_rx,
852        f_rx_response
853    );
854
855    let done = async {
856        select! {
857            res = f_host_ctrl => (res.context("error in handling host control command"), LoopState::Continue),
858            res = f_ctrl => (res.context("error in handling ctrl queue"), LoopState::Continue),
859            res = f_tx => (res.context("error in handling tx queue"), LoopState::Continue),
860            res = f_tx_response => (res.context("error in handling tx response"), LoopState::Continue),
861            res = f_rx => (res.context("error in handling rx queue"), LoopState::Continue),
862            res = f_rx_response => (res.context("error in handling rx response"), LoopState::Continue),
863
864            // For following workers, do not continue the loop
865            res = f_kill => (res.context("error in await_and_exit"), LoopState::Break),
866        }
867    };
868
869    match ex.run_until(done) {
870        Ok((res, loop_state)) => {
871            if let Err(e) = res {
872                error!("Error in worker: {:#}", e);
873            }
874            if loop_state == LoopState::Break {
875                return LoopState::Break;
876            }
877        }
878        Err(e) => {
879            error!("Error happened in executor: {}", e);
880        }
881    }
882
883    warn!("Shutting down all workers for reset procedure");
884    block_on(notify_reset_signal(&reset_signal));
885
886    let shutdown = async {
887        loop {
888            let (res, worker_name) = select!(
889                res = f_ctrl => (res, "f_ctrl"),
890                res = f_tx => (res, "f_tx"),
891                res = f_tx_response => (res, "f_tx_response"),
892                res = f_rx => (res, "f_rx"),
893                res = f_rx_response => (res, "f_rx_response"),
894                complete => break,
895            );
896            match res {
897                Ok(_) => debug!("Worker {} stopped", worker_name),
898                Err(e) => error!("Worker {} stopped with error {}", worker_name, e),
899            };
900        }
901    };
902
903    if let Err(e) = ex.run_until(shutdown) {
904        error!("Error happened in executor while shutdown: {}", e);
905        return LoopState::Break;
906    }
907
908    LoopState::Continue
909}
910
911fn reset_streams(
912    ex: &Executor,
913    streams: &Rc<AsyncRwLock<Vec<AsyncRwLock<StreamInfo>>>>,
914    tx_queue: &Rc<AsyncRwLock<Queue>>,
915    tx_recv: &mut mpsc::UnboundedReceiver<PcmResponse>,
916    rx_queue: &Rc<AsyncRwLock<Queue>>,
917    rx_recv: &mut mpsc::UnboundedReceiver<PcmResponse>,
918) -> Result<(), AsyncError> {
919    let reset_signal = (AsyncRwLock::new(false), Condvar::new());
920
921    let do_reset = async {
922        let streams = streams.read_lock().await;
923        for stream_info in &*streams {
924            let mut stream_info = stream_info.lock().await;
925            if stream_info.state == VIRTIO_SND_R_PCM_START {
926                if let Err(e) = stream_info.stop().await {
927                    error!("Error on stop while resetting stream: {}", e);
928                }
929            }
930            if stream_info.state == VIRTIO_SND_R_PCM_STOP
931                || stream_info.state == VIRTIO_SND_R_PCM_PREPARE
932            {
933                if let Err(e) = stream_info.release().await {
934                    error!("Error on release while resetting stream: {}", e);
935                }
936            }
937            stream_info.just_reset = true;
938        }
939
940        notify_reset_signal(&reset_signal).await;
941    };
942
943    // Run these in a loop to ensure that they will survive until do_reset is finished
944    let f_tx_response = async {
945        while send_pcm_response_worker(tx_queue.clone(), tx_recv, Some(&reset_signal))
946            .await
947            .is_err()
948        {}
949    };
950
951    let f_rx_response = async {
952        while send_pcm_response_worker(rx_queue.clone(), rx_recv, Some(&reset_signal))
953            .await
954            .is_err()
955        {}
956    };
957
958    let reset = async {
959        join!(f_tx_response, f_rx_response, do_reset);
960    };
961
962    ex.run_until(reset)
963}
964
965#[cfg(test)]
966#[allow(clippy::needless_update)]
967mod tests {
968    use audio_streams::StreamEffect;
969
970    use super::*;
971    use crate::parameters::PCMDeviceParameters;
972
973    #[test]
974    fn test_virtio_snd_new() {
975        let params = Parameters {
976            num_output_devices: 3,
977            num_input_devices: 2,
978            num_output_streams: 3,
979            num_input_streams: 2,
980            output_device_config: vec![PCMDeviceParameters {
981                effects: Some(vec![StreamEffect::EchoCancellation]),
982                ..PCMDeviceParameters::default()
983            }],
984            input_device_config: vec![PCMDeviceParameters {
985                effects: Some(vec![StreamEffect::EchoCancellation]),
986                ..PCMDeviceParameters::default()
987            }],
988            ..Default::default()
989        };
990
991        let (t0, _t1) = Tube::pair().expect("failed to create tube");
992        let res = VirtioSnd::new(123, params, t0).unwrap();
993
994        // Default values
995        assert_eq!(res.snd_data.jack_info.len(), 0);
996        assert_eq!(res.acked_features, 0);
997        assert_eq!(res.worker_thread.is_none(), true);
998
999        assert_eq!(res.avail_features, 123); // avail_features must be equal to the input
1000        assert_eq!(res.cfg.jacks.to_native(), 0);
1001        assert_eq!(res.cfg.streams.to_native(), 13); // (Output = 3*3) + (Input = 2*2)
1002        assert_eq!(res.cfg.chmaps.to_native(), 11); // (Output = 3*3) + (Input = 2*1)
1003
1004        // Check snd_data.pcm_info
1005        assert_eq!(res.snd_data.pcm_info.len(), 13);
1006        // Check hda_fn_nid (PCM Device number)
1007        let expected_hda_fn_nid = [0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 1, 1];
1008        for (i, pcm_info) in res.snd_data.pcm_info.iter().enumerate() {
1009            assert_eq!(
1010                pcm_info.hdr.hda_fn_nid.to_native(),
1011                expected_hda_fn_nid[i],
1012                "pcm_info index {i} incorrect hda_fn_nid"
1013            );
1014        }
1015        // First 9 devices must be OUTPUT
1016        for i in 0..9 {
1017            assert_eq!(
1018                res.snd_data.pcm_info[i].direction, VIRTIO_SND_D_OUTPUT,
1019                "pcm_info index {i} incorrect direction"
1020            );
1021        }
1022        // Next 4 devices must be INPUT
1023        for i in 9..13 {
1024            assert_eq!(
1025                res.snd_data.pcm_info[i].direction, VIRTIO_SND_D_INPUT,
1026                "pcm_info index {i} incorrect direction"
1027            );
1028        }
1029
1030        // Check snd_data.chmap_info
1031        assert_eq!(res.snd_data.chmap_info.len(), 11);
1032        let expected_hda_fn_nid = [0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2];
1033        // Check hda_fn_nid (PCM Device number)
1034        for (i, chmap_info) in res.snd_data.chmap_info.iter().enumerate() {
1035            assert_eq!(
1036                chmap_info.hdr.hda_fn_nid.to_native(),
1037                expected_hda_fn_nid[i],
1038                "chmap_info index {i} incorrect hda_fn_nid"
1039            );
1040        }
1041    }
1042
1043    fn advertised_formats(backend: StreamSourceBackend) -> Vec<u64> {
1044        let params = Parameters {
1045            backend,
1046            ..Default::default()
1047        };
1048        let snd_data = hardcoded_snd_data(&params);
1049        assert!(snd_data.pcm_info_len() > 0);
1050        snd_data
1051            .pcm_info_iter()
1052            .map(|pcm_info| pcm_info.formats.to_native())
1053            .collect()
1054    }
1055
1056    #[test]
1057    fn test_null_backend_advertises_all_formats() {
1058        for formats in advertised_formats(StreamSourceBackend::NULL) {
1059            assert_eq!(formats, SUPPORTED_FORMATS);
1060        }
1061    }
1062
1063    #[test]
1064    #[cfg(all(unix, feature = "audio_aaudio"))]
1065    fn test_aaudio_advertises_s16_s32_only() {
1066        let backend = StreamSourceBackend::Sys(crate::sys::StreamSourceBackend::AAUDIO);
1067        for formats in advertised_formats(backend) {
1068            assert_eq!(
1069                formats,
1070                1 << VIRTIO_SND_PCM_FMT_S16 | 1 << VIRTIO_SND_PCM_FMT_S32
1071            );
1072        }
1073    }
1074
1075    #[test]
1076    fn test_resize_parameters_pcm_device_config_truncate() {
1077        // If pcm_device_config is larger than number of devices, it will be truncated
1078        let params = Parameters {
1079            num_output_devices: 1,
1080            num_input_devices: 1,
1081            output_device_config: vec![PCMDeviceParameters::default(); 3],
1082            input_device_config: vec![PCMDeviceParameters::default(); 3],
1083            ..Parameters::default()
1084        };
1085        let params = resize_parameters_pcm_device_config(params);
1086        assert_eq!(params.output_device_config.len(), 1);
1087        assert_eq!(params.input_device_config.len(), 1);
1088    }
1089
1090    #[test]
1091    fn test_resize_parameters_pcm_device_config_extend() {
1092        let params = Parameters {
1093            num_output_devices: 3,
1094            num_input_devices: 2,
1095            num_output_streams: 3,
1096            num_input_streams: 2,
1097            output_device_config: vec![PCMDeviceParameters {
1098                effects: Some(vec![StreamEffect::EchoCancellation]),
1099                ..PCMDeviceParameters::default()
1100            }],
1101            input_device_config: vec![PCMDeviceParameters {
1102                effects: Some(vec![StreamEffect::EchoCancellation]),
1103                ..PCMDeviceParameters::default()
1104            }],
1105            ..Default::default()
1106        };
1107
1108        let params = resize_parameters_pcm_device_config(params);
1109
1110        // Check output_device_config correctly extended
1111        assert_eq!(
1112            params.output_device_config,
1113            vec![
1114                PCMDeviceParameters {
1115                    // Keep from the parameters
1116                    effects: Some(vec![StreamEffect::EchoCancellation]),
1117                    ..PCMDeviceParameters::default()
1118                },
1119                PCMDeviceParameters::default(), // Extended with default
1120                PCMDeviceParameters::default(), // Extended with default
1121            ]
1122        );
1123
1124        // Check input_device_config correctly extended
1125        assert_eq!(
1126            params.input_device_config,
1127            vec![
1128                PCMDeviceParameters {
1129                    // Keep from the parameters
1130                    effects: Some(vec![StreamEffect::EchoCancellation]),
1131                    ..PCMDeviceParameters::default()
1132                },
1133                PCMDeviceParameters::default(), // Extended with default
1134            ]
1135        );
1136    }
1137}