settings/audio/
stream_volume_control.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
// 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 crate::audio::types::AudioStream;
use crate::audio::utils::round_volume_level;
use crate::base::SettingType;
use crate::event::{Event, Publisher};
use crate::handler::setting_handler::ControllerError;
use crate::service_context::{ExternalServiceEvent, ExternalServiceProxy};
use crate::{call, clock, trace, trace_guard};
use fidl::endpoints::create_proxy;
use fidl_fuchsia_media::{AudioRenderUsage, Usage};
use fidl_fuchsia_media_audio::VolumeControlProxy;
use futures::channel::oneshot::Sender;
use futures::TryStreamExt;
use std::rc::Rc;
use {fuchsia_async as fasync, fuchsia_trace as ftrace};

const PUBLISHER_EVENT_NAME: &str = "volume_control_events";
const CONTROLLER_ERROR_DEPENDENCY: &str = "fuchsia.media.audio";
const UNKNOWN_INSPECT_STRING: &str = "unknown";

/// Closure definition for an action that can be triggered by ActionFuse.
pub(crate) type ExitAction = Rc<dyn Fn()>;

// Stores an AudioStream and a VolumeControl proxy bound to the AudioCore
// service for |stored_stream|'s stream type. |proxy| is set to None if it
// fails to bind to the AudioCore service. |early_exit_action| specifies a
// closure to be run if the StreamVolumeControl exits prematurely.
pub struct StreamVolumeControl {
    pub stored_stream: AudioStream,
    proxy: Option<VolumeControlProxy>,
    audio_service: ExternalServiceProxy<fidl_fuchsia_media::AudioCoreProxy>,
    publisher: Option<Publisher>,
    early_exit_action: Option<ExitAction>,
    listen_exit_tx: Option<Sender<()>>,
}

impl Drop for StreamVolumeControl {
    fn drop(&mut self) {
        if let Some(exit_tx) = self.listen_exit_tx.take() {
            // Do not signal exit if receiver is already closed.
            if exit_tx.is_canceled() {
                return;
            }

            // Consider panic! is likely to be abort in the drop method, only log info for
            // unbounded_send failure.
            exit_tx.send(()).unwrap_or_else(|_| {
                tracing::warn!("StreamVolumeControl::drop, exit_tx failed to send exit signal")
            });
        }
    }
}

impl StreamVolumeControl {
    pub(crate) async fn create(
        id: ftrace::Id,
        audio_service: &ExternalServiceProxy<fidl_fuchsia_media::AudioCoreProxy>,
        stream: AudioStream,
        early_exit_action: Option<ExitAction>,
        publisher: Option<Publisher>,
    ) -> Result<Self, ControllerError> {
        // Stream input should be valid. Input comes from restore should be valid
        // and from set request has the validation.
        assert!(stream.has_valid_volume_level());

        trace!(id, c"StreamVolumeControl ctor");
        let mut control = StreamVolumeControl {
            stored_stream: stream,
            proxy: None,
            audio_service: audio_service.clone(),
            publisher,
            listen_exit_tx: None,
            early_exit_action,
        };

        control.bind_volume_control(id).await?;
        Ok(control)
    }

    pub(crate) async fn set_volume(
        &mut self,
        id: ftrace::Id,
        stream: AudioStream,
    ) -> Result<(), ControllerError> {
        assert_eq!(self.stored_stream.stream_type, stream.stream_type);
        // Stream input should be valid. Input comes from restore should be valid
        // and from set request has the validation.
        assert!(stream.has_valid_volume_level());

        // Try to create and bind a new VolumeControl.
        if self.proxy.is_none() {
            self.bind_volume_control(id).await?;
        }

        // Round volume level from user input.
        let mut new_stream_value = stream;
        new_stream_value.user_volume_level = round_volume_level(stream.user_volume_level);

        let proxy = self.proxy.as_ref().expect("no volume control proxy");

        if (self.stored_stream.user_volume_level - new_stream_value.user_volume_level).abs()
            > f32::EPSILON
        {
            if let Err(e) = proxy.set_volume(new_stream_value.user_volume_level) {
                self.stored_stream = new_stream_value;
                return Err(ControllerError::ExternalFailure(
                    SettingType::Audio,
                    CONTROLLER_ERROR_DEPENDENCY.into(),
                    "set volume".into(),
                    format!("{e:?}").into(),
                ));
            }
        }

        if self.stored_stream.user_volume_muted != new_stream_value.user_volume_muted {
            if let Err(e) = proxy.set_mute(stream.user_volume_muted) {
                self.stored_stream = new_stream_value;
                return Err(ControllerError::ExternalFailure(
                    SettingType::Audio,
                    CONTROLLER_ERROR_DEPENDENCY.into(),
                    "set mute".into(),
                    format!("{e:?}").into(),
                ));
            }
        }

        self.stored_stream = new_stream_value;
        Ok(())
    }

