device_virtio_snd/
parameters.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
5use std::num::ParseIntError;
6use std::str::ParseBoolError;
7
8use audio_streams::StreamEffect;
9#[cfg(all(unix, feature = "audio_cras"))]
10use libcras::CrasClientType;
11#[cfg(all(unix, feature = "audio_cras"))]
12use libcras::CrasSocketType;
13#[cfg(all(unix, feature = "audio_cras"))]
14use libcras::CrasStreamType;
15use serde::Deserialize;
16use serde::Serialize;
17use serde_keyvalue::FromKeyValues;
18use thiserror::Error as ThisError;
19
20use crate::constants::*;
21use crate::layout::*;
22use crate::sys::StreamSourceBackend as SysStreamSourceBackend;
23
24#[derive(ThisError, Debug, PartialEq, Eq)]
25pub enum Error {
26    /// Unknown snd parameter value.
27    #[error("Invalid snd parameter value ({0}): {1}")]
28    InvalidParameterValue(String, String),
29    /// Failed to parse bool value.
30    #[error("Invalid bool value: {0}")]
31    InvalidBoolValue(ParseBoolError),
32    /// Failed to parse int value.
33    #[error("Invalid int value: {0}")]
34    InvalidIntValue(ParseIntError),
35    // Invalid backend.
36    #[error("Backend is not implemented")]
37    InvalidBackend,
38    /// Failed to parse parameters.
39    #[error("Invalid snd parameter: {0}")]
40    UnknownParameter(String),
41    /// Invalid PCM device config index. Happens when the length of PCM device config is less than
42    /// the number of PCM devices.
43    #[error("Invalid PCM device config index: {0}")]
44    InvalidPCMDeviceConfigIndex(usize),
45    /// Invalid PCM info direction (VIRTIO_SND_D_OUTPUT = 0, VIRTIO_SND_D_INPUT = 1)
46    #[error("Invalid PCM Info direction: {0}")]
47    InvalidPCMInfoDirection(u8),
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
51#[serde(into = "String", try_from = "&str")]
52pub enum StreamSourceBackend {
53    NULL,
54    FILE,
55    Sys(SysStreamSourceBackend),
56}
57
58// Implemented to make backend serialization possible, since we deserialize from str.
59impl From<StreamSourceBackend> for String {
60    fn from(backend: StreamSourceBackend) -> Self {
61        match backend {
62            StreamSourceBackend::NULL => "null".to_owned(),
63            StreamSourceBackend::FILE => "file".to_owned(),
64            StreamSourceBackend::Sys(sys_backend) => sys_backend.into(),
65        }
66    }
67}
68
69impl TryFrom<&str> for StreamSourceBackend {
70    type Error = Error;
71
72    fn try_from(s: &str) -> Result<Self, Self::Error> {
73        match s {
74            "null" => Ok(StreamSourceBackend::NULL),
75            "file" => Ok(StreamSourceBackend::FILE),
76            _ => SysStreamSourceBackend::try_from(s).map(StreamSourceBackend::Sys),
77        }
78    }
79}
80
81/// Holds the parameters for each PCM device
82#[derive(Debug, Clone, Default, Deserialize, Serialize, FromKeyValues, PartialEq, Eq)]
83#[serde(deny_unknown_fields, default)]
84pub struct PCMDeviceParameters {
85    #[cfg(all(unix, feature = "audio_cras"))]
86    pub client_type: Option<CrasClientType>,
87    #[cfg(all(unix, feature = "audio_cras"))]
88    pub stream_type: Option<CrasStreamType>,
89    pub effects: Option<Vec<StreamEffect>>,
90}
91
92/// Holds the parameters for a cras sound device
93#[derive(Debug, Clone, Deserialize, Serialize, FromKeyValues)]
94#[serde(deny_unknown_fields, default)]
95pub struct Parameters {
96    pub capture: bool,
97    pub num_output_devices: u32,
98    pub num_input_devices: u32,
99    pub backend: StreamSourceBackend,
100    pub num_output_streams: u32,
101    pub num_input_streams: u32,
102    pub playback_path: String,
103    pub playback_size: usize,
104    #[cfg(all(unix, feature = "audio_cras"))]
105    #[serde(deserialize_with = "libcras::deserialize_cras_client_type")]
106    pub client_type: CrasClientType,
107    #[cfg(all(unix, feature = "audio_cras"))]
108    pub socket_type: CrasSocketType,
109    pub output_device_config: Vec<PCMDeviceParameters>,
110    pub input_device_config: Vec<PCMDeviceParameters>,
111    pub card_index: usize,
112
113    #[cfg(any(target_os = "android", target_os = "linux"))]
114    #[serde(default)]
115    /// set MADV_DONTFORK on guest memory
116    ///
117    /// Intended for use in combination with protected VMs, where the guest memory can be dangerous
118    /// to access. Some systems, e.g. Android, have tools that fork processes and examine their
119    /// memory. This flag effectively hides the guest memory from those tools.
120    ///
121    /// Not compatible with sandboxing.
122    pub unmap_guest_memory_on_fork: bool,
123
124    #[cfg(any(target_os = "android", target_os = "linux"))]
125    #[serde(default)]
126    /// File descriptor of an inherited permission socket for audio capture authorization.
127    pub permission_socket_fd: Option<base::RawDescriptor>,
128}
129
130impl Default for Parameters {
131    fn default() -> Self {
132        Parameters {
133            capture: false,
134            num_output_devices: 1,
135            num_input_devices: 1,
136            backend: StreamSourceBackend::NULL,
137            num_output_streams: 1,
138            num_input_streams: 1,
139            playback_path: "".to_string(),
140            playback_size: 0,
141            #[cfg(all(unix, feature = "audio_cras"))]
142            client_type: CrasClientType::CRAS_CLIENT_TYPE_CROSVM,
143            #[cfg(all(unix, feature = "audio_cras"))]
144            socket_type: CrasSocketType::Unified,
145            output_device_config: vec![],
146            input_device_config: vec![],
147            card_index: 0,
148            #[cfg(any(target_os = "android", target_os = "linux"))]
149            unmap_guest_memory_on_fork: false,
150            #[cfg(any(target_os = "android", target_os = "linux"))]
151            permission_socket_fd: None,
152        }
153    }
154}
155
156impl Parameters {
157    pub(crate) fn get_total_output_streams(&self) -> u32 {
158        self.num_output_devices * self.num_output_streams
159    }
160
161    pub(crate) fn get_total_input_streams(&self) -> u32 {
162        self.num_input_devices * self.num_input_streams
163    }
164
165    pub(crate) fn get_total_streams(&self) -> u32 {
166        self.get_total_output_streams() + self.get_total_input_streams()
167    }
168
169    #[allow(dead_code)]
170    pub(crate) fn get_device_params(
171        &self,
172        pcm_info: &virtio_snd_pcm_info,
173    ) -> Result<PCMDeviceParameters, Error> {
174        let device_config = match pcm_info.direction {
175            VIRTIO_SND_D_OUTPUT => &self.output_device_config,
176            VIRTIO_SND_D_INPUT => &self.input_device_config,
177            _ => return Err(Error::InvalidPCMInfoDirection(pcm_info.direction)),
178        };
179        let device_idx = u32::from(pcm_info.hdr.hda_fn_nid) as usize;
180        device_config
181            .get(device_idx)
182            .cloned()
183            .ok_or(Error::InvalidPCMDeviceConfigIndex(device_idx))
184    }
185}
186
187#[cfg(test)]
188#[allow(clippy::needless_update)]
189mod tests {
190    use super::*;
191
192    fn check_failure(s: &str) {
193        serde_keyvalue::from_key_values::<Parameters>(s).expect_err("parse should have failed");
194    }
195
196    fn check_success(
197        s: &str,
198        capture: bool,
199        backend: StreamSourceBackend,
200        num_output_devices: u32,
201        num_input_devices: u32,
202        num_output_streams: u32,
203        num_input_streams: u32,
204        output_device_config: Vec<PCMDeviceParameters>,
205        input_device_config: Vec<PCMDeviceParameters>,
206    ) {
207        let params: Parameters =
208            serde_keyvalue::from_key_values(s).expect("parse should have succeded");
209        assert_eq!(params.capture, capture);
210        assert_eq!(params.backend, backend);
211        assert_eq!(params.num_output_devices, num_output_devices);
212        assert_eq!(params.num_input_devices, num_input_devices);
213        assert_eq!(params.num_output_streams, num_output_streams);
214        assert_eq!(params.num_input_streams, num_input_streams);
215        assert_eq!(params.output_device_config, output_device_config);
216        assert_eq!(params.input_device_config, input_device_config);
217    }
218
219    #[test]
220    fn parameters_fromstr() {
221        check_failure("capture=none");
222        check_success(
223            "capture=false",
224            false,
225            StreamSourceBackend::NULL,
226            1,
227            1,
228            1,
229            1,
230            vec![],
231            vec![],
232        );
233        check_success(
234            "capture=true,num_output_streams=2,num_input_streams=3",
235            true,
236            StreamSourceBackend::NULL,
237            1,
238            1,
239            2,
240            3,
241            vec![],
242            vec![],
243        );
244        check_success(
245            "capture=true,num_output_devices=3,num_input_devices=2",
246            true,
247            StreamSourceBackend::NULL,
248            3,
249            2,
250            1,
251            1,
252            vec![],
253            vec![],
254        );
255        check_success(
256            "capture=true,num_output_devices=2,num_input_devices=3,\
257            num_output_streams=3,num_input_streams=2",
258            true,
259            StreamSourceBackend::NULL,
260            2,
261            3,
262            3,
263            2,
264            vec![],
265            vec![],
266        );
267        check_success(
268            "capture=true,backend=null,num_output_devices=2,num_input_devices=3,\
269            num_output_streams=3,num_input_streams=2",
270            true,
271            StreamSourceBackend::NULL,
272            2,
273            3,
274            3,
275            2,
276            vec![],
277            vec![],
278        );
279        check_success(
280            "output_device_config=[[effects=[aec]],[]]",
281            false,
282            StreamSourceBackend::NULL,
283            1,
284            1,
285            1,
286            1,
287            vec![
288                PCMDeviceParameters {
289                    effects: Some(vec![StreamEffect::EchoCancellation]),
290                    ..Default::default()
291                },
292                Default::default(),
293            ],
294            vec![],
295        );
296        check_success(
297            "input_device_config=[[effects=[aec]],[]]",
298            false,
299            StreamSourceBackend::NULL,
300            1,
301            1,
302            1,
303            1,
304            vec![],
305            vec![
306                PCMDeviceParameters {
307                    effects: Some(vec![StreamEffect::EchoCancellation]),
308                    ..Default::default()
309                },
310                Default::default(),
311            ],
312        );
313
314        // Invalid effect in device config
315        check_failure("output_device_config=[[effects=[none]]]");
316    }
317
318    #[test]
319    #[cfg(all(unix, feature = "audio_cras"))]
320    fn cras_parameters_fromstr() {
321        fn cras_check_success(
322            s: &str,
323            backend: StreamSourceBackend,
324            client_type: CrasClientType,
325            socket_type: CrasSocketType,
326            output_device_config: Vec<PCMDeviceParameters>,
327            input_device_config: Vec<PCMDeviceParameters>,
328        ) {
329            let params: Parameters =
330                serde_keyvalue::from_key_values(s).expect("parse should have succeded");
331            assert_eq!(params.backend, backend);
332            assert_eq!(params.client_type, client_type);
333            assert_eq!(params.socket_type, socket_type);
334            assert_eq!(params.output_device_config, output_device_config);
335            assert_eq!(params.input_device_config, input_device_config);
336        }
337
338        cras_check_success(
339            "backend=cras",
340            StreamSourceBackend::Sys(SysStreamSourceBackend::CRAS),
341            CrasClientType::CRAS_CLIENT_TYPE_CROSVM,
342            CrasSocketType::Unified,
343            vec![],
344            vec![],
345        );
346        cras_check_success(
347            "backend=cras,client_type=crosvm",
348            StreamSourceBackend::Sys(SysStreamSourceBackend::CRAS),
349            CrasClientType::CRAS_CLIENT_TYPE_CROSVM,
350            CrasSocketType::Unified,
351            vec![],
352            vec![],
353        );
354        cras_check_success(
355            "backend=cras,client_type=arcvm",
356            StreamSourceBackend::Sys(SysStreamSourceBackend::CRAS),
357            CrasClientType::CRAS_CLIENT_TYPE_ARCVM,
358            CrasSocketType::Unified,
359            vec![],
360            vec![],
361        );
362        check_failure("backend=cras,client_type=none");
363        cras_check_success(
364            "backend=cras,socket_type=legacy",
365            StreamSourceBackend::Sys(SysStreamSourceBackend::CRAS),
366            CrasClientType::CRAS_CLIENT_TYPE_CROSVM,
367            CrasSocketType::Legacy,
368            vec![],
369            vec![],
370        );
371        cras_check_success(
372            "backend=cras,socket_type=unified",
373            StreamSourceBackend::Sys(SysStreamSourceBackend::CRAS),
374            CrasClientType::CRAS_CLIENT_TYPE_CROSVM,
375            CrasSocketType::Unified,
376            vec![],
377            vec![],
378        );
379        cras_check_success(
380            "output_device_config=[[client_type=crosvm],[client_type=arcvm,stream_type=pro_audio],[]]",
381            StreamSourceBackend::NULL,
382            CrasClientType::CRAS_CLIENT_TYPE_CROSVM,
383            CrasSocketType::Unified,
384            vec![
385                PCMDeviceParameters{
386                    client_type: Some(CrasClientType::CRAS_CLIENT_TYPE_CROSVM),
387                    stream_type: None,
388                    effects: None,
389                },
390                PCMDeviceParameters{
391                    client_type: Some(CrasClientType::CRAS_CLIENT_TYPE_ARCVM),
392                    stream_type: Some(CrasStreamType::CRAS_STREAM_TYPE_PRO_AUDIO),
393                    effects: None,
394                },
395                Default::default(),
396                ],
397            vec![],
398        );
399        cras_check_success(
400            "input_device_config=[[client_type=crosvm],[client_type=arcvm,effects=[aec],stream_type=pro_audio],[effects=[EchoCancellation]],[]]",
401            StreamSourceBackend::NULL,
402            CrasClientType::CRAS_CLIENT_TYPE_CROSVM,
403            CrasSocketType::Unified,
404            vec![],
405            vec![
406                PCMDeviceParameters{
407                    client_type: Some(CrasClientType::CRAS_CLIENT_TYPE_CROSVM),
408                    stream_type: None,
409                    effects: None,
410                },
411                PCMDeviceParameters{
412                    client_type: Some(CrasClientType::CRAS_CLIENT_TYPE_ARCVM),
413                    stream_type: Some(CrasStreamType::CRAS_STREAM_TYPE_PRO_AUDIO),
414                    effects: Some(vec![StreamEffect::EchoCancellation]),
415                },
416                PCMDeviceParameters{
417                    client_type: None,
418                    stream_type: None,
419                    effects: Some(vec![StreamEffect::EchoCancellation]),
420                },
421                Default::default(),
422                ],
423        );
424
425        // Invalid client_type in device config
426        check_failure("output_device_config=[[client_type=none]]");
427
428        // Invalid stream type in device config
429        check_failure("output_device_config=[[stream_type=none]]");
430    }
431
432    #[test]
433    fn get_device_params_output() {
434        let params = Parameters {
435            output_device_config: vec![
436                PCMDeviceParameters {
437                    effects: Some(vec![StreamEffect::EchoCancellation]),
438                    ..Default::default()
439                },
440                PCMDeviceParameters {
441                    effects: Some(vec![
442                        StreamEffect::EchoCancellation,
443                        StreamEffect::EchoCancellation,
444                    ]),
445                    ..Default::default()
446                },
447            ],
448            ..Default::default()
449        };
450
451        let default_pcm_info = virtio_snd_pcm_info {
452            hdr: virtio_snd_info {
453                hda_fn_nid: 0.into(),
454            },
455            features: 0.into(),
456            formats: 0.into(),
457            rates: 0.into(),
458            direction: VIRTIO_SND_D_OUTPUT, // Direction is OUTPUT
459            channels_min: 1,
460            channels_max: 6,
461            padding: [0; 5],
462        };
463
464        let mut pcm_info = default_pcm_info;
465        pcm_info.hdr.hda_fn_nid = 0.into();
466        assert_eq!(
467            params.get_device_params(&pcm_info),
468            Ok(params.output_device_config[0].clone())
469        );
470
471        let mut pcm_info = default_pcm_info;
472        pcm_info.hdr.hda_fn_nid = 1.into();
473        assert_eq!(
474            params.get_device_params(&pcm_info),
475            Ok(params.output_device_config[1].clone())
476        );
477
478        let mut pcm_info = default_pcm_info;
479        pcm_info.hdr.hda_fn_nid = 2.into();
480        assert_eq!(
481            params.get_device_params(&pcm_info),
482            Err(Error::InvalidPCMDeviceConfigIndex(2))
483        );
484    }
485
486    #[test]
487    fn get_device_params_input() {
488        let params = Parameters {
489            input_device_config: vec![
490                PCMDeviceParameters {
491                    effects: Some(vec![
492                        StreamEffect::EchoCancellation,
493                        StreamEffect::EchoCancellation,
494                    ]),
495                    ..Default::default()
496                },
497                PCMDeviceParameters {
498                    effects: Some(vec![StreamEffect::EchoCancellation]),
499                    ..Default::default()
500                },
501            ],
502            ..Default::default()
503        };
504
505        let default_pcm_info = virtio_snd_pcm_info {
506            hdr: virtio_snd_info {
507                hda_fn_nid: 0.into(),
508            },
509            features: 0.into(),
510            formats: 0.into(),
511            rates: 0.into(),
512            direction: VIRTIO_SND_D_INPUT, // Direction is INPUT
513            channels_min: 1,
514            channels_max: 6,
515            padding: [0; 5],
516        };
517
518        let mut pcm_info = default_pcm_info;
519        pcm_info.hdr.hda_fn_nid = 0.into();
520        assert_eq!(
521            params.get_device_params(&pcm_info),
522            Ok(params.input_device_config[0].clone())
523        );
524
525        let mut pcm_info = default_pcm_info;
526        pcm_info.hdr.hda_fn_nid = 1.into();
527        assert_eq!(
528            params.get_device_params(&pcm_info),
529            Ok(params.input_device_config[1].clone())
530        );
531
532        let mut pcm_info = default_pcm_info;
533        pcm_info.hdr.hda_fn_nid = 2.into();
534        assert_eq!(
535            params.get_device_params(&pcm_info),
536            Err(Error::InvalidPCMDeviceConfigIndex(2))
537        );
538    }
539
540    #[test]
541    fn get_device_params_invalid_direction() {
542        let params = Parameters::default();
543
544        let pcm_info = virtio_snd_pcm_info {
545            hdr: virtio_snd_info {
546                hda_fn_nid: 0.into(),
547            },
548            features: 0.into(),
549            formats: 0.into(),
550            rates: 0.into(),
551            direction: 2, // Invalid direction
552            channels_min: 1,
553            channels_max: 6,
554            padding: [0; 5],
555        };
556
557        assert_eq!(
558            params.get_device_params(&pcm_info),
559            Err(Error::InvalidPCMInfoDirection(2))
560        );
561    }
562
563    #[test]
564    #[cfg(any(target_os = "android", target_os = "linux"))]
565    fn parameters_permission_socket_fd() {
566        let params: Parameters =
567            serde_keyvalue::from_key_values("permission_socket_fd=42").unwrap();
568        assert_eq!(params.permission_socket_fd, Some(42));
569    }
570}