settings/audio/
audio_fidl_handler.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use fidl::prelude::*;
use fidl_fuchsia_settings::{
    AudioMarker, AudioRequest, AudioSetResponder, AudioSetResult, AudioSettings,
    AudioStreamSettingSource, AudioStreamSettings, AudioWatchResponder, Volume,
};

use fidl_fuchsia_media::AudioRenderUsage;
use fuchsia_trace as ftrace;

use crate::audio::types::{AudioSettingSource, AudioStream, AudioStreamType, SetAudioStream};
use crate::base::{SettingInfo, SettingType};
use crate::handler::base::Request;
use crate::ingress::{request, watch, Scoped};
use crate::job::source::{Error as JobError, ErrorResponder};
use crate::job::Job;
use crate::{trace, trace_guard};

/// Custom responder that wraps the real FIDL responder plus a tracing guard. The guard is stored
/// here so that it's active until a response is sent and this responder is dropped.
struct AudioSetTraceResponder {
    responder: AudioSetResponder,
    _guard: Option<ftrace::AsyncScope>,
}

impl request::Responder<Scoped<AudioSetResult>> for AudioSetTraceResponder {
    fn respond(self, Scoped(response): Scoped<AudioSetResult>) {
        let _ = self.responder.send(response);
    }
}

impl ErrorResponder for AudioSetTraceResponder {
    fn id(&self) -> &'static str {
        "Audio_Set"
    }

    fn respond(self: Box<Self>, error: fidl_fuchsia_settings::Error) -> Result<(), fidl::Error> {
        self.responder.send(Err(error))
    }
}

impl request::Responder<Scoped<AudioSetResult>> for AudioSetResponder {
    fn respond(self, Scoped(response): Scoped<AudioSetResult>) {
        let _ = self.send(response);
    }
}

impl watch::Responder<AudioSettings, zx::Status> for AudioWatchResponder {
    fn respond(self, response: Result<AudioSettings, zx::Status>) {
        match response {
            Ok(settings) => {
                let _ = self.send(&settings);
            }
            Err(error) => {
                self.control_handle().shutdown_with_epitaph(error);
            }
        }
    }
}

impl TryFrom<AudioRequest> for Job {
    type Error = JobError;

    fn try_from(item: AudioRequest) -> Result<Self, Self::Error> {
        #[allow(unreachable_patterns)]
        match item {
            AudioRequest::Set { settings, responder } => {
                let id = ftrace::Id::new();
                let guard = trace_guard!(id, c"audio fidl handler set");
                let responder = AudioSetTraceResponder { responder, _guard: guard };
                match to_request(settings, id) {
                    Ok(request) => {
                        Ok(request::Work::new(SettingType::Audio, request, responder).into())
                    }
                    Err(err) => {
                        tracing::error!(
                            "{}: Failed to process request: {:?}",
                            AudioMarker::DEBUG_NAME,
                            err
                        );
                        Err(JobError::InvalidInput(Box::new(responder)))
                    }
                }
            }
            AudioRequest::Watch { responder } => {
                let mut hasher = DefaultHasher::new();
                "audio_watch".hash(&mut hasher);
                // Because we increment the modification counters stored in AudioInfo for
                // every change, clients would be notified for every change, even if the
                // streams are identical. A custom change function is used here so only
                // stream changes trigger the Watch notification.
                Ok(watch::Work::new_job_with_change_function(
                    SettingType::Audio,
                    responder,
                    watch::ChangeFunction::new(
                        hasher.finish(),
                        Box::new(move |old: &SettingInfo, new: &SettingInfo| match (old, new) {
                            (SettingInfo::Audio(old_info), SettingInfo::Audio(new_info)) => {
                                let mut old_streams = old_info.streams.iter();
                                let new_streams = new_info.streams.iter();
                                for new_stream in new_streams {
                                    let old_stream = old_streams
                                        .find(|stream| stream.stream_type == new_stream.stream_type)
                                        .expect("stream type should be found in existing streams");
                                    if old_stream != new_stream {
                                        return true;
                                    }
                                }
                                false
                            }
                            _ => false,
                        }),
                    ),
                ))
            }
            _ => {
                tracing::warn!("Received a call to an unsupported API: {:?}", item);
                Err(JobError::Unsupported)
            }
        }
    }
}

impl From<SettingInfo> for AudioSettings {
    fn from(response: SettingInfo) -> Self {
        if let SettingInfo::Audio(info) = response {
            let mut streams = Vec::new();
            for stream in &info.streams {
                streams.push(AudioStreamSettings::from(*stream));
            }

            AudioSettings { streams: Some(streams), ..Default::default() }
        } else {
            panic!("incorrect value sent to audio");
        }
    }
}

impl From<AudioStream> for AudioStreamSettings {
    fn from(stream: AudioStream) -> Self {
        AudioStreamSettings {
            stream: Some(AudioRenderUsage::from(stream.stream_type)),
            source: Some(AudioStreamSettingSource::from(stream.source)),
            user_volume: Some(Volume {
                level: Some(stream.user_volume_level),
                muted: Some(stream.user_volume_muted),
                ..Default::default()
            }),
            ..Default::default()
        }
    }
}

impl From<AudioRenderUsage> for AudioStreamType {
    fn from(usage: AudioRenderUsage) -> Self {
        match usage {
            AudioRenderUsage::Background => AudioStreamType::Background,
            AudioRenderUsage::Communication => AudioStreamType::Communication,
            AudioRenderUsage::Interruption => AudioStreamType::Interruption,
            AudioRenderUsage::Media => AudioStreamType::Media,
            AudioRenderUsage::SystemAgent => AudioStreamType::SystemAgent,
        }
    }
}

