settings/audio/
audio_default_settings.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
// 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::{
    AudioInfo, AudioSettingSource, AudioStream, AudioStreamType, AUDIO_STREAM_TYPE_COUNT,
};
use crate::base::SettingInfo;
use crate::config::default_settings::DefaultSetting;
use crate::inspect::config_logger::InspectConfigLogger;
use settings_storage::storage_factory::DefaultLoader;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Mutex;

const DEFAULT_VOLUME_LEVEL: f32 = 0.5;
const DEFAULT_VOLUME_MUTED: bool = false;

const DEFAULT_STREAMS: [AudioStream; AUDIO_STREAM_TYPE_COUNT] = [
    create_default_audio_stream(AudioStreamType::Background),
    create_default_audio_stream(AudioStreamType::Media),
    create_default_audio_stream(AudioStreamType::Interruption),
    create_default_audio_stream(AudioStreamType::SystemAgent),
    create_default_audio_stream(AudioStreamType::Communication),
    create_default_audio_stream(AudioStreamType::Accessibility),
];

const DEFAULT_AUDIO_INFO: AudioInfo =
    AudioInfo { streams: DEFAULT_STREAMS, modified_counters: None };

/// A mapping from stream type to an arbitrary numerical value. This number will
/// change from the number sent in the previous update if the stream type's
/// volume has changed.
pub type ModifiedCounters = HashMap<AudioStreamType, usize>;

pub(crate) fn create_default_modified_counters() -> ModifiedCounters {
    IntoIterator::into_iter([
        AudioStreamType::Background,
        AudioStreamType::Media,
        AudioStreamType::Interruption,
        AudioStreamType::SystemAgent,
        AudioStreamType::Communication,
        AudioStreamType::Accessibility,
    ])
    .map(|stream_type| (stream_type, 0))
    .collect()
}

pub(crate) const fn create_default_audio_stream(stream_type: AudioStreamType) -> AudioStream {
    AudioStream {
        stream_type,
        source: AudioSettingSource::User,
        user_volume_level: DEFAULT_VOLUME_LEVEL,
        user_volume_muted: DEFAULT_VOLUME_MUTED,
    }
}

pub fn build_audio_default_settings(
    config_logger: Rc<Mutex<InspectConfigLogger>>,
) -> DefaultSetting<AudioInfo, &'static str> {
    DefaultSetting::new(
        Some(DEFAULT_AUDIO_INFO),
        "/config/data/audio_config_data.json",
        config_logger,
    )
}

/// Returns a default audio [`AudioInfo`] that is derived from
/// [`DEFAULT_AUDIO_INFO`] with any fields specified in the
/// audio configuration set.
///
/// [`DEFAULT_AUDIO_INFO`]: static@DEFAULT_AUDIO_INFO
#[derive(Clone)]
pub struct AudioInfoLoader {
    audio_default_settings: Rc<Mutex<DefaultSetting<AudioInfo, &'static str>>>,
}

impl AudioInfoLoader {
    pub(crate) fn new(audio_default_settings: DefaultSetting<AudioInfo, &'static str>) -> Self {
        Self { audio_default_settings: Rc::new(Mutex::new(audio_default_settings)) }
    }
}

impl DefaultLoader for AudioInfoLoader {
    type Result = AudioInfo;

    fn default_value(&self) -> Self::Result {
        let mut default_audio_info: AudioInfo = DEFAULT_AUDIO_INFO.clone();

        if let Ok(Some(audio_configuration)) =
            self.audio_default_settings.lock().unwrap().get_cached_value()
        {
            default_audio_info.streams = audio_configuration.streams;
        }
        default_audio_info
    }
}