    async fn bind_volume_control(&mut self, id: ftrace::Id) -> Result<(), ControllerError> {
        trace!(id, c"bind volume control");
        if self.proxy.is_some() {
            return Ok(());
        }

        let (vol_control_proxy, server_end) = create_proxy();
        let stream_type = self.stored_stream.stream_type;
        let usage = Usage::RenderUsage(AudioRenderUsage::from(stream_type));

        let guard = trace_guard!(id, c"bind usage volume control");
        if let Err(e) = call!(self.audio_service => bind_usage_volume_control(&usage, server_end)) {
            return Err(ControllerError::ExternalFailure(
                SettingType::Audio,
                CONTROLLER_ERROR_DEPENDENCY.into(),
                format!("bind_usage_volume_control for audio_core {usage:?}").into(),
                format!("{e:?}").into(),
            ));
        }
        drop(guard);

        let guard = trace_guard!(id, c"set values");
        // Once the volume control is bound, apply the persisted audio settings to it.
        if let Err(e) = vol_control_proxy.set_volume(self.stored_stream.user_volume_level) {
            return Err(ControllerError::ExternalFailure(
                SettingType::Audio,
                CONTROLLER_ERROR_DEPENDENCY.into(),
                format!("set_volume for vol_control {stream_type:?}").into(),
                format!("{e:?}").into(),
            ));
        }

        if let Err(e) = vol_control_proxy.set_mute(self.stored_stream.user_volume_muted) {
            return Err(ControllerError::ExternalFailure(
                SettingType::Audio,
                CONTROLLER_ERROR_DEPENDENCY.into(),
                "set_mute for vol_control".into(),
                format!("{e:?}").into(),
            ));
        }
        drop(guard);

        if let Some(exit_tx) = self.listen_exit_tx.take() {
            // exit_rx needs this signal to end leftover spawn.
            exit_tx.send(()).expect(
                "StreamVolumeControl::bind_volume_control, listen_exit_tx failed to send exit \
                signal",
            );
        }

        trace!(id, c"setup listener");

        let (exit_tx, mut exit_rx) = futures::channel::oneshot::channel::<()>();
        let publisher_clone = self.publisher.clone();
        let mut volume_events = vol_control_proxy.take_event_stream();
        let early_exit_action = self.early_exit_action.clone();
        fasync::Task::local(async move {
            let id = ftrace::Id::new();
            trace!(id, c"bind volume handler");
            loop {
                futures::select! {
                    _ = exit_rx => {
                        trace!(id, c"exit");
                        if let Some(publisher) = publisher_clone {
                            // Send UNKNOWN_INSPECT_STRING for request-related args because it
                            // can't be tied back to the event that caused the proxy to close.
                            publisher.send_event(
                                Event::ExternalServiceEvent(
                                    ExternalServiceEvent::Closed(
                                        PUBLISHER_EVENT_NAME,
                                        UNKNOWN_INSPECT_STRING.into(),
                                        UNKNOWN_INSPECT_STRING.into(),
                                        clock::inspect_format_now().into(),
                                    )
                                )
                            );
                        }
                        return;
                    }
                    volume_event = volume_events.try_next() => {
                        trace!(id, c"volume_event");
                        if volume_event.is_err() ||
                            volume_event.expect("should not be error").is_none()
                        {
                            if let Some(action) = early_exit_action {
                                (action)();
                            }
                            return;
                        }
                    }

                }
            }
        })
        .detach();

        self.listen_exit_tx = Some(exit_tx);
        self.proxy = Some(vol_control_proxy);
        Ok(())
    }
}