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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
// 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_media::{AudioRenderUsage, AudioRenderUsage2};
use fidl_fuchsia_settings::{
    AudioMarker, AudioRequest, AudioSet2Responder, AudioSet2Result, AudioSetResponder,
    AudioSetResult, AudioSettings, AudioSettings2, AudioStreamSettingSource, AudioStreamSettings,
    AudioStreamSettings2, AudioWatch2Responder, AudioWatchResponder, Volume,
};
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);
            }
        }
    }
}

// Set2 and Watch2 implementations are derived directly from the corresponding Set and Watch
// counterparts, using AudioSettings2 instead of AudioSettings.
struct AudioSet2TraceResponder {
    responder: AudioSet2Responder,
    _guard: Option<ftrace::AsyncScope>,
}
impl request::Responder<Scoped<AudioSet2Result>> for AudioSet2TraceResponder {
    fn respond(self, Scoped(response): Scoped<AudioSet2Result>) {
        let _ = self.responder.send(response);
    }
}
impl ErrorResponder for AudioSet2TraceResponder {
    fn id(&self) -> &'static str {
        "Audio_Set2"
    }

    fn respond(self: Box<Self>, error: fidl_fuchsia_settings::Error) -> Result<(), fidl::Error> {
        self.responder.send(Err(error))
    }
}
impl request::Responder<Scoped<AudioSet2Result>> for AudioSet2Responder {
    fn respond(self, Scoped(response): Scoped<AudioSet2Result>) {
        let _ = self.send(response);
    }
}

impl watch::Responder<AudioSettings2, zx::Status> for AudioWatch2Responder {
    fn respond(self, response: Result<AudioSettings2, 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) => {
                        log::error!(
                            "{}: Failed to process 'set' request: {:?}",
                            AudioMarker::DEBUG_NAME,
                            err
                        );
                        Err(JobError::InvalidInput(Box::new(responder)))
                    }
                }
            }
            AudioRequest::Set2 { settings, responder } => {
                let id = ftrace::Id::new();
                let guard = trace_guard!(id, c"audio fidl handler set2");
                let responder = AudioSet2TraceResponder { responder, _guard: guard };
                match to_request2(settings, id) {
                    Ok(request) => {
                        Ok(request::Work::new(SettingType::Audio, request, responder).into())
                    }
                    Err(err) => {
                        log::error!(
                            "{}: Failed2 to process 'set2' 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
                // (and only in "legacy" stream types) 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");
                                    // Watch() notifies upon changes to "legacy" stream types.
                                    if (old_stream != new_stream)
                                        && new_stream.stream_type.is_legacy()
                                    {
                                        return true;
                                    }
                                }
                                false
                            }
                            _ => false,
                        }),
                    ),
                ))
            }
            AudioRequest::Watch2 { responder } => {
                let mut hasher = DefaultHasher::new();
                "audio_watch2".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 Watch2() 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");
                                    // Watch2() notifies upon changes to any stream type.
                                    if old_stream != new_stream {
                                        return true;
                                    }
                                }
                                false
                            }
                            _ => false,
                        }),
                    ),
                ))
            }
            _ => {
                log::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 {
                let stream_settings = AudioStreamSettings::try_from(*stream);
                if stream_settings.is_ok() {
                    streams.push(stream_settings.unwrap());
                }
            }

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

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

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

impl TryFrom<AudioStream> for AudioStreamSettings {
    type Error = ();

    fn try_from(stream: AudioStream) -> Result<Self, ()> {
        match AudioRenderUsage::try_from(stream.stream_type) {
            Err(_) => Err(()),
            Ok(stream_type) => Ok(AudioStreamSettings {
                stream: Some(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<AudioStream> for AudioStreamSettings2 {
    fn from(stream: AudioStream) -> Self {
        AudioStreamSettings2 {
            stream: Some(AudioRenderUsage2::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 TryFrom<AudioStreamType> for AudioRenderUsage {
    type Error = ();
    fn try_from(usage: AudioStreamType) -> Result<Self, Self::Error> {
        match usage {
            AudioStreamType::Accessibility => Err(()),
            AudioStreamType::Background => Ok(AudioRenderUsage::Background),
            AudioStreamType::Communication => Ok(AudioRenderUsage::Communication),
            AudioStreamType::Interruption => Ok(AudioRenderUsage::Interruption),
            AudioStreamType::Media => Ok(AudioRenderUsage::Media),
            AudioStreamType::SystemAgent => Ok(AudioRenderUsage::SystemAgent),
        }
    }
}

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

impl TryFrom<AudioRenderUsage2> for AudioStreamType {
    type Error = ();
    fn try_from(usage: AudioRenderUsage2) -> Result<Self, Self::Error> {
        match usage {
            AudioRenderUsage2::Accessibility => Ok(AudioStreamType::Accessibility),
            AudioRenderUsage2::Background => Ok(AudioStreamType::Background),
            AudioRenderUsage2::Communication => Ok(AudioStreamType::Communication),
            AudioRenderUsage2::Interruption => Ok(AudioStreamType::Interruption),
            AudioRenderUsage2::Media => Ok(AudioStreamType::Media),
            AudioRenderUsage2::SystemAgent => Ok(AudioStreamType::SystemAgent),
            _ => Err(()),
        }
    }
}

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),
    #[error("request has an unknown stream type")]
    UnrecognizedStreamType,
}

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))
}

fn to_request2(settings: AudioSettings2, id: ftrace::Id) -> Result<Request, Error> {
    trace!(id, c"to_request2");
    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 = match stream.stream.ok_or(Error::NoStreamType(i))?.try_into()
                    {
                        Ok(stream_type) => Ok(stream_type),
                        Err(_) => Err(Error::UnrecognizedStreamType),
                    }?;
                    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()
        }
    }

    fn test_stream2() -> AudioStreamSettings2 {
        AudioStreamSettings2 {
            stream: Some(fidl_fuchsia_media::AudioRenderUsage2::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 an entirely empty settings request2 results in an appropriate error.
    #[fuchsia::test]
    fn test_request2_from_settings_empty() {
        let id = ftrace::Id::new();
        let request = to_request2(AudioSettings2::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 request2 missing user volume info results in an appropriate error.
    #[fuchsia::test]
    fn test_request2_missing_user_volume() {
        let mut stream = test_stream2();
        stream.user_volume = None;

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

        let id = ftrace::Id::new();
        let request = to_request2(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 request2 missing the stream type results in an appropriate error.
    #[fuchsia::test]
    fn test_request2_missing_stream_type() {
        let mut stream = test_stream2();
        stream.stream = None;

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

        let id = ftrace::Id::new();
        let request = to_request2(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 request2 missing the source results in an appropriate error.
    #[fuchsia::test]
    fn test_request2_missing_source() {
        let mut stream = test_stream2();
        stream.source = None;

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

        let id = ftrace::Id::new();
        let request = to_request2(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)));
    }

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

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

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

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