BlueGit

ict rusty-teams

fix(calls): devices plugged in during a call show up and the default follows them

- Device watcher (IMMNotificationClient on Windows) signals changes, debounced 500 ms
- Call loop re-lists devices, re-selects only when the resolved device changed
- Selected device gone: fall back to default, notice, re-select when it returns
- "System default" now means the Windows default communications device (eCommunications), not eConsole
- Call timeline records "device change" and "audio devices" with the resolved names

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-14 · 6 weeks ago

Hash
774bf921c9bdcc6fe64c8fc15e486f01db4ccb80
Parent
84b79477
4 files changed +324 −7
crates/calling/src/call.rs +74 −4
@@ -30,7 +30,8 @@ use crate::captions::{
30 30 use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
31 31 use crate::diagnostics::{CallDiagnostics, StatsSample};
32 32 use crate::data_channel::Depacketizer;
33 use crate::devices::{self, DeviceChoice};
33 use crate::device_watch::{self, Debounce};
34 use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
34 35 use crate::end::EndKind;
35 36 use crate::engine::{CallEngine, EngineConfig, Inner};
36 37 use crate::error::{Error, Result};
@@ -616,12 +617,17 @@ async fn drive(
616 617 let mut output = options.output.clone();
617 618 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
618 619 control.send(CallUpdate::ListenOnly(audio.listen_only));
619 let device_lists = devices::list_devices(&factory);
620 let mut device_lists = devices::list_devices(&factory);
621 let mut applied_input = devices::applied_device(&device_lists.inputs, &input, devices::system_default_id(Flow::Capture).as_deref());
622 let mut applied_output = devices::applied_device(&device_lists.outputs, &output, devices::system_default_id(Flow::Render).as_deref());
623 let (_device_watcher, mut device_changes) = device_watch::watch();
624 let mut device_debounce = Debounce::default();
620 625 timeline.record(
621 626 "audio setup",
622 627 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
623 628 );
624 control.send(CallUpdate::Devices(device_lists));
629 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
630 control.send(CallUpdate::Devices(device_lists.clone()));
625 631 control.send(CallUpdate::Selected {
626 632 input: input.clone(),
627 633 output: output.clone(),
@@ -1341,6 +1347,8 @@ async fn drive(
1341 1347 Some(CallCommand::SelectInput(choice)) => {
1342 1348 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1343 1349 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
1350 applied_input = devices::applied_device(&device_lists.inputs, &choice, devices::system_default_id(Flow::Capture).as_deref());
1351 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1344 1352 }
1345 1353 input = choice;
1346 1354 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
@@ -1360,12 +1368,15 @@ async fn drive(
1360 1368 Some(CallCommand::SelectOutput(choice)) => {
1361 1369 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1362 1370 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
1371 applied_output = devices::applied_device(&device_lists.outputs, &choice, devices::system_default_id(Flow::Render).as_deref());
1372 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1363 1373 }
1364 1374 output = choice;
1365 1375 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
1366 1376 }
1367 1377 Some(CallCommand::RefreshDevices) => {
1368 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
1378 device_lists = devices::list_devices(&factory);
1379 control.send(CallUpdate::Devices(device_lists.clone()));
1369 1380 }
1370 1381 Some(CallCommand::SetCamera(on)) => {
1371 1382 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
@@ -1839,6 +1850,25 @@ async fn drive(
1839 1850 );
1840 1851 }
1841 1852 }
1853 Some(()) = device_changes.recv() => {
1854 device_debounce.signal(Instant::now());
1855 }
1856 _ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {
1857 if device_debounce.take_due(Instant::now()) {
1858 let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));
1859 control.send(CallUpdate::Devices(device_lists.clone()));
1860 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1861 let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, |index| devices::select_input_index(&factory, index), timeline, control);
1862 let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, |index| devices::select_output_index(&factory, index), timeline, control);
1863 if input_changed || output_changed {
1864 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1865 }
1866 if input_changed && software_audio.is_some() {
1867 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
1868 }
1869 }
1870 }
1871 }
1842 1872 _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => {
1843 1873 advance(state, CallSignal::ReconnectTimedOut, control);
1844 1874 break;
@@ -2346,6 +2376,46 @@ fn send_receive_change(control: &CallControl, change: ReceiveChange) {
2346 2376 }
2347 2377 }
2348 2378
2379 fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input: Option<&AppliedDevice>, output: Option<&AppliedDevice>) {
2380 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
2381 applied
2382 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
2383 .map_or("none", |device| device.name.as_str())
2384 .to_owned()
2385 };
2386 timeline.record(
2387 "audio devices",
2388 format!("input={} output={}", name(&lists.inputs, input), name(&lists.outputs, output)),
2389 );
2390 }
2391
2392 fn follow_device_change(
2393 flow: Flow,
2394 (previous, current): (&[AudioDevice], &[AudioDevice]),
2395 choice: &DeviceChoice,
2396 applied: &mut Option<AppliedDevice>,
2397 select: impl Fn(u16) -> bool,
2398 timeline: &Timeline,
2399 control: &CallControl,
2400 ) -> bool {
2401 let system_default = devices::system_default_id(flow);
2402 let (index, fell_back) = match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
2403 Reselect::Keep => return false,
2404 Reselect::Select(index) => (index, false),
2405 Reselect::FallBack(index) => (index, true),
2406 };
2407 let selected = select(index);
2408 timeline.record("device change", format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"));
2409 if selected {
2410 *applied = current.iter().find(|device| device.index == index).map(|device| AppliedDevice { index, key: device.key() });
2411 }
2412 if fell_back {
2413 let fallback = current.iter().find(|device| device.index == index);
2414 control.send(CallUpdate::Notice(devices::disconnect_notice(previous, choice, fallback)));
2415 }
2416 selected
2417 }
2418
2349 2419 fn far_future() -> Instant {
2350 2420 Instant::now() + FAR_FUTURE
2351 2421 }
@@ -30,7 +30,8 @@ use crate::captions::{
30use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
30use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
31use crate::diagnostics::{CallDiagnostics, StatsSample};
31use crate::diagnostics::{CallDiagnostics, StatsSample};
32use crate::data_channel::Depacketizer;
32use crate::data_channel::Depacketizer;
33use crate::devices::{self, DeviceChoice};
33use crate::device_watch::{self, Debounce};
34use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
34use crate::end::EndKind;
35use crate::end::EndKind;
35use crate::engine::{CallEngine, EngineConfig, Inner};
36use crate::engine::{CallEngine, EngineConfig, Inner};
36use crate::error::{Error, Result};
37use crate::error::{Error, Result};
@@ -616,12 +617,17 @@ async fn drive(
616 let mut output = options.output.clone();
617 let mut output = options.output.clone();
617 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
618 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
618 control.send(CallUpdate::ListenOnly(audio.listen_only));
619 control.send(CallUpdate::ListenOnly(audio.listen_only));
619 let device_lists = devices::list_devices(&factory);
620 let mut device_lists = devices::list_devices(&factory);
621 let mut applied_input = devices::applied_device(&device_lists.inputs, &input, devices::system_default_id(Flow::Capture).as_deref());
622 let mut applied_output = devices::applied_device(&device_lists.outputs, &output, devices::system_default_id(Flow::Render).as_deref());
623 let (_device_watcher, mut device_changes) = device_watch::watch();
624 let mut device_debounce = Debounce::default();
620 timeline.record(
625 timeline.record(
621 "audio setup",
626 "audio setup",
622 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
627 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
623 );
628 );
624 control.send(CallUpdate::Devices(device_lists));
629 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
630 control.send(CallUpdate::Devices(device_lists.clone()));
625 control.send(CallUpdate::Selected {
631 control.send(CallUpdate::Selected {
626 input: input.clone(),
632 input: input.clone(),
627 output: output.clone(),
633 output: output.clone(),
@@ -1341,6 +1347,8 @@ async fn drive(
1341 Some(CallCommand::SelectInput(choice)) => {
1347 Some(CallCommand::SelectInput(choice)) => {
1342 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1348 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1343 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
1349 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
1350 applied_input = devices::applied_device(&device_lists.inputs, &choice, devices::system_default_id(Flow::Capture).as_deref());
1351 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1344 }
1352 }
1345 input = choice;
1353 input = choice;
1346 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
1354 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
@@ -1360,12 +1368,15 @@ async fn drive(
1360 Some(CallCommand::SelectOutput(choice)) => {
1368 Some(CallCommand::SelectOutput(choice)) => {
1361 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1369 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1362 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
1370 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
1371 applied_output = devices::applied_device(&device_lists.outputs, &choice, devices::system_default_id(Flow::Render).as_deref());
1372 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1363 }
1373 }
1364 output = choice;
1374 output = choice;
1365 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
1375 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
1366 }
1376 }
1367 Some(CallCommand::RefreshDevices) => {
1377 Some(CallCommand::RefreshDevices) => {
1368 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
1378 device_lists = devices::list_devices(&factory);
1379 control.send(CallUpdate::Devices(device_lists.clone()));
1369 }
1380 }
1370 Some(CallCommand::SetCamera(on)) => {
1381 Some(CallCommand::SetCamera(on)) => {
1371 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
1382 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
@@ -1839,6 +1850,25 @@ async fn drive(
1839 );
1850 );
1840 }
1851 }
1841 }
1852 }
1853 Some(()) = device_changes.recv() => {
1854 device_debounce.signal(Instant::now());
1855 }
1856 _ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {
1857 if device_debounce.take_due(Instant::now()) {
1858 let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));
1859 control.send(CallUpdate::Devices(device_lists.clone()));
1860 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1861 let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, |index| devices::select_input_index(&factory, index), timeline, control);
1862 let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, |index| devices::select_output_index(&factory, index), timeline, control);
1863 if input_changed || output_changed {
1864 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1865 }
1866 if input_changed && software_audio.is_some() {
1867 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
1868 }
1869 }
1870 }
1871 }
1842 _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => {
1872 _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => {
1843 advance(state, CallSignal::ReconnectTimedOut, control);
1873 advance(state, CallSignal::ReconnectTimedOut, control);
1844 break;
1874 break;
@@ -2346,6 +2376,46 @@ fn send_receive_change(control: &CallControl, change: ReceiveChange) {
2346 }
2376 }
2347}
2377}
2348
2378
2379fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input: Option<&AppliedDevice>, output: Option<&AppliedDevice>) {
2380 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
2381 applied
2382 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
2383 .map_or("none", |device| device.name.as_str())
2384 .to_owned()
2385 };
2386 timeline.record(
2387 "audio devices",
2388 format!("input={} output={}", name(&lists.inputs, input), name(&lists.outputs, output)),
2389 );
2390}
2391
2392fn follow_device_change(
2393 flow: Flow,
2394 (previous, current): (&[AudioDevice], &[AudioDevice]),
2395 choice: &DeviceChoice,
2396 applied: &mut Option<AppliedDevice>,
2397 select: impl Fn(u16) -> bool,
2398 timeline: &Timeline,
2399 control: &CallControl,
2400) -> bool {
2401 let system_default = devices::system_default_id(flow);
2402 let (index, fell_back) = match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
2403 Reselect::Keep => return false,
2404 Reselect::Select(index) => (index, false),
2405 Reselect::FallBack(index) => (index, true),
2406 };
2407 let selected = select(index);
2408 timeline.record("device change", format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"));
2409 if selected {
2410 *applied = current.iter().find(|device| device.index == index).map(|device| AppliedDevice { index, key: device.key() });
2411 }
2412 if fell_back {
2413 let fallback = current.iter().find(|device| device.index == index);
2414 control.send(CallUpdate::Notice(devices::disconnect_notice(previous, choice, fallback)));
2415 }
2416 selected
2417}
2418
2349fn far_future() -> Instant {
2419fn far_future() -> Instant {
2350 Instant::now() + FAR_FUTURE
2420 Instant::now() + FAR_FUTURE
2351}
2421}
crates/calling/src/device_watch.rs added +133 −0
@@ -0,0 +1,133 @@
1 use std::time::Duration;
2
3 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
4 use tokio::time::Instant;
5
6 pub const DEVICE_CHANGE_QUIET: Duration = Duration::from_millis(500);
7
8 #[derive(Debug, Default)]
9 pub struct Debounce {
10 deadline: Option<Instant>,
11 }
12
13 impl Debounce {
14 pub fn signal(&mut self, now: Instant) {
15 self.deadline = Some(now + DEVICE_CHANGE_QUIET);
16 }
17
18 pub fn deadline(&self) -> Option<Instant> {
19 self.deadline
20 }
21
22 pub fn take_due(&mut self, now: Instant) -> bool {
23 let due = self.deadline.is_some_and(|deadline| now >= deadline);
24 if due {
25 self.deadline = None;
26 }
27 due
28 }
29 }
30
31 pub struct DeviceWatcher {
32 #[cfg(windows)]
33 _stop: std::sync::mpsc::Sender<()>,
34 }
35
36 pub fn watch() -> (DeviceWatcher, UnboundedReceiver<()>) {
37 let (sender, receiver) = unbounded_channel();
38 (platform::start(sender), receiver)
39 }
40
41 #[cfg(windows)]
42 mod platform {
43 use tokio::sync::mpsc::UnboundedSender;
44 use windows::Win32::Media::Audio::{
45 DEVICE_STATE, EDataFlow, ERole, IMMDeviceEnumerator, IMMNotificationClient, IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications,
46 };
47 use windows::Win32::Foundation::PROPERTYKEY;
48 use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize};
49 use windows::core::PCWSTR;
50 use windows_core::implement;
51
52 use super::DeviceWatcher;
53
54 #[implement(IMMNotificationClient)]
55 struct Client {
56 sender: UnboundedSender<()>,
57 }
58
59 impl IMMNotificationClient_Impl for Client_Impl {
60 fn OnDeviceStateChanged(&self, _device_id: &PCWSTR, _state: DEVICE_STATE) -> windows::core::Result<()> {
61 let _ = self.sender.send(());
62 Ok(())
63 }
64
65 fn OnDeviceAdded(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {
66 let _ = self.sender.send(());
67 Ok(())
68 }
69
70 fn OnDeviceRemoved(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {
71 let _ = self.sender.send(());
72 Ok(())
73 }
74
75 fn OnDefaultDeviceChanged(&self, _flow: EDataFlow, role: ERole, _device_id: &PCWSTR) -> windows::core::Result<()> {
76 if role == eCommunications {
77 let _ = self.sender.send(());
78 }
79 Ok(())
80 }
81
82 fn OnPropertyValueChanged(&self, _device_id: &PCWSTR, _key: &PROPERTYKEY) -> windows::core::Result<()> {
83 Ok(())
84 }
85 }
86
87 pub fn start(sender: UnboundedSender<()>) -> DeviceWatcher {
88 let (stop, stopped) = std::sync::mpsc::channel::<()>();
89 std::thread::spawn(move || unsafe {
90 let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();
91 if let Ok(enumerator) = CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL) {
92 let client: IMMNotificationClient = Client { sender }.into();
93 if enumerator.RegisterEndpointNotificationCallback(&client).is_ok() {
94 let _ = stopped.recv();
95 let _ = enumerator.UnregisterEndpointNotificationCallback(&client);
96 }
97 }
98 if initialized {
99 CoUninitialize();
100 }
101 });
102 DeviceWatcher { _stop: stop }
103 }
104 }
105
106 #[cfg(not(windows))]
107 mod platform {
108 use tokio::sync::mpsc::UnboundedSender;
109
110 use super::DeviceWatcher;
111
112 pub fn start(_sender: UnboundedSender<()>) -> DeviceWatcher {
113 DeviceWatcher {}
114 }
115 }
116
117 #[cfg(test)]
118 mod tests {
119 use super::*;
120
121 #[test]
122 fn a_burst_of_events_fires_once_after_the_quiet_period() {
123 let start = Instant::now();
124 let mut debounce = Debounce::default();
125 assert!(!debounce.take_due(start));
126 debounce.signal(start);
127 debounce.signal(start + Duration::from_millis(300));
128 assert!(!debounce.take_due(start + Duration::from_millis(600)));
129 assert!(debounce.take_due(start + Duration::from_millis(800)));
130 assert!(!debounce.take_due(start + Duration::from_millis(900)));
131 assert_eq!(debounce.deadline(), None);
132 }
133 }
@@ -0,0 +1,133 @@
1use std::time::Duration;
2
3use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
4use tokio::time::Instant;
5
6pub const DEVICE_CHANGE_QUIET: Duration = Duration::from_millis(500);
7
8#[derive(Debug, Default)]
9pub struct Debounce {
10 deadline: Option<Instant>,
11}
12
13impl Debounce {
14 pub fn signal(&mut self, now: Instant) {
15 self.deadline = Some(now + DEVICE_CHANGE_QUIET);
16 }
17
18 pub fn deadline(&self) -> Option<Instant> {
19 self.deadline
20 }
21
22 pub fn take_due(&mut self, now: Instant) -> bool {
23 let due = self.deadline.is_some_and(|deadline| now >= deadline);
24 if due {
25 self.deadline = None;
26 }
27 due
28 }
29}
30
31pub struct DeviceWatcher {
32 #[cfg(windows)]
33 _stop: std::sync::mpsc::Sender<()>,
34}
35
36pub fn watch() -> (DeviceWatcher, UnboundedReceiver<()>) {
37 let (sender, receiver) = unbounded_channel();
38 (platform::start(sender), receiver)
39}
40
41#[cfg(windows)]
42mod platform {
43 use tokio::sync::mpsc::UnboundedSender;
44 use windows::Win32::Media::Audio::{
45 DEVICE_STATE, EDataFlow, ERole, IMMDeviceEnumerator, IMMNotificationClient, IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications,
46 };
47 use windows::Win32::Foundation::PROPERTYKEY;
48 use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize};
49 use windows::core::PCWSTR;
50 use windows_core::implement;
51
52 use super::DeviceWatcher;
53
54 #[implement(IMMNotificationClient)]
55 struct Client {
56 sender: UnboundedSender<()>,
57 }
58
59 impl IMMNotificationClient_Impl for Client_Impl {
60 fn OnDeviceStateChanged(&self, _device_id: &PCWSTR, _state: DEVICE_STATE) -> windows::core::Result<()> {
61 let _ = self.sender.send(());
62 Ok(())
63 }
64
65 fn OnDeviceAdded(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {
66 let _ = self.sender.send(());
67 Ok(())
68 }
69
70 fn OnDeviceRemoved(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {
71 let _ = self.sender.send(());
72 Ok(())
73 }
74
75 fn OnDefaultDeviceChanged(&self, _flow: EDataFlow, role: ERole, _device_id: &PCWSTR) -> windows::core::Result<()> {
76 if role == eCommunications {
77 let _ = self.sender.send(());
78 }
79 Ok(())
80 }
81
82 fn OnPropertyValueChanged(&self, _device_id: &PCWSTR, _key: &PROPERTYKEY) -> windows::core::Result<()> {
83 Ok(())
84 }
85 }
86
87 pub fn start(sender: UnboundedSender<()>) -> DeviceWatcher {
88 let (stop, stopped) = std::sync::mpsc::channel::<()>();
89 std::thread::spawn(move || unsafe {
90 let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();
91 if let Ok(enumerator) = CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL) {
92 let client: IMMNotificationClient = Client { sender }.into();
93 if enumerator.RegisterEndpointNotificationCallback(&client).is_ok() {
94 let _ = stopped.recv();
95 let _ = enumerator.UnregisterEndpointNotificationCallback(&client);
96 }
97 }
98 if initialized {
99 CoUninitialize();
100 }
101 });
102 DeviceWatcher { _stop: stop }
103 }
104}
105
106#[cfg(not(windows))]
107mod platform {
108 use tokio::sync::mpsc::UnboundedSender;
109
110 use super::DeviceWatcher;
111
112 pub fn start(_sender: UnboundedSender<()>) -> DeviceWatcher {
113 DeviceWatcher {}
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120
121 #[test]
122 fn a_burst_of_events_fires_once_after_the_quiet_period() {
123 let start = Instant::now();
124 let mut debounce = Debounce::default();
125 assert!(!debounce.take_due(start));
126 debounce.signal(start);
127 debounce.signal(start + Duration::from_millis(300));
128 assert!(!debounce.take_due(start + Duration::from_millis(600)));
129 assert!(debounce.take_due(start + Duration::from_millis(800)));
130 assert!(!debounce.take_due(start + Duration::from_millis(900)));
131 assert_eq!(debounce.deadline(), None);
132 }
133}
crates/calling/src/devices.rs +116 −3
@@ -86,7 +86,7 @@ pub enum Flow {
86 86 Render,
87 87 }
88 88
89 /// Endpoint id of the Windows default device (console role), which the ADM reports as the device guid.
89 /// Endpoint id of the Windows default communications device, which the ADM reports as the device guid.
90 90 #[cfg(windows)]
91 91 pub fn system_default_id(flow: Flow) -> Option<String> {
92 92 use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
@@ -100,7 +100,7 @@ pub fn system_default_id(flow: Flow) -> Option<String> {
100 100
101 101 #[cfg(windows)]
102 102 fn default_endpoint_id(flow: Flow) -> Option<String> {
103 use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eConsole, eRender};
103 use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eRender};
104 104 use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
105 105 let data_flow = match flow {
106 106 Flow::Capture => eCapture,
@@ -108,7 +108,7 @@ fn default_endpoint_id(flow: Flow) -> Option<String> {
108 108 };
109 109 unsafe {
110 110 let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;
111 let device = enumerator.GetDefaultAudioEndpoint(data_flow, eConsole).ok()?;
111 let device = enumerator.GetDefaultAudioEndpoint(data_flow, eCommunications).ok()?;
112 112 let id = device.GetId().ok()?;
113 113 let text = id.to_string().ok();
114 114 CoTaskMemFree(Some(id.0 as *const _));
@@ -135,6 +135,54 @@ pub fn resolve_index(devices: &[AudioDevice], choice: &DeviceChoice, system_defa
135 135 }
136 136 }
137 137
138 #[derive(Debug, Clone, PartialEq, Eq)]
139 pub struct AppliedDevice {
140 pub index: u16,
141 pub key: String,
142 }
143
144 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
145 pub enum Reselect {
146 Keep,
147 Select(u16),
148 FallBack(u16),
149 }
150
151 pub fn applied_device(devices: &[AudioDevice], choice: &DeviceChoice, system_default: Option<&str>) -> Option<AppliedDevice> {
152 let index = resolve_index(devices, choice, system_default)?;
153 device_at(devices, index)
154 }
155
156 fn device_at(devices: &[AudioDevice], index: u16) -> Option<AppliedDevice> {
157 devices
158 .iter()
159 .find(|device| device.index == index)
160 .map(|device| AppliedDevice { index, key: device.key() })
161 }
162
163 pub fn reselect(applied: Option<&AppliedDevice>, devices: &[AudioDevice], choice: &DeviceChoice, system_default: Option<&str>) -> Reselect {
164 let unchanged = |index: u16| device_at(devices, index).as_ref() == applied;
165 match resolve_index(devices, choice, system_default) {
166 Some(index) if unchanged(index) => Reselect::Keep,
167 Some(index) => Reselect::Select(index),
168 None => match resolve_index(devices, &DeviceChoice::SystemDefault, system_default) {
169 Some(index) if !unchanged(index) && matches!(choice, DeviceChoice::Device(_)) => Reselect::FallBack(index),
170 _ => Reselect::Keep,
171 },
172 }
173 }
174
175 pub fn disconnect_notice(previous: &[AudioDevice], choice: &DeviceChoice, fallback: Option<&AudioDevice>) -> String {
176 let lost = previous
177 .iter()
178 .find(|device| matches!(choice, DeviceChoice::Device(key) if device.key() == *key))
179 .map_or("Device", |device| device.name.as_str());
180 match fallback {
181 Some(device) => format!("{lost} disconnected. Using {}.", device.name),
182 None => format!("{lost} disconnected."),
183 }
184 }
185
138 186 fn enumerate(factory: &PeerConnectionFactory) -> DeviceLists {
139 187 let inputs = (0..factory.recording_devices().max(0) as u16)
140 188 .map(|index| AudioDevice {
@@ -170,6 +218,10 @@ pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> b
170 218 let Some(index) = resolve_index(&enumerate(factory).inputs, choice, default_for(choice, Flow::Capture).as_deref()) else {
171 219 return false;
172 220 };
221 select_input_index(factory, index)
222 }
223
224 pub fn select_input_index(factory: &PeerConnectionFactory, index: u16) -> bool {
173 225 factory.stop_recording();
174 226 let selected = factory.set_recording_device(index);
175 227 factory.init_recording();
@@ -181,6 +233,10 @@ pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) ->
181 233 let Some(index) = resolve_index(&enumerate(factory).outputs, choice, default_for(choice, Flow::Render).as_deref()) else {
182 234 return false;
183 235 };
236 select_output_index(factory, index)
237 }
238
239 pub fn select_output_index(factory: &PeerConnectionFactory, index: u16) -> bool {
184 240 factory.stop_playout();
185 241 let selected = factory.set_playout_device(index);
186 242 factory.init_playout();
@@ -259,6 +315,63 @@ mod tests {
259 315 assert_eq!(resolve_index(&devices, &DeviceChoice::Device("{0.0.0.00000000}.{aaaa}".into()), headset), Some(0));
260 316 }
261 317
318 fn headset_lists() -> (Vec<AudioDevice>, Vec<AudioDevice>) {
319 let before = vec![device(0, "Speakers", "{s}")];
320 let after = vec![device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
321 (before, after)
322 }
323
324 #[test]
325 fn the_default_moving_to_a_new_headset_selects_it() {
326 let (before, after) = headset_lists();
327 let applied = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
328 assert_eq!(reselect(applied.as_ref(), &after, &DeviceChoice::SystemDefault, Some("{h}")), Reselect::Select(1));
329 }
330
331 #[test]
332 fn nothing_changed_keeps_the_device_running() {
333 let (_, after) = headset_lists();
334 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
335 assert_eq!(reselect(applied.as_ref(), &after, &DeviceChoice::SystemDefault, Some("{h}")), Reselect::Keep);
336 let explicit = DeviceChoice::Device("{h}".into());
337 let applied = applied_device(&after, &explicit, Some("{s}"));
338 assert_eq!(reselect(applied.as_ref(), &after, &explicit, Some("{s}")), Reselect::Keep);
339 }
340
341 #[test]
342 fn unplugging_the_selected_headset_falls_back_and_returns_when_it_comes_back() {
343 let (before, after) = headset_lists();
344 let explicit = DeviceChoice::Device("{h}".into());
345 let applied = applied_device(&after, &explicit, Some("{h}"));
346 assert_eq!(reselect(applied.as_ref(), &before, &explicit, Some("{s}")), Reselect::FallBack(0));
347 let fallen_back = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
348 assert_eq!(reselect(fallen_back.as_ref(), &before, &explicit, Some("{s}")), Reselect::Keep);
349 assert_eq!(reselect(fallen_back.as_ref(), &after, &explicit, Some("{s}")), Reselect::Select(1));
350 }
351
352 #[test]
353 fn a_shifted_index_with_the_same_key_is_reselected() {
354 let explicit = DeviceChoice::Device("{h}".into());
355 let before = [device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
356 let after = [device(0, "Dock", "{d}"), device(1, "Speakers", "{s}"), device(2, "Headset", "{h}")];
357 let applied = applied_device(&before, &explicit, None);
358 assert_eq!(reselect(applied.as_ref(), &after, &explicit, None), Reselect::Select(2));
359 }
360
361 #[test]
362 fn a_removed_default_selects_the_new_default() {
363 let (before, after) = headset_lists();
364 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
365 assert_eq!(reselect(applied.as_ref(), &before, &DeviceChoice::SystemDefault, Some("{s}")), Reselect::Select(0));
366 }
367
368 #[test]
369 fn the_notice_names_both_devices() {
370 let (before, after) = headset_lists();
371 let explicit = DeviceChoice::Device("{h}".into());
372 assert_eq!(disconnect_notice(&after, &explicit, before.first()), "Headset disconnected. Using Speakers.");
373 }
374
262 375 #[test]
263 376 fn unnamed_devices_are_hidden() {
264 377 let entries = menu_entries(&[device(0, " ", "g")]);
@@ -86,7 +86,7 @@ pub enum Flow {
86 Render,
86 Render,
87}
87}
88
88
89/// Endpoint id of the Windows default device (console role), which the ADM reports as the device guid.
89/// Endpoint id of the Windows default communications device, which the ADM reports as the device guid.
90#[cfg(windows)]
90#[cfg(windows)]
91pub fn system_default_id(flow: Flow) -> Option<String> {
91pub fn system_default_id(flow: Flow) -> Option<String> {
92 use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
92 use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
@@ -100,7 +100,7 @@ pub fn system_default_id(flow: Flow) -> Option<String> {
100
100
101#[cfg(windows)]
101#[cfg(windows)]
102fn default_endpoint_id(flow: Flow) -> Option<String> {
102fn default_endpoint_id(flow: Flow) -> Option<String> {
103 use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eConsole, eRender};
103 use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eRender};
104 use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
104 use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
105 let data_flow = match flow {
105 let data_flow = match flow {
106 Flow::Capture => eCapture,
106 Flow::Capture => eCapture,
@@ -108,7 +108,7 @@ fn default_endpoint_id(flow: Flow) -> Option<String> {
108 };
108 };
109 unsafe {
109 unsafe {
110 let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;
110 let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;
111 let device = enumerator.GetDefaultAudioEndpoint(data_flow, eConsole).ok()?;
111 let device = enumerator.GetDefaultAudioEndpoint(data_flow, eCommunications).ok()?;
112 let id = device.GetId().ok()?;
112 let id = device.GetId().ok()?;
113 let text = id.to_string().ok();
113 let text = id.to_string().ok();
114 CoTaskMemFree(Some(id.0 as *const _));
114 CoTaskMemFree(Some(id.0 as *const _));
@@ -135,6 +135,54 @@ pub fn resolve_index(devices: &[AudioDevice], choice: &DeviceChoice, system_defa
135 }
135 }
136}
136}
137
137
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct AppliedDevice {
140 pub index: u16,
141 pub key: String,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum Reselect {
146 Keep,
147 Select(u16),
148 FallBack(u16),
149}
150
151pub fn applied_device(devices: &[AudioDevice], choice: &DeviceChoice, system_default: Option<&str>) -> Option<AppliedDevice> {
152 let index = resolve_index(devices, choice, system_default)?;
153 device_at(devices, index)
154}
155
156fn device_at(devices: &[AudioDevice], index: u16) -> Option<AppliedDevice> {
157 devices
158 .iter()
159 .find(|device| device.index == index)
160 .map(|device| AppliedDevice { index, key: device.key() })
161}
162
163pub fn reselect(applied: Option<&AppliedDevice>, devices: &[AudioDevice], choice: &DeviceChoice, system_default: Option<&str>) -> Reselect {
164 let unchanged = |index: u16| device_at(devices, index).as_ref() == applied;
165 match resolve_index(devices, choice, system_default) {
166 Some(index) if unchanged(index) => Reselect::Keep,
167 Some(index) => Reselect::Select(index),
168 None => match resolve_index(devices, &DeviceChoice::SystemDefault, system_default) {
169 Some(index) if !unchanged(index) && matches!(choice, DeviceChoice::Device(_)) => Reselect::FallBack(index),
170 _ => Reselect::Keep,
171 },
172 }
173}
174
175pub fn disconnect_notice(previous: &[AudioDevice], choice: &DeviceChoice, fallback: Option<&AudioDevice>) -> String {
176 let lost = previous
177 .iter()
178 .find(|device| matches!(choice, DeviceChoice::Device(key) if device.key() == *key))
179 .map_or("Device", |device| device.name.as_str());
180 match fallback {
181 Some(device) => format!("{lost} disconnected. Using {}.", device.name),
182 None => format!("{lost} disconnected."),
183 }
184}
185
138fn enumerate(factory: &PeerConnectionFactory) -> DeviceLists {
186fn enumerate(factory: &PeerConnectionFactory) -> DeviceLists {
139 let inputs = (0..factory.recording_devices().max(0) as u16)
187 let inputs = (0..factory.recording_devices().max(0) as u16)
140 .map(|index| AudioDevice {
188 .map(|index| AudioDevice {
@@ -170,6 +218,10 @@ pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> b
170 let Some(index) = resolve_index(&enumerate(factory).inputs, choice, default_for(choice, Flow::Capture).as_deref()) else {
218 let Some(index) = resolve_index(&enumerate(factory).inputs, choice, default_for(choice, Flow::Capture).as_deref()) else {
171 return false;
219 return false;
172 };
220 };
221 select_input_index(factory, index)
222}
223
224pub fn select_input_index(factory: &PeerConnectionFactory, index: u16) -> bool {
173 factory.stop_recording();
225 factory.stop_recording();
174 let selected = factory.set_recording_device(index);
226 let selected = factory.set_recording_device(index);
175 factory.init_recording();
227 factory.init_recording();
@@ -181,6 +233,10 @@ pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) ->
181 let Some(index) = resolve_index(&enumerate(factory).outputs, choice, default_for(choice, Flow::Render).as_deref()) else {
233 let Some(index) = resolve_index(&enumerate(factory).outputs, choice, default_for(choice, Flow::Render).as_deref()) else {
182 return false;
234 return false;
183 };
235 };
236 select_output_index(factory, index)
237}
238
239pub fn select_output_index(factory: &PeerConnectionFactory, index: u16) -> bool {
184 factory.stop_playout();
240 factory.stop_playout();
185 let selected = factory.set_playout_device(index);
241 let selected = factory.set_playout_device(index);
186 factory.init_playout();
242 factory.init_playout();
@@ -259,6 +315,63 @@ mod tests {
259 assert_eq!(resolve_index(&devices, &DeviceChoice::Device("{0.0.0.00000000}.{aaaa}".into()), headset), Some(0));
315 assert_eq!(resolve_index(&devices, &DeviceChoice::Device("{0.0.0.00000000}.{aaaa}".into()), headset), Some(0));
260 }
316 }
261
317
318 fn headset_lists() -> (Vec<AudioDevice>, Vec<AudioDevice>) {
319 let before = vec![device(0, "Speakers", "{s}")];
320 let after = vec![device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
321 (before, after)
322 }
323
324 #[test]
325 fn the_default_moving_to_a_new_headset_selects_it() {
326 let (before, after) = headset_lists();
327 let applied = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
328 assert_eq!(reselect(applied.as_ref(), &after, &DeviceChoice::SystemDefault, Some("{h}")), Reselect::Select(1));
329 }
330
331 #[test]
332 fn nothing_changed_keeps_the_device_running() {
333 let (_, after) = headset_lists();
334 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
335 assert_eq!(reselect(applied.as_ref(), &after, &DeviceChoice::SystemDefault, Some("{h}")), Reselect::Keep);
336 let explicit = DeviceChoice::Device("{h}".into());
337 let applied = applied_device(&after, &explicit, Some("{s}"));
338 assert_eq!(reselect(applied.as_ref(), &after, &explicit, Some("{s}")), Reselect::Keep);
339 }
340
341 #[test]
342 fn unplugging_the_selected_headset_falls_back_and_returns_when_it_comes_back() {
343 let (before, after) = headset_lists();
344 let explicit = DeviceChoice::Device("{h}".into());
345 let applied = applied_device(&after, &explicit, Some("{h}"));
346 assert_eq!(reselect(applied.as_ref(), &before, &explicit, Some("{s}")), Reselect::FallBack(0));
347 let fallen_back = applied_device(&before, &DeviceChoice::SystemDefault, Some("{s}"));
348 assert_eq!(reselect(fallen_back.as_ref(), &before, &explicit, Some("{s}")), Reselect::Keep);
349 assert_eq!(reselect(fallen_back.as_ref(), &after, &explicit, Some("{s}")), Reselect::Select(1));
350 }
351
352 #[test]
353 fn a_shifted_index_with_the_same_key_is_reselected() {
354 let explicit = DeviceChoice::Device("{h}".into());
355 let before = [device(0, "Speakers", "{s}"), device(1, "Headset", "{h}")];
356 let after = [device(0, "Dock", "{d}"), device(1, "Speakers", "{s}"), device(2, "Headset", "{h}")];
357 let applied = applied_device(&before, &explicit, None);
358 assert_eq!(reselect(applied.as_ref(), &after, &explicit, None), Reselect::Select(2));
359 }
360
361 #[test]
362 fn a_removed_default_selects_the_new_default() {
363 let (before, after) = headset_lists();
364 let applied = applied_device(&after, &DeviceChoice::SystemDefault, Some("{h}"));
365 assert_eq!(reselect(applied.as_ref(), &before, &DeviceChoice::SystemDefault, Some("{s}")), Reselect::Select(0));
366 }
367
368 #[test]
369 fn the_notice_names_both_devices() {
370 let (before, after) = headset_lists();
371 let explicit = DeviceChoice::Device("{h}".into());
372 assert_eq!(disconnect_notice(&after, &explicit, before.first()), "Headset disconnected. Using Speakers.");
373 }
374
262 #[test]
375 #[test]
263 fn unnamed_devices_are_hidden() {
376 fn unnamed_devices_are_hidden() {
264 let entries = menu_entries(&[device(0, " ", "g")]);
377 let entries = menu_entries(&[device(0, " ", "g")]);
crates/calling/src/lib.rs +1 −0
@@ -10,6 +10,7 @@ pub mod captions;
10 10 pub mod capture;
11 11 pub mod control;
12 12 pub mod data_channel;
13 pub mod device_watch;
13 14 pub mod devices;
14 15 pub mod diagnostics;
15 16 pub mod engine;
@@ -10,6 +10,7 @@ pub mod captions;
10pub mod capture;
10pub mod capture;
11pub mod control;
11pub mod control;
12pub mod data_channel;
12pub mod data_channel;
13pub mod device_watch;
13pub mod devices;
14pub mod devices;
14pub mod diagnostics;
15pub mod diagnostics;
15pub mod engine;
16pub mod engine;