1use crate::{DeviceInfo, Error, Result};
3use crossbeam_channel::{bounded, Receiver, Sender};
4use parking_lot::Mutex;
5use std::collections::BTreeMap;
6use std::sync::{
7 atomic::{AtomicBool, Ordering},
8 Arc,
9};
10use std::time::Duration;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum UsbPermission {
16 Unknown,
17 Required,
18 Granted,
19 Denied,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct UsbAttachment {
26 pub id: u64,
27 pub host_key: String,
28 pub info: DeviceInfo,
29 pub permission: UsbPermission,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum HotplugEvent {
35 Snapshot(Vec<UsbAttachment>),
37 Attached(UsbAttachment),
38 Detached(UsbAttachment),
39 PermissionChanged(UsbAttachment),
40 DiscoveryFailed(String),
41}
42
43struct Subscriber {
44 sender: Sender<HotplugEvent>,
45 overflow: Arc<AtomicBool>,
46}
47#[derive(Default)]
48struct State {
49 next_id: u64,
50 attached: BTreeMap<String, UsbAttachment>,
51 subscribers: Vec<Subscriber>,
52}
53
54#[derive(Clone, Default)]
59pub struct HotplugHub {
60 state: Arc<Mutex<State>>,
61}
62impl HotplugHub {
63 pub fn new() -> Self {
64 Self::default()
65 }
66 pub fn snapshot(&self) -> Vec<UsbAttachment> {
67 self.state.lock().attached.values().cloned().collect()
68 }
69 pub fn subscribe(&self) -> HotplugSubscription {
70 let (sender, receiver) = bounded(64);
71 let overflow = Arc::new(AtomicBool::new(false));
72 let mut state = self.state.lock();
73 let snapshot = state.attached.values().cloned().collect();
74 let _ = sender.try_send(HotplugEvent::Snapshot(snapshot));
75 state.subscribers.push(Subscriber {
76 sender,
77 overflow: overflow.clone(),
78 });
79 HotplugSubscription {
80 receiver,
81 overflow,
82 state: self.state.clone(),
83 }
84 }
85 pub fn attached(
88 &self,
89 host_key: impl Into<String>,
90 info: DeviceInfo,
91 permission: UsbPermission,
92 ) -> UsbAttachment {
93 let host_key = host_key.into();
94 let mut state = self.state.lock();
95 attach_or_replace(&mut state, host_key, info, permission)
96 }
97 pub fn reconcile(&self, devices: Vec<(String, DeviceInfo, UsbPermission)>) {
102 let mut state = self.state.lock();
103 let mut observed = BTreeMap::new();
104 for (key, info, permission) in devices {
105 observed.insert(key, (info, permission));
106 }
107 let missing: Vec<_> = state
108 .attached
109 .keys()
110 .filter(|key| !observed.contains_key(*key))
111 .cloned()
112 .collect();
113 for key in missing {
114 let attachment = state.attached.remove(&key).expect("attachment under lock");
115 broadcast(&mut state, HotplugEvent::Detached(attachment));
116 }
117 for (key, (info, permission)) in observed {
118 let attachment = attach_or_replace(&mut state, key.clone(), info, permission);
119 if attachment.permission != permission {
120 let existing = state.attached.get_mut(&key).expect("attachment under lock");
121 existing.permission = permission;
122 let event = HotplugEvent::PermissionChanged(existing.clone());
123 broadcast(&mut state, event);
124 }
125 }
126 }
127 pub fn permission_changed(&self, id: u64, permission: UsbPermission) -> bool {
129 let mut state = self.state.lock();
130 let Some(attachment) = state.attached.values_mut().find(|a| a.id == id) else {
131 return false;
132 };
133 if attachment.permission != permission {
134 attachment.permission = permission;
135 let event = HotplugEvent::PermissionChanged(attachment.clone());
136 broadcast(&mut state, event);
137 }
138 true
139 }
140 pub fn detached(&self, id: u64) -> bool {
141 let mut state = self.state.lock();
142 let Some(key) = state
143 .attached
144 .iter()
145 .find(|(_, a)| a.id == id)
146 .map(|(k, _)| k.clone())
147 else {
148 return false;
149 };
150 let attachment = state.attached.remove(&key).expect("attachment under lock");
151 broadcast(&mut state, HotplugEvent::Detached(attachment));
152 true
153 }
154}
155fn same_identity(existing: &UsbAttachment, info: &DeviceInfo) -> bool {
157 existing.info.vendor_id == info.vendor_id && existing.info.product_id == info.product_id
158}
159
160fn attach_or_replace(
161 state: &mut State,
162 host_key: String,
163 info: DeviceInfo,
164 permission: UsbPermission,
165) -> UsbAttachment {
166 if let Some(existing) = state.attached.get(&host_key) {
167 if same_identity(existing, &info) {
168 return existing.clone();
169 }
170 let old = state
171 .attached
172 .remove(&host_key)
173 .expect("attachment under lock");
174 broadcast(state, HotplugEvent::Detached(old));
175 }
176 state.next_id = state
177 .next_id
178 .checked_add(1)
179 .expect("USB attachment ID exhausted");
180 let attachment = UsbAttachment {
181 id: state.next_id,
182 host_key: host_key.clone(),
183 info,
184 permission,
185 };
186 state.attached.insert(host_key, attachment.clone());
187 broadcast(state, HotplugEvent::Attached(attachment.clone()));
188 attachment
189}
190
191fn broadcast(state: &mut State, event: HotplugEvent) {
192 state.subscribers.retain(
193 |subscriber| match subscriber.sender.try_send(event.clone()) {
194 Ok(()) => true,
195 Err(crossbeam_channel::TrySendError::Full(_)) => {
196 subscriber.overflow.store(true, Ordering::Release);
197 true
198 }
199 Err(crossbeam_channel::TrySendError::Disconnected(_)) => false,
200 },
201 );
202}
203
204pub struct HotplugSubscription {
207 receiver: Receiver<HotplugEvent>,
208 overflow: Arc<AtomicBool>,
209 state: Arc<Mutex<State>>,
210}
211impl HotplugSubscription {
212 fn resync(&self) -> Option<HotplugEvent> {
213 let state = self.state.lock();
214 if self.overflow.swap(false, Ordering::AcqRel) {
215 for _ in 0..64 {
216 let _ = self.receiver.try_recv();
217 }
218 Some(HotplugEvent::Snapshot(
219 state.attached.values().cloned().collect(),
220 ))
221 } else {
222 None
223 }
224 }
225 pub fn try_recv(&self) -> std::result::Result<HotplugEvent, crossbeam_channel::TryRecvError> {
226 if let Some(snapshot) = self.resync() {
227 Ok(snapshot)
228 } else {
229 self.receiver.try_recv()
230 }
231 }
232 pub fn recv_timeout(
233 &self,
234 timeout: Duration,
235 ) -> std::result::Result<HotplugEvent, crossbeam_channel::RecvTimeoutError> {
236 if let Some(snapshot) = self.resync() {
237 return Ok(snapshot);
238 }
239 let event = self.receiver.recv_timeout(timeout)?;
240 if let Some(snapshot) = self.resync() {
241 Ok(snapshot)
242 } else {
243 Ok(event)
244 }
245 }
246}
247
248pub struct LinuxHotplugMonitor {
255 stop: Sender<()>,
256 worker: Option<std::thread::JoinHandle<()>>,
257 hub: HotplugHub,
258}
259impl LinuxHotplugMonitor {
260 pub fn start() -> Result<Self> {
261 #[cfg(target_os = "linux")]
262 {
263 let context = rusb::Context::new().map_err(|e| Error::Claim(e.to_string()))?;
264 let hub = HotplugHub::new();
265 use rusb::UsbContext;
266 let native = rusb::has_hotplug();
267 let registration = if native {
268 Some(
269 rusb::HotplugBuilder::new()
270 .enumerate(true)
271 .register(&context, Box::new(NativeHotplug(hub.clone())))
272 .map_err(|e| Error::Claim(e.to_string()))?,
273 )
274 } else {
275 for (key, info) in scan_linux(&context)? {
276 hub.attached(key, info, UsbPermission::Unknown);
277 }
278 None
279 };
280 let worker_hub = hub.clone();
281 let (stop, receiver) = bounded(1);
282 let worker = std::thread::Builder::new()
283 .name("usbdac-hotplug".into())
284 .spawn(move || {
285 let _registration = registration;
286 while receiver.try_recv() == Err(crossbeam_channel::TryRecvError::Empty) {
287 if native {
288 if let Err(error) =
289 context.handle_events(Some(Duration::from_millis(100)))
290 {
291 broadcast(
292 &mut worker_hub.state.lock(),
293 HotplugEvent::DiscoveryFailed(error.to_string()),
294 );
295 break;
296 }
297 continue;
298 }
299 if receiver.recv_timeout(Duration::from_millis(250))
300 != Err(crossbeam_channel::RecvTimeoutError::Timeout)
301 {
302 break;
303 }
304 match scan_linux(&context) {
305 Ok(devices) => {
306 for attachment in worker_hub.snapshot() {
307 if !devices.iter().any(|(key, info)| {
308 *key == attachment.host_key
309 && info.vendor_id == attachment.info.vendor_id
310 && info.product_id == attachment.info.product_id
311 }) {
312 worker_hub.detached(attachment.id);
313 }
314 }
315 for (key, info) in devices {
316 worker_hub.attached(key, info, UsbPermission::Unknown);
317 }
318 }
319 Err(e) => broadcast(
320 &mut worker_hub.state.lock(),
321 HotplugEvent::DiscoveryFailed(e.to_string()),
322 ),
323 }
324 }
325 })
326 .map_err(|e| Error::Claim(e.to_string()))?;
327 Ok(Self {
328 stop,
329 worker: Some(worker),
330 hub,
331 })
332 }
333 #[cfg(not(target_os = "linux"))]
334 {
335 Err(Error::PlatformUnsupported)
336 }
337 }
338 pub fn hub(&self) -> HotplugHub {
339 self.hub.clone()
340 }
341}
342#[cfg(target_os = "linux")]
343struct NativeHotplug(HotplugHub);
344#[cfg(target_os = "linux")]
345impl rusb::Hotplug<rusb::Context> for NativeHotplug {
346 fn device_arrived(&mut self, device: rusb::Device<rusb::Context>) {
347 if let Some((key, info)) = describe_linux(&device) {
348 self.0.attached(key, info, UsbPermission::Unknown);
349 }
350 }
351 fn device_left(&mut self, device: rusb::Device<rusb::Context>) {
352 let key = linux_path(&device);
353 if let Some(attachment) = self.0.snapshot().into_iter().find(|a| a.host_key == key) {
354 self.0.detached(attachment.id);
355 }
356 }
357}
358#[cfg(target_os = "linux")]
359fn linux_path(device: &rusb::Device<rusb::Context>) -> String {
360 format!(
361 "/dev/bus/usb/{:03}/{:03}",
362 device.bus_number(),
363 device.address()
364 )
365}
366#[cfg(target_os = "linux")]
367fn describe_linux(device: &rusb::Device<rusb::Context>) -> Option<(String, DeviceInfo)> {
368 let descriptor = device.device_descriptor().ok()?;
369 let audio = descriptor.class_code() == 1
370 || (0..descriptor.num_configurations()).any(|index| {
371 device.config_descriptor(index).is_ok_and(|config| {
372 config
373 .interfaces()
374 .any(|i| i.descriptors().any(|d| d.class_code() == 1))
375 })
376 });
377 if !audio {
378 return None;
379 }
380 let path = linux_path(device);
381 let info = DeviceInfo::new(
382 descriptor.vendor_id(),
383 descriptor.product_id(),
384 format!(
385 "USB audio {:04x}:{:04x}",
386 descriptor.vendor_id(),
387 descriptor.product_id()
388 ),
389 )
390 .with_device_name(path.clone());
391 Some((path, info))
392}
393#[cfg(target_os = "linux")]
394fn scan_linux(context: &rusb::Context) -> Result<Vec<(String, DeviceInfo)>> {
395 use rusb::UsbContext;
396 let devices = context.devices().map_err(|e| Error::Claim(e.to_string()))?;
397 let mut result = Vec::new();
398 for device in devices.iter() {
399 if let Some(device) = describe_linux(&device) {
400 result.push(device);
401 }
402 }
403 Ok(result)
404}
405impl Drop for LinuxHotplugMonitor {
406 fn drop(&mut self) {
407 let _ = self.stop.try_send(());
408 if let Some(worker) = self.worker.take() {
409 let _ = worker.join();
410 }
411 }
412}