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
use std::error::Error;
use std::fmt::{Display, Formatter};

/// The requested host, although supported on this platform, is unavailable.
#[derive(Copy, Clone, Debug)]
pub struct HostUnavailable;

impl Display for HostUnavailable {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("the requested host is unavailable")
    }
}

impl Error for HostUnavailable {}

/// Some error has occurred that is specific to the backend from which it was produced.
///
/// This error is often used as a catch-all in cases where:
///
/// - It is unclear exactly what error might be produced by the backend API.
/// - It does not make sense to add a variant to the enclosing error type.
/// - No error was expected to occur at all, but we return an error to avoid the possibility of a
///   `panic!` caused by some unforeseen or unknown reason.
///
/// **Note:** If you notice a `BackendSpecificError` that you believe could be better handled in a
/// cross-platform manner, please create an issue or submit a pull request with a patch that adds
/// the necessary error variant to the appropriate error enum.
#[derive(Clone, Debug)]
pub struct BackendSpecificError {
    pub description: String,
}

impl Display for BackendSpecificError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "A backend-specific error has occurred: {}",
            self.description
        )
    }
}

impl Error for BackendSpecificError {}

/// An error that might occur while attempting to enumerate the available devices on a system.
#[derive(Clone, Debug)]
pub enum DevicesError {
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for DevicesError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
        }
    }
}

impl Error for DevicesError {}

impl From<BackendSpecificError> for DevicesError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}

/// An error that may occur while attempting to retrieve a device name.
#[derive(Clone, Debug)]
pub enum DeviceNameError {
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for DeviceNameError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
        }
    }
}

impl Error for DeviceNameError {}

impl From<BackendSpecificError> for DeviceNameError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}

/// Error that can happen when enumerating the list of supported formats.
#[derive(Debug)]
pub enum SupportedStreamConfigsError {
    /// The device no longer exists. This can happen if the device is disconnected while the
    /// program is running.
    DeviceNotAvailable,
    /// We called something the C-Layer did not understand
    InvalidArgument,
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for SupportedStreamConfigsError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
            Self::DeviceNotAvailable => f.write_str("The requested device is no longer available. For example, it has been unplugged."),
            Self::InvalidArgument => f.write_str("Invalid argument passed to the backend. For example, this happens when trying to read capture capabilities when the device does not support it.")
        }
    }
}

impl Error for SupportedStreamConfigsError {}

impl From<BackendSpecificError> for SupportedStreamConfigsError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}

/// May occur when attempting to request the default input or output stream format from a [`Device`](crate::Device).
#[derive(Debug)]
pub enum DefaultStreamConfigError {
    /// The device no longer exists. This can happen if the device is disconnected while the
    /// program is running.
    DeviceNotAvailable,
    /// Returned if e.g. the default input format was requested on an output-only audio device.
    StreamTypeNotSupported,
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for DefaultStreamConfigError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
            DefaultStreamConfigError::DeviceNotAvailable => f.write_str(
                "The requested device is no longer available. For example, it has been unplugged.",
            ),
            DefaultStreamConfigError::StreamTypeNotSupported => {
                f.write_str("The requested stream type is not supported by the device.")
            }
        }
    }
}

impl Error for DefaultStreamConfigError {}

impl From<BackendSpecificError> for DefaultStreamConfigError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}
/// Error that can happen when creating a [`Stream`](crate::Stream).
#[derive(Debug)]
pub enum BuildStreamError {
    /// The device no longer exists. This can happen if the device is disconnected while the
    /// program is running.
    DeviceNotAvailable,
    /// The specified stream configuration is not supported.
    StreamConfigNotSupported,
    /// We called something the C-Layer did not understand
    ///
    /// On ALSA device functions called with a feature they do not support will yield this. E.g.
    /// Trying to use capture capabilities on an output only format yields this.
    InvalidArgument,
    /// Occurs if adding a new Stream ID would cause an integer overflow.
    StreamIdOverflow,
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for BuildStreamError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
            BuildStreamError::DeviceNotAvailable => f.write_str(
                "The requested device is no longer available. For example, it has been unplugged.",
            ),
            BuildStreamError::StreamConfigNotSupported => {
                f.write_str("The requested stream configuration is not supported by the device.")
            }
            BuildStreamError::InvalidArgument => f.write_str(
                "The requested device does not support this capability (invalid argument)",
            ),
            BuildStreamError::StreamIdOverflow => {
                f.write_str("Adding a new stream ID would cause an overflow")
            }
        }
    }
}

impl Error for BuildStreamError {}

impl From<BackendSpecificError> for BuildStreamError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}

/// Errors that might occur when calling [`Stream::play()`](crate::traits::StreamTrait::play).
///
/// As of writing this, only macOS may immediately return an error while calling this method. This
/// is because both the alsa and wasapi backends only enqueue these commands and do not process
/// them immediately.
#[derive(Debug)]
pub enum PlayStreamError {
    /// The device associated with the stream is no longer available.
    DeviceNotAvailable,
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for PlayStreamError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
            PlayStreamError::DeviceNotAvailable => {
                f.write_str("the device associated with the stream is no longer available")
            }
        }
    }
}

impl Error for PlayStreamError {}

impl From<BackendSpecificError> for PlayStreamError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}

/// Errors that might occur when calling [`Stream::pause()`](crate::traits::StreamTrait::pause).
///
/// As of writing this, only macOS may immediately return an error while calling this method. This
/// is because both the alsa and wasapi backends only enqueue these commands and do not process
/// them immediately.
#[derive(Debug)]
pub enum PauseStreamError {
    /// The device associated with the stream is no longer available.
    DeviceNotAvailable,
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for PauseStreamError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
            PauseStreamError::DeviceNotAvailable => {
                f.write_str("the device associated with the stream is no longer available")
            }
        }
    }
}

impl Error for PauseStreamError {}

impl From<BackendSpecificError> for PauseStreamError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}

/// Errors that might occur while a stream is running.
#[derive(Debug)]
pub enum StreamError {
    /// The device no longer exists. This can happen if the device is disconnected while the
    /// program is running.
    DeviceNotAvailable,
    /// See the [`BackendSpecificError`] docs for more information about this error variant.
    BackendSpecific { err: BackendSpecificError },
}

impl Display for StreamError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BackendSpecific { err } => err.fmt(f),
            StreamError::DeviceNotAvailable => f.write_str(
                "The requested device is no longer available. For example, it has been unplugged.",
            ),
        }
    }
}

impl Error for StreamError {}

impl From<BackendSpecificError> for StreamError {
    fn from(err: BackendSpecificError) -> Self {
        Self::BackendSpecific { err }
    }
}