BlueGit

ict rusty-teams

Files

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

device_watch.rs

device_watch.rs 7.2 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 touched_ids: Vec<String>,
12}
13
14impl Debounce {
15 pub fn signal(&mut self, now: Instant) {
16 self.signal_device(now, None);
17 }
18
19 pub fn signal_device(&mut self, now: Instant, device_id: Option<String>) {
20 self.deadline = Some(now + DEVICE_CHANGE_QUIET);
21 if let Some(id) = device_id
22 && !self
23 .touched_ids
24 .iter()
25 .any(|existing| existing.eq_ignore_ascii_case(&id))
26 {
27 self.touched_ids.push(id);
28 }
29 }
30
31 pub fn deadline(&self) -> Option<Instant> {
32 self.deadline
33 }
34
35 pub fn take_due(&mut self, now: Instant) -> bool {
36 self.take_due_devices(now).is_some()
37 }
38
39 pub fn take_due_devices(&mut self, now: Instant) -> Option<Vec<String>> {
40 let due = self.deadline.is_some_and(|deadline| now >= deadline);
41 if due {
42 self.deadline = None;
43 Some(std::mem::take(&mut self.touched_ids))
44 } else {
45 None
46 }
47 }
48}
49
50pub struct DeviceWatcher {
51 #[cfg(windows)]
52 _stop: std::sync::mpsc::Sender<()>,
53}
54
55pub fn endpoint_delta(previous: &[String], current: &[String]) -> Vec<String> {
56 let mut changed = Vec::new();
57 for id in previous.iter().chain(current.iter()) {
58 let before = previous.iter().any(|key| key.eq_ignore_ascii_case(id));
59 let after = current.iter().any(|key| key.eq_ignore_ascii_case(id));
60 let seen = changed.iter().any(|key: &String| key.eq_ignore_ascii_case(id));
61 if before != after && !seen {
62 changed.push(id.clone());
63 }
64 }
65 changed
66}
67
68pub fn watch() -> (DeviceWatcher, UnboundedReceiver<Option<String>>) {
69 let (sender, receiver) = unbounded_channel();
70 (platform::start(sender), receiver)
71}
72
73#[cfg(windows)]
74mod platform {
75 use tokio::sync::mpsc::UnboundedSender;
76 use windows::Win32::Foundation::PROPERTYKEY;
77 use windows::Win32::Media::Audio::{
78 DEVICE_STATE, EDataFlow, ERole, IMMDeviceEnumerator, IMMNotificationClient,
79 IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications, eConsole,
80 };
81 use windows::Win32::System::Com::{
82 CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,
83 };
84 use windows::core::PCWSTR;
85 use windows_core::implement;
86
87 use super::DeviceWatcher;
88
89 fn id_string(device_id: &PCWSTR) -> Option<String> {
90 if device_id.is_null() {
91 return None;
92 }
93 unsafe { device_id.to_string().ok() }.filter(|id| !id.is_empty())
94 }
95
96 #[implement(IMMNotificationClient)]
97 struct Client {
98 sender: UnboundedSender<Option<String>>,
99 }
100
101 impl IMMNotificationClient_Impl for Client_Impl {
102 fn OnDeviceStateChanged(
103 &self,
104 device_id: &PCWSTR,
105 _state: DEVICE_STATE,
106 ) -> windows::core::Result<()> {
107 let _ = self.sender.send(id_string(device_id));
108 Ok(())
109 }
110
111 fn OnDeviceAdded(&self, device_id: &PCWSTR) -> windows::core::Result<()> {
112 let _ = self.sender.send(id_string(device_id));
113 Ok(())
114 }
115
116 fn OnDeviceRemoved(&self, device_id: &PCWSTR) -> windows::core::Result<()> {
117 let _ = self.sender.send(id_string(device_id));
118 Ok(())
119 }
120
121 fn OnDefaultDeviceChanged(
122 &self,
123 _flow: EDataFlow,
124 role: ERole,
125 _device_id: &PCWSTR,
126 ) -> windows::core::Result<()> {
127 if role == eConsole || role == eCommunications {
128 let _ = self.sender.send(None);
129 }
130 Ok(())
131 }
132
133 fn OnPropertyValueChanged(
134 &self,
135 _device_id: &PCWSTR,
136 _key: &PROPERTYKEY,
137 ) -> windows::core::Result<()> {
138 Ok(())
139 }
140 }
141
142 pub fn start(sender: UnboundedSender<Option<String>>) -> DeviceWatcher {
143 let (stop, stopped) = std::sync::mpsc::channel::<()>();
144 std::thread::spawn(move || unsafe {
145 let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();
146 if let Ok(enumerator) =
147 CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL)
148 {
149 let client: IMMNotificationClient = Client { sender }.into();
150 if enumerator
151 .RegisterEndpointNotificationCallback(&client)
152 .is_ok()
153 {
154 let _ = stopped.recv();
155 let _ = enumerator.UnregisterEndpointNotificationCallback(&client);
156 }
157 }
158 if initialized {
159 CoUninitialize();
160 }
161 });
162 DeviceWatcher { _stop: stop }
163 }
164}
165
166#[cfg(not(windows))]
167mod platform {
168 use tokio::sync::mpsc::UnboundedSender;
169
170 use super::DeviceWatcher;
171
172 pub fn start(_sender: UnboundedSender<Option<String>>) -> DeviceWatcher {
173 DeviceWatcher {}
174 }
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 #[test]
182 fn a_burst_of_events_fires_once_after_the_quiet_period() {
183 let start = Instant::now();
184 let mut debounce = Debounce::default();
185 assert!(!debounce.take_due(start));
186 debounce.signal(start);
187 debounce.signal(start + Duration::from_millis(300));
188 assert!(!debounce.take_due(start + Duration::from_millis(600)));
189 assert!(debounce.take_due(start + Duration::from_millis(800)));
190 assert!(!debounce.take_due(start + Duration::from_millis(900)));
191 assert_eq!(debounce.deadline(), None);
192 }
193
194 #[test]
195 fn debounce_collects_unique_touched_device_ids() {
196 let start = Instant::now();
197 let mut debounce = Debounce::default();
198 debounce.signal_device(start, Some("{dev-a}".into()));
199 debounce.signal_device(start + Duration::from_millis(100), Some("{DEV-A}".into()));
200 debounce.signal_device(start + Duration::from_millis(200), None);
201 debounce.signal_device(start + Duration::from_millis(250), Some("{dev-b}".into()));
202 let ids = debounce
203 .take_due_devices(start + Duration::from_millis(800))
204 .expect("due");
205 assert_eq!(ids, vec!["{dev-a}".to_owned(), "{dev-b}".to_owned()]);
206 assert_eq!(
207 debounce.take_due_devices(start + Duration::from_millis(900)),
208 None
209 );
210 }
211
212 #[test]
213 fn a_device_that_leaves_and_returns_inside_the_quiet_period_is_one_event() {
214 let start = Instant::now();
215 let present = vec!["{headset}".to_owned()];
216 let gone = Vec::new();
217 let mut debounce = Debounce::default();
218 for id in endpoint_delta(&present, &gone) {
219 debounce.signal_device(start, Some(id));
220 }
221 for id in endpoint_delta(&gone, &present) {
222 debounce.signal_device(start + Duration::from_millis(200), Some(id));
223 }
224 assert_eq!(
225 debounce.take_due_devices(start + DEVICE_CHANGE_QUIET + Duration::from_millis(200)),
226 Some(vec!["{headset}".to_owned()])
227 );
228 }
229}