BlueGit

ict rusty-teams

Files

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

device_watch.rs

device_watch.rs 4.1 KiB Download Raw
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}