impl From<AudioStreamType> for AudioRenderUsage {
    fn from(usage: AudioStreamType) -> Self {
        match usage {
            AudioStreamType::Background => AudioRenderUsage::Background,
            AudioStreamType::Communication => AudioRenderUsage::Communication,
            AudioStreamType::Interruption => AudioRenderUsage::Interruption,
            AudioStreamType::Media => AudioRenderUsage::Media,
            AudioStreamType::SystemAgent => AudioRenderUsage::SystemAgent,
        }
    }
}

impl From<AudioStreamSettingSource> for AudioSettingSource {
    fn from(source: AudioStreamSettingSource) -> Self {
        match source {
            AudioStreamSettingSource::User => AudioSettingSource::User,
            AudioStreamSettingSource::System => AudioSettingSource::System,
            AudioStreamSettingSource::SystemWithFeedback => AudioSettingSource::SystemWithFeedback,
        }
    }
}

impl From<AudioSettingSource> for AudioStreamSettingSource {
    fn from(source: AudioSettingSource) -> Self {
        match source {
            AudioSettingSource::User => AudioStreamSettingSource::User,
            AudioSettingSource::System => AudioStreamSettingSource::System,
            AudioSettingSource::SystemWithFeedback => AudioStreamSettingSource::SystemWithFeedback,
        }
    }
}

// Clippy warns about all variants starting with the same prefix `No`.
#[allow(clippy::enum_variant_names)]
#[derive(thiserror::Error, Debug, PartialEq)]
enum Error {
    #[error("request has no streams")]
    NoStreams,
    #[error("missing user_volume at stream {0}")]
    NoUserVolume(usize),
    #[error("missing user_volume.level and user_volume.muted at stream {0}")]
    MissingVolumeAndMuted(usize),
    #[error("missing stream at stream {0}")]
    NoStreamType(usize),
    #[error("missing source at stream {0}")]
    NoSource(usize),
}

fn to_request(settings: AudioSettings, id: ftrace::Id) -> Result<Request, Error> {
    trace!(id, c"to_request");
    settings
        .streams
        .map(|streams| {
            streams
                .into_iter()
                .enumerate()
                .map(|(i, stream)| {
                    let user_volume = stream.user_volume.ok_or(Error::NoUserVolume(i))?;
                    let user_volume_level = user_volume.level;
                    let user_volume_muted = user_volume.muted;
                    let stream_type = stream.stream.ok_or(Error::NoStreamType(i))?.into();
                    let source = stream.source.ok_or(Error::NoSource(i))?.into();
                    let request = SetAudioStream {
                        stream_type,
                        source,
                        user_volume_level,
                        user_volume_muted,
                    };
                    if request.is_valid_payload() {
                        Ok(request)
                    } else {
                        Err(Error::MissingVolumeAndMuted(i))
                    }
                })
                .collect::<Result<Vec<_>, _>>()
                .map(|streams| Request::SetVolume(streams, id))
        })
        .unwrap_or(Err(Error::NoStreams))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_stream() -> AudioStreamSettings {
        AudioStreamSettings {
            stream: Some(fidl_fuchsia_media::AudioRenderUsage::Media),
            source: Some(AudioStreamSettingSource::User),
            user_volume: Some(Volume {
                level: Some(0.6),
                muted: Some(false),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    // Verifies that an entirely empty settings request results in an appropriate error.
    #[fuchsia::test]
    fn test_request_from_settings_empty() {
        let id = ftrace::Id::new();
        let request = to_request(AudioSettings::default(), id);

        assert_eq!(request, Err(Error::NoStreams));
    }

    // Verifies that a settings request missing user volume info results in an appropriate error.
    #[fuchsia::test]
    fn test_request_missing_user_volume() {
        let mut stream = test_stream();
        stream.user_volume = None;

        let audio_settings = AudioSettings { streams: Some(vec![stream]), ..Default::default() };

        let id = ftrace::Id::new();
        let request = to_request(audio_settings, id);

        assert_eq!(request, Err(Error::NoUserVolume(0)));
    }

    // Verifies that a settings request missing the stream type results in an appropriate error.
    #[fuchsia::test]
    fn test_request_missing_stream_type() {
        let mut stream = test_stream();
        stream.stream = None;

        let audio_settings = AudioSettings { streams: Some(vec![stream]), ..Default::default() };

        let id = ftrace::Id::new();
        let request = to_request(audio_settings, id);

        assert_eq!(request, Err(Error::NoStreamType(0)));
    }

    // Verifies that a settings request missing the source results in an appropriate error.
    #[fuchsia::test]
    fn test_request_missing_source() {
        let mut stream = test_stream();
        stream.source = None;

        let audio_settings = AudioSettings { streams: Some(vec![stream]), ..Default::default() };

        let id = ftrace::Id::new();
        let request = to_request(audio_settings, id);

        assert_eq!(request, Err(Error::NoSource(0)));
    }

    // Verifies that a settings request missing both the user volume level and mute state results in
    // an appropriate error.
    #[fuchsia::test]
    fn test_request_missing_user_volume_level_and_muted() {
        let mut stream = test_stream();
        stream.user_volume = Some(Volume { level: None, muted: None, ..Default::default() });

        let audio_settings = AudioSettings { streams: Some(vec![stream]), ..Default::default() };

        let id = ftrace::Id::new();
        let request = to_request(audio_settings, id);

        assert_eq!(request, Err(Error::MissingVolumeAndMuted(0)));
    }
}