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
// 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};
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; 5] = [
    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),
];

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,
    ])
    .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};
    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,
            },
        ],
        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 settings = make_default_settings();
        let settings = load_default_settings(&mut settings);
        assert_eq!(CONFIG_AUDIO_INFO, settings);
    }

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

        let serialized_v1 = serde_json::to_string(&v1).expect("default should serialize");

        let v2 = AudioInfoV2::try_deserialize_from(&serialized_v1)
            .expect("deserialization should succeed");

        assert_eq!(v2.input.mic_mute, updated_mic_mute_val);
    }

    #[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 settings = load_default_settings(&mut default_settings);

        let mut v2 = move_executor_forward_and_get(
            &mut executor,
            async { AudioInfoV2::default_value(settings) },
            "Unable to get V2 default value",
        );
        let updated_mic_mute_val = !v2.input.mic_mute;
        v2.input.mic_mute = updated_mic_mute_val;

        let serialized_v2 = serde_json::to_string(&v2).expect("default should serialize");

        let current = AudioInfo::try_deserialize_from(&serialized_v2)
            .expect("deserialization should succeed");

        let loader = AudioInfoLoader::new(default_settings);
        assert_eq!(current, loader.default_value());
    }

    #[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 settings = load_default_settings(&mut default_settings);

        let mut v1 = move_executor_forward_and_get(
            &mut executor,
            async { AudioInfoV1::default_value(settings) },
            "Unable to get V1 default value",
        );
        let updated_mic_mute_val = !v1.input.mic_mute;
        v1.input.mic_mute = updated_mic_mute_val;

        let serialized_v1 = serde_json::to_string(&v1).expect("default should serialize");

        let current = AudioInfo::try_deserialize_from(&serialized_v1)
            .expect("deserialization should succeed");

        let loader = AudioInfoLoader::new(default_settings);
        assert_eq!(current, loader.default_value());
    }
}