BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / devices.rs

devices.rs

devices.rs 17.8 KiB Download Raw
1use std::sync::OnceLock;
2
3use libwebrtc::peer_connection_factory::PeerConnectionFactory;
4use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
5
6pub const DEFAULT_DEVICE_LABEL: &str = "Default device";
7const SYSTEM_ALIAS_PREFIXES: [&str; 3] = ["default", "communication", "sysdefault"];
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct AudioDevice {
11 pub index: u16,
12 pub guid: String,
13 pub name: String,
14}
15
16#[derive(Debug, Clone, Default, PartialEq, Eq)]
17pub enum DeviceChoice {
18 #[default]
19 SystemDefault,
20 Device(String),
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct DeviceEntry {
25 pub choice: DeviceChoice,
26 pub label: String,
27}
28
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub struct DeviceLists {
31 pub inputs: Vec<AudioDevice>,
32 pub outputs: Vec<AudioDevice>,
33}
34
35impl AudioDevice {
36 pub fn key(&self) -> String {
37 if self.guid.is_empty() {
38 self.name.clone()
39 } else {
40 self.guid.clone()
41 }
42 }
43
44 fn is_system_alias(&self) -> bool {
45 let name = self.name.to_lowercase();
46 let guid = self.guid.to_lowercase();
47 SYSTEM_ALIAS_PREFIXES
48 .iter()
49 .any(|prefix| name.starts_with(prefix) || guid == *prefix)
50 }
51}
52
53pub fn menu_entries(devices: &[AudioDevice]) -> Vec<DeviceEntry> {
54 let default_entry = DeviceEntry {
55 choice: DeviceChoice::SystemDefault,
56 label: DEFAULT_DEVICE_LABEL.to_owned(),
57 };
58 let named = devices
59 .iter()
60 .filter(|device| !device.is_system_alias() && !device.name.trim().is_empty())
61 .map(|device| DeviceEntry {
62 choice: DeviceChoice::Device(device.key()),
63 label: device.name.clone(),
64 });
65 std::iter::once(default_entry).chain(named).collect()
66}
67
68impl DeviceLists {
69 pub fn input_entries(&self) -> Vec<DeviceEntry> {
70 menu_entries(&self.inputs)
71 }
72
73 pub fn output_entries(&self) -> Vec<DeviceEntry> {
74 menu_entries(&self.outputs)
75 }
76}
77
78pub fn shared_factory() -> PeerConnectionFactory {
79 static FACTORY: OnceLock<PeerConnectionFactory> = OnceLock::new();
80 FACTORY.get_or_init(PeerConnectionFactory::default).clone()
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Flow {
85 Capture,
86 Render,
87}
88
89/// Endpoint id of the Windows default audio device (preferring eConsole to match the Windows
90/// taskbar switcher and AdmProxy::SystemDefaultFor, with fallback to eCommunications).
91#[cfg(windows)]
92pub fn system_default_id(flow: Flow) -> Option<String> {
93 use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
94 let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok();
95 let id = default_endpoint_id(flow);
96 if initialized {
97 unsafe { CoUninitialize() };
98 }
99 id
100}
101
102#[cfg(windows)]
103fn default_endpoint_id(flow: Flow) -> Option<String> {
104 use windows::Win32::Media::Audio::{
105 IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eConsole, eRender,
106 };
107 use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
108 let data_flow = match flow {
109 Flow::Capture => eCapture,
110 Flow::Render => eRender,
111 };
112 unsafe {
113 let enumerator: IMMDeviceEnumerator =
114 CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;
115 let device = enumerator
116 .GetDefaultAudioEndpoint(data_flow, eConsole)
117 .or_else(|_| enumerator.GetDefaultAudioEndpoint(data_flow, eCommunications))
118 .ok()?;
119 let id = device.GetId().ok()?;
120 let text = id.to_string().ok();
121 CoTaskMemFree(Some(id.0 as *const _));
122 text
123 }
124}
125
126#[cfg(not(windows))]
127pub fn system_default_id(_flow: Flow) -> Option<String> {
128 None
129}
130
131pub fn resolve_index(
132 devices: &[AudioDevice],
133 choice: &DeviceChoice,
134 system_default: Option<&str>,
135) -> Option<u16> {
136 match choice {
137 DeviceChoice::SystemDefault => system_default
138 .and_then(|id| {
139 devices
140 .iter()
141 .find(|device| device.guid.eq_ignore_ascii_case(id))
142 })
143 .or_else(|| devices.iter().find(|device| device.is_system_alias()))
144 .or(devices.first())
145 .map(|device| device.index),
146 DeviceChoice::Device(key) => devices
147 .iter()
148 .find(|device| device.key().eq_ignore_ascii_case(key))
149 .map(|device| device.index),
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct AppliedDevice {
155 pub index: u16,
156 pub key: String,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum Reselect {
161 Keep,
162 Select(u16),
163 FallBack(u16),
164}
165
166pub fn applied_device(
167 devices: &[AudioDevice],
168 choice: &DeviceChoice,
169 system_default: Option<&str>,
170) -> Option<AppliedDevice> {
171 let index = resolve_index(devices, choice, system_default)?;
172 device_at(devices, index)
173}
174
175fn device_at(devices: &[AudioDevice], index: u16) -> Option<AppliedDevice> {
176 devices
177 .iter()
178 .find(|device| device.index == index)
179 .map(|device| AppliedDevice {
180 index,
181 key: device.key(),
182 })
183}
184
185pub fn reselect(
186 applied: Option<&AppliedDevice>,
187 devices: &[AudioDevice],
188 choice: &DeviceChoice,
189 system_default: Option<&str>,
190) -> Reselect {
191 let unchanged = |index: u16| device_at(devices, index).as_ref() == applied;
192 match resolve_index(devices, choice, system_default) {
193 Some(index) if unchanged(index) => Reselect::Keep,
194 Some(index) => Reselect::Select(index),
195 None => match resolve_index(devices, &DeviceChoice::SystemDefault, system_default) {
196 Some(index) if !unchanged(index) && matches!(choice, DeviceChoice::Device(_)) => {
197 Reselect::FallBack(index)
198 }
199 _ => Reselect::Keep,
200 },
201 }
202}
203
204pub fn disconnect_notice(
205 previous: &[AudioDevice],
206 choice: &DeviceChoice,
207 fallback: Option<&AudioDevice>,
208) -> String {
209 let lost = previous
210 .iter()
211 .find(|device| matches!(choice, DeviceChoice::Device(key) if device.key() == *key))
212 .map_or("Device", |device| device.name.as_str());
213 match fallback {
214 Some(device) => format!("{lost} disconnected. Using {}.", device.name),
215 None => format!("{lost} disconnected."),
216 }
217}
218
219fn enumerate(factory: &PeerConnectionFactory) -> DeviceLists {
220 let inputs = (0..factory.recording_devices().max(0) as u16)
221 .map(|index| AudioDevice {
222 index,
223 guid: factory.recording_device_guid(index),
224 name: factory.recording_device_name(index),
225 })
226 .collect();
227 let outputs = (0..factory.playout_devices().max(0) as u16)
228 .map(|index| AudioDevice {
229 index,
230 guid: factory.playout_device_guid(index),
231 name: factory.playout_device_name(index),
232 })
233 .collect();
234 DeviceLists { inputs, outputs }
235}
236
237pub fn list_devices(factory: &PeerConnectionFactory) -> DeviceLists {
238 if !factory.acquire_platform_adm() {
239 return DeviceLists::default();
240 }
241 let lists = enumerate(factory);
242 factory.release_platform_adm();
243 lists
244}
245
246fn default_for(choice: &DeviceChoice, flow: Flow) -> Option<String> {
247 (*choice == DeviceChoice::SystemDefault)
248 .then(|| system_default_id(flow))
249 .flatten()
250}
251
252pub fn device_switch_applied(selected: bool, started: bool) -> bool {
253 selected && started
254}
255
256pub fn input_label(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> Option<String> {
257 let DeviceChoice::Device(key) = choice else {
258 return None;
259 };
260 enumerate(factory)
261 .inputs
262 .into_iter()
263 .find(|device| device.key().eq_ignore_ascii_case(key))
264 .map(|device| device.name)
265}
266
267pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
268 let Some(index) = resolve_index(
269 &enumerate(factory).inputs,
270 choice,
271 default_for(choice, Flow::Capture).as_deref(),
272 ) else {
273 return false;
274 };
275 select_input_index(factory, index)
276}
277
278#[cfg(windows)]
279fn pause_for_endpoint_retry() {
280 let pause = || std::thread::sleep(std::time::Duration::from_millis(150));
281 if tokio::runtime::Handle::try_current().is_ok() {
282 tokio::task::block_in_place(pause);
283 } else {
284 pause();
285 }
286}
287
288pub fn select_input_index(factory: &PeerConnectionFactory, index: u16) -> bool {
289 factory.stop_recording();
290 let selected = factory.set_recording_device(index);
291 let started = factory.init_recording() && factory.start_recording();
292 #[cfg(windows)]
293 let started = if selected && !started {
294 // Bluetooth headsets (HFP/A2DP profile switch) can momentarily reject Init/StartRecording.
295 pause_for_endpoint_retry();
296 factory.stop_recording();
297 let reselected = factory.set_recording_device(index);
298 reselected && factory.init_recording() && factory.start_recording()
299 } else {
300 started
301 };
302 #[cfg(windows)]
303 return device_switch_applied(selected, started);
304 #[cfg(not(windows))]
305 {
306 let _ = started;
307 selected
308 }
309}
310
311pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
312 let Some(index) = resolve_index(
313 &enumerate(factory).outputs,
314 choice,
315 default_for(choice, Flow::Render).as_deref(),
316 ) else {
317 return false;
318 };
319 select_output_index(factory, index)
320}
321
322pub fn select_output_index(factory: &PeerConnectionFactory, index: u16) -> bool {
323 factory.stop_playout();
324 let selected = factory.set_playout_device(index);
325 let started = factory.init_playout() && factory.start_playout();
326 #[cfg(windows)]
327 let started = if selected && !started {
328 // Retry once after Bluetooth A2DP/HFP endpoint renegotiation settles.
329 pause_for_endpoint_retry();
330 factory.stop_playout();
331 let reselected = factory.set_playout_device(index);
332 reselected && factory.init_playout() && factory.start_playout()
333 } else {
334 started
335 };
336 #[cfg(windows)]
337 return device_switch_applied(selected, started);
338 #[cfg(not(windows))]
339 {
340 let _ = started;
341 selected
342 }
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348
349 fn device(index: u16, name: &str, guid: &str) -> AudioDevice {
350 AudioDevice {
351 index,
352 guid: guid.into(),
353 name: name.into(),
354 }
355 }
356
357 #[test]
358 fn default_device_comes_first_and_aliases_are_dropped() {
359 let devices = [
360 device(0, "Headset Microphone", "{b}"),
361 device(1, "Default - Headset Microphone", "{a}"),
362 device(2, "Communication - Headset Microphone", "{c}"),
363 device(3, "Webcam Microphone", "{w}"),
364 ];
365 let entries = menu_entries(&devices);
366 let labels: Vec<&str> = entries.iter().map(|entry| entry.label.as_str()).collect();
367 assert_eq!(
368 labels,
369 ["Default device", "Headset Microphone", "Webcam Microphone"]
370 );
371 assert_eq!(entries[0].choice, DeviceChoice::SystemDefault);
372 assert_eq!(entries[1].choice, DeviceChoice::Device("{b}".into()));
373 }
374
375 #[test]
376 fn no_devices_still_offers_the_default_entry() {
377 let entries = menu_entries(&[]);
378 assert_eq!(entries.len(), 1);
379 assert_eq!(entries[0].label, DEFAULT_DEVICE_LABEL);
380 }
381
382 #[test]
383 fn linux_default_names_are_aliases() {
384 let devices = [
385 device(0, "default", "default"),
386 device(1, "sysdefault:CARD=PCH", "x"),
387 device(2, "USB Audio", "usb"),
388 ];
389 let labels: Vec<String> = menu_entries(&devices)
390 .into_iter()
391 .map(|entry| entry.label)
392 .collect();
393 assert_eq!(labels, ["Default device", "USB Audio"]);
394 }
395
396 #[test]
397 fn devices_without_a_guid_are_keyed_by_name() {
398 let devices = [
399 device(0, "default: Speakers", ""),
400 device(1, "Speakers", ""),
401 device(2, "Headset", ""),
402 ];
403 let entries = menu_entries(&devices);
404 assert_eq!(entries[1].choice, DeviceChoice::Device("Speakers".into()));
405 assert_eq!(
406 resolve_index(&devices, &DeviceChoice::Device("Headset".into()), None),
407 Some(2)
408 );
409 assert_eq!(
410 resolve_index(&devices, &DeviceChoice::Device("Gone".into()), None),
411 None
412 );
413 }
414
415 #[test]
416 fn the_system_default_resolves_to_the_alias_or_the_first_device() {
417 let with_alias = [device(0, "USB", "u"), device(1, "default: USB", "")];
418 assert_eq!(
419 resolve_index(&with_alias, &DeviceChoice::SystemDefault, None),
420 Some(1)
421 );
422 let without_alias = [device(0, "Speakers", "s"), device(1, "Headset", "h")];
423 assert_eq!(
424 resolve_index(&without_alias, &DeviceChoice::SystemDefault, None),
425 Some(0)
426 );
427 assert_eq!(resolve_index(&[], &DeviceChoice::SystemDefault, None), None);
428 }
429
430 #[test]
431 fn the_system_default_follows_the_platform_default_endpoint() {
432 let devices = [
433 device(0, "Speakers (Realtek)", "{0.0.0.00000000}.{aaaa}"),
434 device(1, "Headset Earphone", "{0.0.0.00000000}.{BBBB}"),
435 ];
436 let headset = Some("{0.0.0.00000000}.{bbbb}");
437 assert_eq!(
438 resolve_index(&devices, &DeviceChoice::SystemDefault, headset),
439 Some(1)
440 );
441 assert_eq!(
442 resolve_index(
443 &devices,
444 &DeviceChoice::SystemDefault,
445 Some("{0.0.0.00000000}.{gone}")
446 ),
447 Some(0)
448 );
449 assert_eq!(
450 resolve_index(
451 &devices,
452 &DeviceChoice::Device("{0.0.0.00000000}.{aaaa}".into()),
453 headset
454 ),
455 Some(0)
456 );
457 assert_eq!(
458 resolve_index(
459 &devices,
460 &DeviceChoice::Device("{0.0.0.00000000}.{BBBB}".into()),
461 None
462 ),
463 Some(1)
464 );
465 }
466
467 #[test]
468 fn a_device_switch_counts_only_when_audio_starts() {
469 assert!(!device_switch_applied(true, false));
470 assert!(device_switch_applied(true, true));
471 assert!(!device_switch_applied(false, true));
472 }
473
474 fn headset_lists() -> (Vec<AudioDevice>, Vec<AudioDevice>) {
475 let before = vec![device(0, "Speakers", "{s}")];
476 let after = vec![device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
477 (before, after)
478 }
479
480 #[test]
481 fn the_default_moving_to_a_new_headset_selects_it() {
482 let (before, after) = headset_lists();
483 let applied = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
484 assert_eq!(
485 reselect(
486 applied.as_ref(),
487 &after,
488 &DeviceChoice::SystemDefault,
489 Some("{h}")
490 ),
491 Reselect::Select(1)
492 );
493 }
494
495 #[test]
496 fn nothing_changed_keeps_the_device_running() {
497 let (_, after) = headset_lists();
498 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
499 assert_eq!(
500 reselect(
501 applied.as_ref(),
502 &after,
503 &DeviceChoice::SystemDefault,
504 Some("{h}")
505 ),
506 Reselect::Keep
507 );
508 let explicit = DeviceChoice::Device("{h}".into());
509 let applied = applied_device(&after, &explicit, Some("{s}"));
510 assert_eq!(
511 reselect(applied.as_ref(), &after, &explicit, Some("{s}")),
512 Reselect::Keep
513 );
514 }
515
516 #[test]
517 fn unplugging_the_selected_headset_falls_back_and_returns_when_it_comes_back() {
518 let (before, after) = headset_lists();
519 let explicit = DeviceChoice::Device("{h}".into());
520 let applied = applied_device(&after, &explicit, Some("{h}"));
521 assert_eq!(
522 reselect(applied.as_ref(), &before, &explicit, Some("{s}")),
523 Reselect::FallBack(0)
524 );
525 let fallen_back = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
526 assert_eq!(
527 reselect(fallen_back.as_ref(), &before, &explicit, Some("{s}")),
528 Reselect::Keep
529 );
530 assert_eq!(
531 reselect(fallen_back.as_ref(), &after, &explicit, Some("{s}")),
532 Reselect::Select(1)
533 );
534 }
535
536 #[test]
537 fn a_shifted_index_with_the_same_key_is_reselected() {
538 let explicit = DeviceChoice::Device("{h}".into());
539 let before = [device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
540 let after = [
541 device(0, "Dock", "{d}"),
542 device(1, "Speakers", "{s}"),
543 device(2, "Headset", "{h}"),
544 ];
545 let applied = applied_device(&before, &explicit, None);
546 assert_eq!(
547 reselect(applied.as_ref(), &after, &explicit, None),
548 Reselect::Select(2)
549 );
550 }
551
552 #[test]
553 fn a_removed_default_selects_the_new_default() {
554 let (before, after) = headset_lists();
555 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
556 assert_eq!(
557 reselect(
558 applied.as_ref(),
559 &before,
560 &DeviceChoice::SystemDefault,
561 Some("{s}")
562 ),
563 Reselect::Select(0)
564 );
565 }
566
567 #[test]
568 fn the_notice_names_both_devices() {
569 let (before, after) = headset_lists();
570 let explicit = DeviceChoice::Device("{h}".into());
571 assert_eq!(
572 disconnect_notice(&after, &explicit, before.first()),
573 "Headset disconnected. Using Speakers."
574 );
575 }
576
577 #[test]
578 fn unnamed_devices_are_hidden() {
579 let entries = menu_entries(&[device(0, " ", "g")]);
580 assert_eq!(entries.len(), 1);
581 }
582}