impl From<AudioInfo> for SettingInfo {
    fn from(audio: AudioInfo) -> SettingInfo {
        SettingInfo::Audio(audio)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fuchsia_async::TestExecutor;
    use fuchsia_inspect::component;

    use crate::audio::types::{AudioInfoV1, AudioInfoV2, AudioInfoV3};
    use crate::tests::helpers::move_executor_forward_and_get;
    use settings_storage::device_storage::DeviceStorageCompatible;

    const CONFIG_AUDIO_INFO: AudioInfo = AudioInfo {
        streams: [
            AudioStream {
                stream_type: AudioStreamType::Background,
                source: AudioSettingSource::System,
                user_volume_level: 0.6,
                user_volume_muted: true,
            },
            AudioStream {
                stream_type: AudioStreamType::Media,
                source: AudioSettingSource::System,
                user_volume_level: 0.7,
                user_volume_muted: true,
            },
            AudioStream {
                stream_type: AudioStreamType::Interruption,
                source: AudioSettingSource::System,
                user_volume_level: 0.2,
                user_volume_muted: true,
            },
            AudioStream {
                stream_type: AudioStreamType::SystemAgent,
                source: AudioSettingSource::User,
                user_volume_level: 0.3,
                user_volume_muted: true,
            },
            AudioStream {
                stream_type: AudioStreamType::Communication,
                source: AudioSettingSource::User,
                user_volume_level: 0.4,
                user_volume_muted: false,
            },
            AudioStream {
                stream_type: AudioStreamType::Accessibility,
                source: AudioSettingSource::User,
                user_volume_level: 0.35,
                user_volume_muted: false,
            },
        ],
        modified_counters: None,
    };

    /// Construct default audio settings and its dependencies.
    fn make_default_settings() -> DefaultSetting<AudioInfo, &'static str> {
        let config_logger =
            Rc::new(Mutex::new(InspectConfigLogger::new(component::inspector().root())));
        build_audio_default_settings(config_logger)
    }

