rodio 0.22.2

Audio playback and recording library
Documentation
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use std::{fmt::Debug, marker::PhantomData};

use cpal::{
    traits::{DeviceTrait, HostTrait},
    SupportedStreamConfigRange,
};

use crate::{
    common::assert_error_traits, microphone::config::InputConfig, ChannelCount, SampleRate,
};

use super::Microphone;

/// Error configuring or opening microphone input
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error, Clone)]
pub enum Error {
    /// No input device is available on the system.
    #[error("There is no input device")]
    NoDevice,
    /// Failed to get the default input configuration for the device.
    #[error("Could not get default input configuration for input device: '{device_name}'")]
    DefaultInputConfig {
        #[source]
        source: cpal::DefaultStreamConfigError,
        device_name: String,
    },
    /// Failed to get the supported input configurations for the device.
    #[error("Could not get supported input configurations for input device: '{device_name}'")]
    InputConfigs {
        #[source]
        source: cpal::SupportedStreamConfigsError,
        device_name: String,
    },
    /// The requested input configuration is not supported by the device.
    #[error("The input configuration is not supported by input device: '{device_name}'")]
    UnsupportedByDevice { device_name: String },
}
assert_error_traits! {Error}

/// Generic on the `MicrophoneBuilder` which is only present when a device has been set.
/// Methods needing a config are only available on MicrophoneBuilder with this
/// Generic set.
pub struct DeviceIsSet;
/// Generic on the `MicrophoneBuilder` which is only present when a config has been set.
/// Methods needing a device set are only available on MicrophoneBuilder with this
/// Generic set.
pub struct ConfigIsSet;

/// Generic on the `MicrophoneBuilder` which indicates no config has been set.
/// Some methods are only available when this types counterpart: `ConfigIsSet` is present.
pub struct ConfigNotSet;
/// Generic on the `MicrophoneBuilder` which indicates no device has been set.
/// Some methods are only available when this types counterpart: `DeviceIsSet` is present.
pub struct DeviceNotSet;

/// Builder for configuring and opening microphone input streams.
#[must_use]
pub struct MicrophoneBuilder<Device, Config, E = fn(cpal::StreamError)>
where
    E: FnMut(cpal::StreamError) + Send + Clone + 'static,
{
    device: Option<(cpal::Device, Vec<SupportedStreamConfigRange>)>,
    config: Option<super::config::InputConfig>,
    error_callback: E,

    device_set: PhantomData<Device>,
    config_set: PhantomData<Config>,
}

impl<Device, Config, E> Debug for MicrophoneBuilder<Device, Config, E>
where
    E: FnMut(cpal::StreamError) + Send + Clone + 'static,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MicrophoneBuilder")
            .field(
                "device",
                &self.device.as_ref().map(|d| {
                    d.0.description()
                        .ok()
                        .map_or("unknown".to_string(), |d| d.name().to_string())
                }),
            )
            .field("config", &self.config)
            .finish()
    }
}

impl Default for MicrophoneBuilder<DeviceNotSet, ConfigNotSet> {
    fn default() -> Self {
        Self {
            device: None,
            config: None,
            error_callback: default_error_callback,

            device_set: PhantomData,
            config_set: PhantomData,
        }
    }
}

fn default_error_callback(err: cpal::StreamError) {
    #[cfg(feature = "tracing")]
    tracing::error!("audio stream error: {err}");
    #[cfg(not(feature = "tracing"))]
    eprintln!("audio stream error: {err}");
}

impl MicrophoneBuilder<DeviceNotSet, ConfigNotSet, fn(cpal::StreamError)> {
    /// Creates a new microphone builder.
    ///
    /// # Example
    /// ```no_run
    /// let builder = rodio::microphone::MicrophoneBuilder::new();
    /// ```
    pub fn new() -> MicrophoneBuilder<DeviceNotSet, ConfigNotSet, fn(cpal::StreamError)> {
        Self::default()
    }
}

