diff --git a/crates/client/src/share/camera.rs b/crates/client/src/share/camera.rs index 70db19b..c627050 100644 --- a/crates/client/src/share/camera.rs +++ b/crates/client/src/share/camera.rs @@ -50,7 +50,7 @@ pub struct Camera { alive: Arc, opened: Instant, stop: Arc, - thread: Option<(JoinHandle<()>, Receiver<()>, CameraIndex)>, + thread: Option<(JoinHandle<()>, Receiver<()>)>, _fake: Option, } @@ -64,20 +64,30 @@ fn held() -> std::sync::MutexGuard<'static, Vec> { impl Drop for Camera { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); - let Some((thread, done, index)) = self.thread.take() else { - return; - }; - if done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) { + if let Some((thread, done)) = self.thread.take() + && done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) + { let _ = thread.join(); - return; } - tracing::warn!(?index, "camera thread stuck, device held until it returns"); - held().push(index.clone()); - std::thread::spawn(move || { - let _ = done.recv(); - let _ = thread.join(); - held().retain(|busy| *busy != index); - }); + } +} + +struct Hold(CameraIndex); + +impl Hold { + fn take(index: CameraIndex) -> Option { + let mut held = held(); + if held.contains(&index) { + return None; + } + held.push(index.clone()); + Some(Self(index)) + } +} + +impl Drop for Hold { + fn drop(&mut self) { + held().retain(|busy| *busy != self.0); } } @@ -137,7 +147,7 @@ fn index(device: Option<&str>) -> Option { }) .unwrap_or(CameraIndex::Index(0)); if held().contains(&index) { - tracing::warn!(?index, "camera still held by a stuck thread"); + tracing::warn!(?index, "camera still held by our capture thread"); return None; } let count = format_count(&index); @@ -228,6 +238,7 @@ pub fn open(top: Quality, device: Option) -> Result { return Err(w().camera.needs_media_pack.to_string()); } let index = index(device.as_deref()).ok_or_else(|| w().camera.no_response.to_string())?; + let hold = Hold::take(index.clone()).ok_or_else(|| w().camera.no_response.to_string())?; let (negotiated_tx, negotiated_rx) = sync_channel::>(1); let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); let stop = Arc::new(AtomicBool::new(false)); @@ -236,11 +247,12 @@ pub fn open(top: Quality, device: Option) -> Result { let opened = Instant::now(); let (done_tx, done) = sync_channel::<()>(0); let thread = { - let (stop, fps, alive, index) = (stop.clone(), fps.clone(), alive.clone(), index.clone()); + let (stop, fps, alive) = (stop.clone(), fps.clone(), alive.clone()); std::thread::Builder::new() .name("camera-capture".to_string()) .spawn(move || { let _done = done_tx; + let _hold = hold; let clock = Clock { opened, alive: &alive, @@ -274,7 +286,7 @@ pub fn open(top: Quality, device: Option) -> Result { alive, opened, stop, - thread: Some((thread, done, index)), + thread: Some((thread, done)), _fake: None, }) }