1use std::str::FromStr;
4
5use cpal::traits::{DeviceTrait, HostTrait};
6
7use crate::Error;
8
9const RATES: &[u32] = &[48_000, 44_100];
13
14const MAX_CHANNELS: u16 = 8;
17
18const FORMATS: &[cpal::SampleFormat] = &[
26 cpal::SampleFormat::F32,
27 cpal::SampleFormat::I32,
28 cpal::SampleFormat::I16,
29 cpal::SampleFormat::U16,
30];
31
32#[derive(Clone, Debug)]
34#[non_exhaustive]
35pub struct Device {
36 pub id: String,
40 pub name: String,
42 pub default: bool,
47 pub host: String,
52}
53
54pub async fn devices() -> Result<Vec<Device>, Error> {
56 tokio::task::spawn_blocking(list)
59 .await
60 .map_err(|err| Error::Playback(format!("audio host thread failed: {err}")))?
61}
62
63fn list() -> Result<Vec<Device>, Error> {
64 let preferred = cpal::default_host().id();
69 let mut devices = Vec::new();
70 let mut seen = std::collections::HashSet::new();
71
72 for id in cpal::available_hosts() {
73 let host = match cpal::host_from_id(id) {
76 Ok(host) => host,
77 Err(err) => {
78 tracing::debug!(host = id.name(), error = %err, "skipping an audio host that would not open");
79 continue;
80 }
81 };
82 let default = host.default_output_device().and_then(|d| d.id().ok());
83
84 let outputs = match host.output_devices() {
85 Ok(outputs) => outputs,
86 Err(err) => {
87 tracing::debug!(host = id.name(), error = %err, "skipping a host that would not list its outputs");
88 continue;
89 }
90 };
91 for device in outputs {
92 let Ok(device_id) = device.id() else {
93 tracing::debug!(host = id.name(), "skipping an output device with no id");
94 continue;
95 };
96 if !seen.insert(device_id.to_string()) {
98 continue;
99 }
100 devices.push(Device {
101 default: id == preferred && Some(&device_id) == default.as_ref(),
104 name: describe(&device, &device_id),
105 host: id.name().to_string(),
106 id: device_id.to_string(),
107 });
108 }
109 }
110
111 Ok(devices)
112}
113
114pub(super) fn open(selector: Option<&str>) -> Result<cpal::Device, Error> {
116 let Some(selector) = selector else {
117 return cpal::default_host()
118 .default_output_device()
119 .ok_or_else(|| Error::Device("no default output device".into()));
120 };
121
122 let id = cpal::DeviceId::from_str(selector).map_err(|err| Error::Device(format!("{selector:?}: {err}")))?;
125 let host = cpal::host_from_id(id.host()).map_err(|err| Error::Device(format!("{selector:?}: {err}")))?;
126 host.device_by_id(&id)
127 .ok_or_else(|| Error::Device(format!("output device {selector:?} not found")))
128}
129
130pub(super) fn negotiate(device: &cpal::Device) -> Result<cpal::SupportedStreamConfig, Error> {
138 let supported = device
139 .supported_output_configs()
140 .map_err(|err| Error::Playback(format!("cannot enumerate output configs: {err}")))?;
141
142 let native = device.default_output_config().ok().map(|config| config.channels());
146
147 choose(supported, native).ok_or_else(|| {
148 Error::Unsupported("output device offers no sample format and speaker layout we can write".into())
149 })
150}
151
152#[cfg_attr(
159 not(all(
160 feature = "pulseaudio",
161 any(
162 target_os = "linux",
163 target_os = "dragonfly",
164 target_os = "freebsd",
165 target_os = "netbsd"
166 )
167 )),
168 expect(unused_variables, reason = "only the PulseAudio host needs a size")
169)]
170pub(super) fn buffer_size(device: &cpal::Device, supported: &cpal::SupportedStreamConfig) -> cpal::BufferSize {
171 #[cfg(all(
173 feature = "pulseaudio",
174 any(
175 target_os = "linux",
176 target_os = "dragonfly",
177 target_os = "freebsd",
178 target_os = "netbsd"
179 )
180 ))]
181 if let (Ok(id), cpal::SupportedBufferSize::Range { min, max }) = (device.id(), supported.buffer_size())
182 && id.host() == cpal::HostId::PulseAudio
183 {
184 return cpal::BufferSize::Fixed((supported.sample_rate() / 50).clamp(*min, *max));
185 }
186 cpal::BufferSize::Default
187}
188
189fn choose(
195 supported: impl Iterator<Item = cpal::SupportedStreamConfigRange>,
196 native: Option<u16>,
197) -> Option<cpal::SupportedStreamConfig> {
198 supported
199 .filter(|config| FORMATS.contains(&config.sample_format()))
200 .filter(|config| (1..=MAX_CHANNELS).contains(&config.channels()))
201 .min_by_key(|config| preference(config, native))
202 .map(|config| match preferred_rate(&config) {
203 Some(rate) => config.try_with_sample_rate(rate).expect("a rate the range covers"),
204 None => config.with_max_sample_rate(),
205 })
206}
207
208fn preference(
217 config: &cpal::SupportedStreamConfigRange,
218 native: Option<u16>,
219) -> ((bool, std::cmp::Reverse<u16>), usize, std::cmp::Reverse<u32>, usize) {
220 let channels = (native != Some(config.channels()), std::cmp::Reverse(config.channels()));
221 let rate = match preferred_rate(config) {
222 Some(rate) => (RATES.iter().position(|r| *r == rate).expect("from RATES"), rate),
223 None => (RATES.len(), config.max_sample_rate()),
226 };
227 (
228 channels,
229 rate.0,
230 std::cmp::Reverse(rate.1),
231 rank(config.sample_format()),
232 )
233}
234
235fn preferred_rate(config: &cpal::SupportedStreamConfigRange) -> Option<u32> {
237 RATES
238 .iter()
239 .copied()
240 .find(|rate| config.min_sample_rate() <= *rate && *rate <= config.max_sample_rate())
241}
242
243fn rank(format: cpal::SampleFormat) -> usize {
248 FORMATS.iter().position(|f| *f == format).unwrap_or(FORMATS.len())
249}
250
251fn describe(device: &cpal::Device, id: &cpal::DeviceId) -> String {
254 device
255 .description()
256 .map(|d| d.name().to_string())
257 .unwrap_or_else(|_| id.id().to_string())
258}
259
260#[cfg(test)]
261mod tests {
262 use cpal::{SampleFormat, SupportedBufferSize, SupportedStreamConfigRange};
263
264 use super::*;
265
266 fn range(channels: u16, rate: u32, format: SampleFormat) -> SupportedStreamConfigRange {
267 SupportedStreamConfigRange::new(channels, rate, rate, SupportedBufferSize::Unknown, format)
268 }
269
270 #[test]
274 fn stereo_wins_even_when_the_device_lists_mono_first() {
275 let chosen = choose(
276 [range(1, 48_000, SampleFormat::F32), range(2, 48_000, SampleFormat::F32)].into_iter(),
277 None,
278 )
279 .expect("a config");
280 assert_eq!(chosen.channels(), 2);
281 }
282
283 #[test]
285 fn mono_is_taken_when_that_is_all_there_is() {
286 let chosen = choose([range(1, 48_000, SampleFormat::F32)].into_iter(), None).expect("a config");
287 assert_eq!(chosen.channels(), 1);
288 }
289
290 #[test]
292 fn a_surround_only_device_opens() {
293 let chosen = choose([range(6, 48_000, SampleFormat::F32)].into_iter(), None).expect("a config");
294 assert_eq!(chosen.channels(), 6);
295 }
296
297 #[test]
299 fn six_channels_are_chosen_when_offered() {
300 let offered = || [range(2, 48_000, SampleFormat::F32), range(6, 48_000, SampleFormat::F32)].into_iter();
301 assert_eq!(choose(offered(), None).expect("a config").channels(), 6);
302 assert_eq!(choose(offered(), Some(6)).expect("a config").channels(), 6);
303 }
304
305 #[test]
309 fn the_native_count_beats_the_widest() {
310 let offered = (1..=8).map(|channels| range(channels, 48_000, SampleFormat::F32));
311 assert_eq!(choose(offered, Some(2)).expect("a config").channels(), 2);
312 }
313
314 #[test]
317 fn counts_without_a_layout_are_refused() {
318 assert!(choose([range(12, 48_000, SampleFormat::F32)].into_iter(), Some(12)).is_none());
319 let chosen = choose(
320 [
321 range(12, 48_000, SampleFormat::F32),
322 range(2, 48_000, SampleFormat::F32),
323 ]
324 .into_iter(),
325 Some(12),
326 )
327 .expect("a config");
328 assert_eq!(chosen.channels(), 2);
329 }
330
331 #[test]
335 fn channels_outrank_the_sample_rate() {
336 let chosen = choose(
337 [range(1, 48_000, SampleFormat::F32), range(2, 44_100, SampleFormat::F32)].into_iter(),
338 None,
339 )
340 .expect("a config");
341 assert_eq!((chosen.channels(), chosen.sample_rate()), (2, 44_100));
342 }
343
344 #[test]
347 fn f32_is_preferred_over_a_format_we_convert_to() {
348 let chosen = choose(
349 [range(2, 48_000, SampleFormat::I16), range(2, 48_000, SampleFormat::F32)].into_iter(),
350 None,
351 )
352 .expect("a config");
353 assert_eq!(chosen.sample_format(), SampleFormat::F32);
354 }
355
356 #[test]
359 fn a_device_we_cannot_write_to_is_rejected() {
360 assert!(choose([range(2, 48_000, SampleFormat::I8)].into_iter(), None).is_none());
361 assert!(choose(std::iter::empty(), None).is_none());
362 }
363
364 #[test]
371 fn stereo_at_an_awkward_rate_beats_mono_at_a_preferred_one() {
372 let chosen = choose(
373 [range(1, 48_000, SampleFormat::F32), range(2, 96_000, SampleFormat::F32)].into_iter(),
374 None,
375 )
376 .expect("a config");
377 assert_eq!((chosen.channels(), chosen.sample_rate()), (2, 96_000));
378 }
379
380 #[test]
383 fn stereo_beats_mono_when_neither_is_on_a_preferred_rate() {
384 let chosen = choose(
385 [
386 range(1, 192_000, SampleFormat::F32),
387 range(2, 96_000, SampleFormat::F32),
388 ]
389 .into_iter(),
390 None,
391 )
392 .expect("a config");
393 assert_eq!((chosen.channels(), chosen.sample_rate()), (2, 96_000));
394 }
395
396 #[test]
399 fn the_last_resort_takes_the_highest_rate() {
400 let chosen = choose(
401 [
402 range(2, 96_000, SampleFormat::I16),
403 range(2, 96_000, SampleFormat::F32),
404 range(2, 32_000, SampleFormat::F32),
405 ]
406 .into_iter(),
407 None,
408 )
409 .expect("a config");
410 assert_eq!(
411 (chosen.sample_rate(), chosen.sample_format()),
412 (96_000, SampleFormat::F32)
413 );
414 }
415}