BlueGit

ict rusty-teams

Files

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

devices.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
devices.rs 15.4 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 communications device, which the ADM reports as the device guid.
90#[cfg(windows)]
91pub fn system_default_id(flow: Flow) -> Option<String> {
92 use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
93 let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok();
94 let id = default_endpoint_id(flow);
95 if initialized {
96 unsafe { CoUninitialize() };
97 }
98 id
99}
100
101#[cfg(windows)]
102fn default_endpoint_id(flow: Flow) -> Option<String> {
103 use windows::Win32::Media::Audio::{
104 IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eRender,
105 };
106 use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
107 let data_flow = match flow {
108 Flow::Capture => eCapture,
109 Flow::Render => eRender,
110 };
111 unsafe {
112 let enumerator: IMMDeviceEnumerator =
113 CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;
114 let device = enumerator
115 .GetDefaultAudioEndpoint(data_flow, eCommunications)
116 .ok()?;
117 let id = device.GetId().ok()?;
118 let text = id.to_string().ok();
119 CoTaskMemFree(Some(id.0 as *const _));
120 text
121 }
122}
123
124#[cfg(not(windows))]
125pub fn system_default_id(_flow: Flow) -> Option<String> {
126 None
127}
128
129pub fn resolve_index(
130 devices: &[AudioDevice],
131 choice: &DeviceChoice,
132 system_default: Option<&str>,
133) -> Option<u16> {
134 match choice {
135 DeviceChoice::SystemDefault => system_default
136 .and_then(|id| {
137 devices
138 .iter()
139 .find(|device| device.guid.eq_ignore_ascii_case(id))
140 })
141 .or_else(|| devices.iter().find(|device| device.is_system_alias()))
142 .or(devices.first())
143 .map(|device| device.index),
144 DeviceChoice::Device(key) => devices
145 .iter()
146 .find(|device| device.key() == *key)
147 .map(|device| device.index),
148 }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct AppliedDevice {
153 pub index: u16,
154 pub key: String,
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum Reselect {
159 Keep,
160 Select(u16),
161 FallBack(u16),
162}
163
164pub fn applied_device(
165 devices: &[AudioDevice],
166 choice: &DeviceChoice,
167 system_default: Option<&str>,
168) -> Option<AppliedDevice> {
169 let index = resolve_index(devices, choice, system_default)?;
170 device_at(devices, index)
171}
172
173fn device_at(devices: &[AudioDevice], index: u16) -> Option<AppliedDevice> {
174 devices
175 .iter()
176 .find(|device| device.index == index)
177 .map(|device| AppliedDevice {
178 index,
179 key: device.key(),
180 })
181}
182
183pub fn reselect(
184 applied: Option<&AppliedDevice>,
185 devices: &[AudioDevice],
186 choice: &DeviceChoice,
187 system_default: Option<&str>,
188) -> Reselect {
189 let unchanged = |index: u16| device_at(devices, index).as_ref() == applied;
190 match resolve_index(devices, choice, system_default) {
191 Some(index) if unchanged(index) => Reselect::Keep,
192 Some(index) => Reselect::Select(index),
193 None => match resolve_index(devices, &DeviceChoice::SystemDefault, system_default) {
194 Some(index) if !unchanged(index) && matches!(choice, DeviceChoice::Device(_)) => {
195 Reselect::FallBack(index)
196 }
197 _ => Reselect::Keep,
198 },
199 }
200}
201
202pub fn disconnect_notice(
203 previous: &[AudioDevice],
204 choice: &DeviceChoice,
205 fallback: Option<&AudioDevice>,
206) -> String {
207 let lost = previous
208 .iter()
209 .find(|device| matches!(choice, DeviceChoice::Device(key) if device.key() == *key))
210 .map_or("Device", |device| device.name.as_str());
211 match fallback {
212 Some(device) => format!("{lost} disconnected. Using {}.", device.name),
213 None => format!("{lost} disconnected."),
214 }
215}
216
217fn enumerate(factory: &PeerConnectionFactory) -> DeviceLists {
218 let inputs = (0..factory.recording_devices().max(0) as u16)
219 .map(|index| AudioDevice {
220 index,
221 guid: factory.recording_device_guid(index),
222 name: factory.recording_device_name(index),
223 })
224 .collect();
225 let outputs = (0..factory.playout_devices().max(0) as u16)
226 .map(|index| AudioDevice {
227 index,
228 guid: factory.playout_device_guid(index),
229 name: factory.playout_device_name(index),
230 })
231 .collect();
232 DeviceLists { inputs, outputs }
233}
234
235pub fn list_devices(factory: &PeerConnectionFactory) -> DeviceLists {
236 if !factory.acquire_platform_adm() {
237 return DeviceLists::default();
238 }
239 let lists = enumerate(factory);
240 factory.release_platform_adm();
241 lists
242}
243
244fn default_for(choice: &DeviceChoice, flow: Flow) -> Option<String> {
245 (*choice == DeviceChoice::SystemDefault)
246 .then(|| system_default_id(flow))
247 .flatten()
248}
249
250pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
251 let Some(index) = resolve_index(
252 &enumerate(factory).inputs,
253 choice,
254 default_for(choice, Flow::Capture).as_deref(),
255 ) else {
256 return false;
257 };
258 select_input_index(factory, index)
259}
260
261pub fn select_input_index(factory: &PeerConnectionFactory, index: u16) -> bool {
262 factory.stop_recording();
263 let selected = factory.set_recording_device(index);
264 factory.init_recording();
265 factory.start_recording();
266 selected
267}
268
269pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
270 let Some(index) = resolve_index(
271 &enumerate(factory).outputs,
272 choice,
273 default_for(choice, Flow::Render).as_deref(),
274 ) else {
275 return false;
276 };
277 select_output_index(factory, index)
278}
279
280pub fn select_output_index(factory: &PeerConnectionFactory, index: u16) -> bool {
281 factory.stop_playout();
282 let selected = factory.set_playout_device(index);
283 factory.init_playout();
284 factory.start_playout();
285 selected
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292 fn device(index: u16, name: &str, guid: &str) -> AudioDevice {
293 AudioDevice {
294 index,
295 guid: guid.into(),
296 name: name.into(),
297 }
298 }
299
300 #[test]
301 fn default_device_comes_first_and_aliases_are_dropped() {
302 let devices = [
303 device(0, "Headset Microphone", "{b}"),
304 device(1, "Default - Headset Microphone", "{a}"),
305 device(2, "Communication - Headset Microphone", "{c}"),
306 device(3, "Webcam Microphone", "{w}"),
307 ];
308 let entries = menu_entries(&devices);
309 let labels: Vec<&str> = entries.iter().map(|entry| entry.label.as_str()).collect();
310 assert_eq!(
311 labels,
312 ["Default device", "Headset Microphone", "Webcam Microphone"]
313 );
314 assert_eq!(entries[0].choice, DeviceChoice::SystemDefault);
315 assert_eq!(entries[1].choice, DeviceChoice::Device("{b}".into()));
316 }
317
318 #[test]
319 fn no_devices_still_offers_the_default_entry() {
320 let entries = menu_entries(&[]);
321 assert_eq!(entries.len(), 1);
322 assert_eq!(entries[0].label, DEFAULT_DEVICE_LABEL);
323 }
324
325 #[test]
326 fn linux_default_names_are_aliases() {
327 let devices = [
328 device(0, "default", "default"),
329 device(1, "sysdefault:CARD=PCH", "x"),
330 device(2, "USB Audio", "usb"),
331 ];
332 let labels: Vec<String> = menu_entries(&devices)
333 .into_iter()
334 .map(|entry| entry.label)
335 .collect();
336 assert_eq!(labels, ["Default device", "USB Audio"]);
337 }
338
339 #[test]
340 fn devices_without_a_guid_are_keyed_by_name() {
341 let devices = [
342 device(0, "default: Speakers", ""),
343 device(1, "Speakers", ""),
344 device(2, "Headset", ""),
345 ];
346 let entries = menu_entries(&devices);
347 assert_eq!(entries[1].choice, DeviceChoice::Device("Speakers".into()));
348 assert_eq!(
349 resolve_index(&devices, &DeviceChoice::Device("Headset".into()), None),
350 Some(2)
351 );
352 assert_eq!(
353 resolve_index(&devices, &DeviceChoice::Device("Gone".into()), None),
354 None
355 );
356 }
357
358 #[test]
359 fn the_system_default_resolves_to_the_alias_or_the_first_device() {
360 let with_alias = [device(0, "USB", "u"), device(1, "default: USB", "")];
361 assert_eq!(
362 resolve_index(&with_alias, &DeviceChoice::SystemDefault, None),
363 Some(1)
364 );
365 let without_alias = [device(0, "Speakers", "s"), device(1, "Headset", "h")];
366 assert_eq!(
367 resolve_index(&without_alias, &DeviceChoice::SystemDefault, None),
368 Some(0)
369 );
370 assert_eq!(resolve_index(&[], &DeviceChoice::SystemDefault, None), None);
371 }
372
373 #[test]
374 fn the_system_default_follows_the_platform_default_endpoint() {
375 let devices = [
376 device(0, "Speakers (Realtek)", "{0.0.0.00000000}.{aaaa}"),
377 device(1, "Headset Earphone", "{0.0.0.00000000}.{BBBB}"),
378 ];
379 let headset = Some("{0.0.0.00000000}.{bbbb}");
380 assert_eq!(
381 resolve_index(&devices, &DeviceChoice::SystemDefault, headset),
382 Some(1)
383 );
384 assert_eq!(
385 resolve_index(
386 &devices,
387 &DeviceChoice::SystemDefault,
388 Some("{0.0.0.00000000}.{gone}")
389 ),
390 Some(0)
391 );
392 assert_eq!(
393 resolve_index(
394 &devices,
395 &DeviceChoice::Device("{0.0.0.00000000}.{aaaa}".into()),
396 headset
397 ),
398 Some(0)
399 );
400 }
401
402 fn headset_lists() -> (Vec<AudioDevice>, Vec<AudioDevice>) {
403 let before = vec![device(0, "Speakers", "{s}")];
404 let after = vec![device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
405 (before, after)
406 }
407
408 #[test]
409 fn the_default_moving_to_a_new_headset_selects_it() {
410 let (before, after) = headset_lists();
411 let applied = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
412 assert_eq!(
413 reselect(
414 applied.as_ref(),
415 &after,
416 &DeviceChoice::SystemDefault,
417 Some("{h}")
418 ),
419 Reselect::Select(1)
420 );
421 }
422
423 #[test]
424 fn nothing_changed_keeps_the_device_running() {
425 let (_, after) = headset_lists();
426 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
427 assert_eq!(
428 reselect(
429 applied.as_ref(),
430 &after,
431 &DeviceChoice::SystemDefault,
432 Some("{h}")
433 ),
434 Reselect::Keep
435 );
436 let explicit = DeviceChoice::Device("{h}".into());
437 let applied = applied_device(&after, &explicit, Some("{s}"));
438 assert_eq!(
439 reselect(applied.as_ref(), &after, &explicit, Some("{s}")),
440 Reselect::Keep
441 );
442 }
443
444 #[test]
445 fn unplugging_the_selected_headset_falls_back_and_returns_when_it_comes_back() {
446 let (before, after) = headset_lists();
447 let explicit = DeviceChoice::Device("{h}".into());
448 let applied = applied_device(&after, &explicit, Some("{h}"));
449 assert_eq!(
450 reselect(applied.as_ref(), &before, &explicit, Some("{s}")),
451 Reselect::FallBack(0)
452 );
453 let fallen_back = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
454 assert_eq!(
455 reselect(fallen_back.as_ref(), &before, &explicit, Some("{s}")),
456 Reselect::Keep
457 );
458 assert_eq!(
459 reselect(fallen_back.as_ref(), &after, &explicit, Some("{s}")),
460 Reselect::Select(1)
461 );
462 }
463
464 #[test]
465 fn a_shifted_index_with_the_same_key_is_reselected() {
466 let explicit = DeviceChoice::Device("{h}".into());
467 let before = [device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
468 let after = [
469 device(0, "Dock", "{d}"),
470 device(1, "Speakers", "{s}"),
471 device(2, "Headset", "{h}"),
472 ];
473 let applied = applied_device(&before, &explicit, None);
474 assert_eq!(
475 reselect(applied.as_ref(), &after, &explicit, None),
476 Reselect::Select(2)
477 );
478 }
479
480 #[test]
481 fn a_removed_default_selects_the_new_default() {
482 let (before, after) = headset_lists();
483 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
484 assert_eq!(
485 reselect(
486 applied.as_ref(),
487 &before,
488 &DeviceChoice::SystemDefault,
489 Some("{s}")
490 ),
491 Reselect::Select(0)
492 );
493 }
494
495 #[test]
496 fn the_notice_names_both_devices() {
497 let (before, after) = headset_lists();
498 let explicit = DeviceChoice::Device("{h}".into());
499 assert_eq!(
500 disconnect_notice(&after, &explicit, before.first()),
501 "Headset disconnected. Using Speakers."
502 );
503 }
504
505 #[test]
506 fn unnamed_devices_are_hidden() {
507 let entries = menu_entries(&[device(0, " ", "g")]);
508 assert_eq!(entries.len(), 1);
509 }
510}