settings/audio/
types.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
// Copyright 2021 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::audio_default_settings::AudioInfoLoader;
use crate::audio::{create_default_modified_counters, ModifiedCounters};
use anyhow::{anyhow, Error};
use serde::{Deserialize, Serialize};
use settings_storage::device_storage::DeviceStorageCompatible;
use std::collections::HashMap;
use std::ops::RangeInclusive;

const RANGE: RangeInclusive<f32> = 0.0..=1.0;

#[derive(PartialEq, Eq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum AudioSettingSource {
    User,
    System,
    SystemWithFeedback,
}

#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize, Hash, Eq)]
pub enum AudioStreamType {
    Background,
    Media,
    Interruption,
    SystemAgent,
    Communication,
}

#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct AudioStream {
    pub stream_type: AudioStreamType,
    pub source: AudioSettingSource,
    pub user_volume_level: f32,
    pub user_volume_muted: bool,
}

impl AudioStream {
    pub(crate) fn has_valid_volume_level(&self) -> bool {
        RANGE.contains(&self.user_volume_level)
    }
}

#[derive(PartialEq, Debug, Clone, Copy)]
pub struct SetAudioStream {
    pub stream_type: AudioStreamType,
    pub source: AudioSettingSource,
    pub user_volume_level: Option<f32>,
    pub user_volume_muted: Option<bool>,
}

impl SetAudioStream {
    pub(crate) fn has_valid_volume_level(&self) -> bool {
        self.user_volume_level.map(|v| RANGE.contains(&v)).unwrap_or(true)
    }

    pub(crate) fn is_valid_payload(&self) -> bool {
        self.user_volume_level.is_some() || self.user_volume_muted.is_some()
    }
}

impl From<AudioStream> for SetAudioStream {
    fn from(stream: AudioStream) -> Self {
        Self {
            stream_type: stream.stream_type,
            source: stream.source,
            user_volume_level: Some(stream.user_volume_level),
            user_volume_muted: Some(stream.user_volume_muted),
        }
    }
}

#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct AudioInfo {
    pub streams: [AudioStream; 5],
    pub modified_counters: Option<ModifiedCounters>,
}

impl DeviceStorageCompatible for AudioInfo {
    type Loader = AudioInfoLoader;
    const KEY: &'static str = "audio_info";

    fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        Self::extract(value).or_else(|_| AudioInfoV2::try_deserialize_from(value).map(Self::from))
    }
}

////////////////////////////////////////////////////////////////
/// Past versions of AudioInfo.
////////////////////////////////////////////////////////////////

#[derive(PartialEq, Eq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct AudioInputInfo {
    pub mic_mute: bool,
}

/// The following struct should never be modified. It represents an old
/// version of the audio settings.
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct AudioInfoV2 {
    pub streams: [AudioStream; 5],
    pub input: AudioInputInfo,
    pub modified_counters: Option<ModifiedCounters>,
}

impl AudioInfoV2 {
    pub(super) fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        serde_json::from_str(value)
            .map_err(|e| anyhow!("could not deserialize: {e:?}"))
            .or_else(|_| AudioInfoV1::try_deserialize_from(value).map(Self::from))
    }

    #[cfg(test)]
    pub(super) fn default_value(default_setting: AudioInfo) -> Self {
        AudioInfoV2 {
            streams: default_setting.streams,
            input: AudioInputInfo { mic_mute: false },
            modified_counters: None,
        }
    }
}

impl From<AudioInfoV2> for AudioInfo {
    fn from(v2: AudioInfoV2) -> AudioInfo {
        AudioInfo { streams: v2.streams, modified_counters: v2.modified_counters }
    }
}

/// The following struct should never be modified. It represents an old
/// version of the audio settings.
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct AudioInfoV1 {
    pub streams: [AudioStream; 5],
    pub input: AudioInputInfo,
    pub modified_timestamps: Option<HashMap<AudioStreamType, String>>,
}

impl AudioInfoV1 {
    pub(super) fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        serde_json::from_str(value)
            .map_err(|e| anyhow!("could not deserialize: {e:?}"))
            .or_else(|_| AudioInfoV1::try_deserialize_from(value).map(Self::from))
    }

    #[cfg(test)]
    pub(super) fn default_value(default_setting: AudioInfo) -> Self {
        AudioInfoV1 {
            streams: default_setting.streams,
            input: AudioInputInfo { mic_mute: false },
            modified_timestamps: None,
        }
    }
}

impl From<AudioInfoV1> for AudioInfoV2 {
    fn from(v1: AudioInfoV1) -> Self {
        AudioInfoV2 {
            streams: v1.streams,
            input: v1.input,
            modified_counters: Some(create_default_modified_counters()),
        }
    }
}

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

    const VALID_AUDIO_STREAM: AudioStream = AudioStream {
        stream_type: AudioStreamType::Background,
        source: AudioSettingSource::User,
        user_volume_level: 0.5,
        user_volume_muted: false,
    };
    const INVALID_NEGATIVE_AUDIO_STREAM: AudioStream =
        AudioStream { user_volume_level: -0.1, ..VALID_AUDIO_STREAM };
    const INVALID_GREATER_THAN_ONE_AUDIO_STREAM: AudioStream =
        AudioStream { user_volume_level: 1.1, ..VALID_AUDIO_STREAM };

    #[fuchsia::test]
    fn test_volume_level_validation() {
        assert!(VALID_AUDIO_STREAM.has_valid_volume_level());
        assert!(!INVALID_NEGATIVE_AUDIO_STREAM.has_valid_volume_level());
        assert!(!INVALID_GREATER_THAN_ONE_AUDIO_STREAM.has_valid_volume_level());
    }

    #[fuchsia::test]
    fn test_set_audio_stream_validation() {
        let valid_set_audio_stream = SetAudioStream::from(VALID_AUDIO_STREAM);
        assert!(valid_set_audio_stream.has_valid_volume_level());
        let invalid_set_audio_stream = SetAudioStream::from(INVALID_NEGATIVE_AUDIO_STREAM);
        assert!(!invalid_set_audio_stream.has_valid_volume_level());
        let invalid_set_audio_stream = SetAudioStream::from(INVALID_GREATER_THAN_ONE_AUDIO_STREAM);
        assert!(!invalid_set_audio_stream.has_valid_volume_level());
    }
}