impl<Device, Config, E> MicrophoneBuilder<Device, Config, E>
where
    E: FnMut(cpal::StreamError) + Send + Clone + 'static,
{
    /// Sets the input device to use.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::{MicrophoneBuilder, available_inputs};
    /// let input = available_inputs()?.remove(2);
    /// let builder = MicrophoneBuilder::new().device(input)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn device(
        &self,
        device: super::Input,
    ) -> Result<MicrophoneBuilder<DeviceIsSet, ConfigNotSet, E>, Error> {
        let device = device.into_inner();
        let supported_configs = device
            .supported_input_configs()
            .map_err(|source| Error::InputConfigs {
                source,
                device_name: device
                    .description()
                    .ok()
                    .map_or("unknown".to_string(), |d| d.name().to_string()),
            })?
            .collect();
        Ok(MicrophoneBuilder {
            device: Some((device, supported_configs)),
            config: self.config,
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        })
    }

    /// Uses the system's default input device.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new().default_device()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn default_device(&self) -> Result<MicrophoneBuilder<DeviceIsSet, ConfigNotSet, E>, Error> {
        let default_device = cpal::default_host()
            .default_input_device()
            .ok_or(Error::NoDevice)?;
        let supported_configs = default_device
            .supported_input_configs()
            .map_err(|source| Error::InputConfigs {
                source,
                device_name: default_device
                    .description()
                    .ok()
                    .map_or("unknown".to_string(), |d| d.name().to_string()),
            })?
            .collect();
        Ok(MicrophoneBuilder {
            device: Some((default_device, supported_configs)),
            config: self.config,
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        })
    }
}

impl<Config, E> MicrophoneBuilder<DeviceIsSet, Config, E>
where
    E: FnMut(cpal::StreamError) + Send + Clone + 'static,
{
    /// Uses the device's default input configuration.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn default_config(&self) -> Result<MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E>, Error> {
        let device = &self.device.as_ref().expect("DeviceIsSet").0;
        let default_config: InputConfig = device
            .default_input_config()
            .map_err(|source| Error::DefaultInputConfig {
                source,
                device_name: device
                    .description()
                    .ok()
                    .map_or("unknown".to_string(), |d| d.name().to_string()),
            })?
            .into();

        // Lets try getting f32 output from the default config, as thats
        // what rodio uses internally
        let config = if self
            .check_config(&default_config.with_f32_samples())
            .is_ok()
        {
            default_config.with_f32_samples()
        } else {
            default_config
        };

        Ok(MicrophoneBuilder {
            device: self.device.clone(),
            config: Some(config),
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        })
    }

    /// Sets a custom input configuration.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::{MicrophoneBuilder, InputConfig};
    /// # use std::num::NonZero;
    /// let config = InputConfig {
    ///     sample_rate: NonZero::new(44_100).expect("44100 is not zero"),
    ///     channel_count: NonZero::new(2).expect("2 is not zero"),
    ///     buffer_size: cpal::BufferSize::Fixed(42_000),
    ///     sample_format: cpal::SampleFormat::U16,
    /// };
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .config(config)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn config(
        &self,
        config: InputConfig,
    ) -> Result<MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E>, Error> {
        self.check_config(&config)?;

        Ok(MicrophoneBuilder {
            device: self.device.clone(),
            config: Some(config),
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        })
    }

    fn check_config(&self, config: &InputConfig) -> Result<(), Error> {
        let (device, supported_configs) = self.device.as_ref().expect("DeviceIsSet");
        if !supported_configs
            .iter()
            .any(|range| config.supported_given(range))
        {
            Err(Error::UnsupportedByDevice {
                device_name: device
                    .description()
                    .ok()
                    .map_or("unknown".to_string(), |d| d.name().to_string()),
            })
        } else {
            Ok(())
        }
    }
}