    /// Load default settings from disk.
    fn load_default_settings(
        default_settings: &mut DefaultSetting<AudioInfo, &'static str>,
    ) -> AudioInfo {
        default_settings
            .load_default_value()
            .expect("if config exists, it should be parseable")
            .expect("default value should always exist")
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_audio_config() {
        let mut default_settings = make_default_settings();
        let current_from_storage = load_default_settings(&mut default_settings);
        // Ensure that settings are read from storage.
        assert_eq!(CONFIG_AUDIO_INFO, current_from_storage);
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_audio_info_migration_v1_to_v2() {
        let mut default_settings = make_default_settings();
        let mut v1_settings =
            AudioInfoV1::default_value(load_default_settings(&mut default_settings));
        let updated_mic_mute_val = !v1_settings.input.mic_mute;
        v1_settings.input.mic_mute = updated_mic_mute_val;
        v1_settings.streams[0].user_volume_level = 0.9;
        v1_settings.streams[0].user_volume_muted = false;

        let serialized_v1 = serde_json::to_string(&v1_settings).expect("default should serialize");
        let v2_from_v1 = AudioInfoV2::try_deserialize_from(&serialized_v1)
            .expect("deserialization should succeed");

        // Ensure that changes made in v1 are migrated to v2.
        assert_eq!(v2_from_v1.input.mic_mute, updated_mic_mute_val);
        assert_eq!(v2_from_v1.streams[0].user_volume_level, 0.9);
        assert_eq!(v2_from_v1.streams[0].user_volume_muted, false);
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_audio_info_migration_v2_to_v3() {
        let mut default_settings = make_default_settings();
        let mut v2_settings =
            AudioInfoV1::default_value(load_default_settings(&mut default_settings));
        v2_settings.streams[0].user_volume_level = 0.9;
        v2_settings.streams[0].user_volume_muted = false;

        let serialized_v2 = serde_json::to_string(&v2_settings).expect("default should serialize");
        let v3_from_v2 = AudioInfoV3::try_deserialize_from(&serialized_v2)
            .expect("deserialization should succeed");

        // Ensure that changes made in v2 are migrated to v3.
        assert_eq!(v3_from_v2.streams[0].user_volume_level, 0.9);
        assert_eq!(v3_from_v2.streams[0].user_volume_muted, false);
    }

    #[fuchsia::test]
    fn test_audio_info_migration_v3_to_current() {
        let mut executor = TestExecutor::new_with_fake_time();
        let mut default_settings = make_default_settings();
        let current_defaults = load_default_settings(&mut default_settings);

        let mut v3_settings = move_executor_forward_and_get(
            &mut executor,
            async { AudioInfoV3::default_value(current_defaults) },
            "Unable to get V3 default value",
        );
        v3_settings.streams[0].user_volume_level = 0.9;
        v3_settings.streams[0].user_volume_muted = false;

        let serialized_v3 = serde_json::to_string(&v3_settings).expect("default should serialize");
        let current_from_v3 = AudioInfo::try_deserialize_from(&serialized_v3)
            .expect("deserialization should succeed");

        // Ensure that changes made in v3 are migrated to current.
        assert_eq!(current_from_v3.streams[0].user_volume_level, 0.9);
        assert_eq!(current_from_v3.streams[0].user_volume_muted, false);
        // Ensure that migrating from v3 picks up a default for the new stream type.
        assert_eq!(current_from_v3.streams[5], DEFAULT_AUDIO_INFO.streams[5]);
    }

    #[fuchsia::test]
    fn test_audio_info_migration_v2_to_current() {
        let mut executor = TestExecutor::new_with_fake_time();
        let mut default_settings = make_default_settings();
        let current_defaults = load_default_settings(&mut default_settings);

        let mut v2_settings = move_executor_forward_and_get(
            &mut executor,
            async { AudioInfoV2::default_value(current_defaults) },
            "Unable to get V2 default value",
        );
        let updated_mic_mute_val = !v2_settings.input.mic_mute;
        v2_settings.input.mic_mute = updated_mic_mute_val;
        v2_settings.streams[0].user_volume_level = 0.9;
        v2_settings.streams[0].user_volume_muted = false;

        let serialized_v2 = serde_json::to_string(&v2_settings).expect("default should serialize");
        let current_from_v2 = AudioInfo::try_deserialize_from(&serialized_v2)
            .expect("deserialization should succeed");

        // Ensure that changes made in v2 are migrated to current.
        assert_eq!(current_from_v2.streams[0].user_volume_level, 0.9);
        assert_eq!(current_from_v2.streams[0].user_volume_muted, false);
        // Ensure that migrating from v2 picks up a default for the new stream type.
        assert_eq!(current_from_v2.streams[5], DEFAULT_AUDIO_INFO.streams[5]);
    }

    #[fuchsia::test]
    fn test_audio_info_migration_v1_to_current() {
        let mut executor = TestExecutor::new_with_fake_time();
        let mut default_settings = make_default_settings();
        let current_defaults = load_default_settings(&mut default_settings);

        let mut v1_settings = move_executor_forward_and_get(
            &mut executor,
            async { AudioInfoV1::default_value(current_defaults) },
            "Unable to get V1 default value",
        );
        let updated_mic_mute_val = !v1_settings.input.mic_mute;
        v1_settings.input.mic_mute = updated_mic_mute_val;
        v1_settings.streams[0].user_volume_level = 0.9;
        v1_settings.streams[0].user_volume_muted = false;

        let serialized_v1 = serde_json::to_string(&v1_settings).expect("default should serialize");
        let current_from_v1 = AudioInfo::try_deserialize_from(&serialized_v1)
            .expect("deserialization should succeed");

        // Ensure that changes made in v1 are migrated to current.
        assert_eq!(current_from_v1.streams[0].user_volume_level, 0.9);
        assert_eq!(current_from_v1.streams[0].user_volume_muted, false);
        // Ensure that migrating from v1 picks up a default for the new stream type.
        assert_eq!(current_from_v1.streams[5], DEFAULT_AUDIO_INFO.streams[5]);
    }
}