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