impl<E> MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E>
where
    E: FnMut(cpal::StreamError) + Send + Clone + 'static,
{
    /// Sets the sample rate for input.
    ///
    /// # Error
    /// Returns an error if the requested sample rate combined with the
    /// other parameters can not be supported.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     .try_sample_rate(44_100.try_into()?)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_sample_rate(
        &self,
        sample_rate: SampleRate,
    ) -> Result<MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E>, Error> {
        let mut new_config = self.config.expect("ConfigIsSet");
        new_config.sample_rate = sample_rate;
        self.check_config(&new_config)?;

        Ok(MicrophoneBuilder {
            device: self.device.clone(),
            config: Some(new_config),
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        })
    }

    /// Try multiple sample rates, fall back to the default it non match. The
    /// sample rates are in order of preference. If the first can be supported
    /// the second will never be tried.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     // 16k or its double with can trivially be resampled to 16k
    ///     .prefer_sample_rates([
    ///         16_000.try_into().expect("not zero"),
    ///         32_000.try_into().expect("not_zero"),
    ///     ]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn prefer_sample_rates(
        &self,
        sample_rates: impl IntoIterator<Item = SampleRate>,
    ) -> MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E> {
        self.set_preferred_if_supported(sample_rates, |config, sample_rate| {
            config.sample_rate = sample_rate
        })
    }

    fn set_preferred_if_supported<T>(
        &self,
        options: impl IntoIterator<Item = T>,
        setter: impl Fn(&mut InputConfig, T),
    ) -> MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E> {
        let mut config = self.config.expect("ConfigIsSet");
        let mut final_config = config;

        for option in options.into_iter() {
            setter(&mut config, option);
            if self.check_config(&config).is_ok() {
                final_config = config;
                break;
            }
        }

        MicrophoneBuilder {
            device: self.device.clone(),
            config: Some(final_config),
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        }
    }

    /// Sets the number of input channels.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     .try_channels(2.try_into()?)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_channels(
        &self,
        channel_count: ChannelCount,
    ) -> Result<MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E>, Error> {
        let mut new_config = self.config.expect("ConfigIsSet");
        new_config.channel_count = channel_count;
        self.check_config(&new_config)?;

        Ok(MicrophoneBuilder {
            device: self.device.clone(),
            config: Some(new_config),
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        })
    }

    /// Try multiple channel counts, fall back to the default it non match. The
    /// channel counts are in order of preference. If the first can be supported
    /// the second will never be tried.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     // We want mono, if thats not possible give
    ///     // us the lowest channel count
    ///     .prefer_channel_counts([
    ///         1.try_into().expect("not zero"),
    ///         2.try_into().expect("not_zero"),
    ///         3.try_into().expect("not_zero"),
    ///     ]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn prefer_channel_counts(
        &self,
        channel_counts: impl IntoIterator<Item = ChannelCount>,
    ) -> MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E> {
        self.set_preferred_if_supported(channel_counts, |config, count| {
            config.channel_count = count
        })
    }

    /// Sets the buffer size for the input.
    ///
    /// This has no impact on latency, though a too small buffer can lead to audio
    /// artifacts if your program can not get samples out of the buffer before they
    /// get overridden again.
    ///
    /// Normally the default input config will have this set up correctly.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     .try_buffer_size(4096)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_buffer_size(
        &self,
        buffer_size: u32,
    ) -> Result<MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E>, Error> {
        let mut new_config = self.config.expect("ConfigIsSet");
        new_config.buffer_size = cpal::BufferSize::Fixed(buffer_size);
        self.check_config(&new_config)?;

        Ok(MicrophoneBuilder {
            device: self.device.clone(),
            config: Some(new_config),
            error_callback: self.error_callback.clone(),
            device_set: PhantomData,
            config_set: PhantomData,
        })
    }

    /// See the docs of [`try_buffer_size`](MicrophoneBuilder::try_buffer_size)
    /// for more.
    ///
    /// Try multiple buffer sizes, fall back to the default it non match. The
    /// buffer sizes are in order of preference. If the first can be supported
    /// the second will never be tried.
    ///
    /// # Note
    /// We will not try buffer sizes larger then 100_000 to prevent this
    /// from hanging too long on open ranges.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     .prefer_buffer_sizes([
    ///         2048.try_into().expect("not zero"),
    ///         4096.try_into().expect("not_zero"),
    ///     ]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Get the smallest buffer size larger then 512.
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     .prefer_buffer_sizes(4096..);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn prefer_buffer_sizes(
        &self,
        buffer_sizes: impl IntoIterator<Item = u32>,
    ) -> MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E> {
        let buffer_sizes = buffer_sizes.into_iter().take_while(|size| *size < 100_000);

        self.set_preferred_if_supported(buffer_sizes, |config, size| {
            config.buffer_size = cpal::BufferSize::Fixed(size)
        })
    }
}

impl<Device, E> MicrophoneBuilder<Device, ConfigIsSet, E>
where
    E: FnMut(cpal::StreamError) + Send + Clone + 'static,
{
    /// Returns the current input configuration.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// let builder = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?;
    /// let config = builder.get_config();
    /// println!("Sample rate: {}", config.sample_rate.get());
    /// println!("Channel count: {}", config.channel_count.get());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn get_config(&self) -> InputConfig {
        self.config.expect("ConfigIsSet")
    }
}

impl<E> MicrophoneBuilder<DeviceIsSet, ConfigIsSet, E>
where
    E: FnMut(cpal::StreamError) + Send + Clone + 'static,
{
    /// Opens the microphone input stream.
    ///
    /// # Example
    /// ```no_run
    /// # use rodio::microphone::MicrophoneBuilder;
    /// # use rodio::Source;
    /// # use std::time::Duration;
    /// let mic = MicrophoneBuilder::new()
    ///     .default_device()?
    ///     .default_config()?
    ///     .open_stream()?;
    /// let recording = mic.take_duration(Duration::from_secs(3)).record();
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_stream(&self) -> Result<Microphone, super::OpenError> {
        Microphone::open(
            self.device.as_ref().expect("DeviceIsSet").0.clone(),
            *self.config.as_ref().expect("ConfigIsSet"),
            self.error_callback.clone(),
        )
    }
}