diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index b3864fc..c1a03d2 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -44,6 +44,7 @@ resvg = "0.50.0" nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } [target.'cfg(target_os = "linux")'.dependencies] +v4l = "0.14.0" pipewire = { version = "0.10.1", features = ["v0_3_49"] } ksni = "0.3.7" ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } diff --git a/crates/client/src/share/camera.rs b/crates/client/src/share/camera.rs index fea1c8c..6c3b1fb 100644 --- a/crates/client/src/share/camera.rs +++ b/crates/client/src/share/camera.rs @@ -2,6 +2,7 @@ use std::{ sync::{ Arc, atomic::{AtomicBool, AtomicU32, Ordering}, + Mutex, mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}, }, thread::JoinHandle, @@ -27,6 +28,7 @@ const SLACK_MS: u32 = 4; const MAX_FAILURES: u32 = 200; const STALL: Duration = Duration::from_secs(5); const JOIN_TIMEOUT: Duration = Duration::from_secs(1); +const MAX_FORMATS: u64 = 100_000; const WANTED_FORMATS: [RequestedFormatType; 4] = [ RequestedFormatType::HighestFrameRate(30), RequestedFormatType::HighestFrameRate(60), @@ -49,18 +51,33 @@ pub struct Camera { alive: Arc, opened: Instant, stop: Arc, - thread: Option<(JoinHandle<()>, Receiver<()>)>, + thread: Option<(JoinHandle<()>, Receiver<()>, CameraIndex)>, _fake: Option, } +static HELD: Mutex> = Mutex::new(Vec::new()); + +fn held() -> std::sync::MutexGuard<'static, Vec> { + HELD.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + impl Drop for Camera { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); - if let Some((thread, done)) = self.thread.take() - && done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) - { + let Some((thread, done, index)) = self.thread.take() else { + return; + }; + if 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); + }); } } @@ -109,8 +126,8 @@ pub fn label(name: &str) -> &str { } } -fn index(device: Option<&str>) -> CameraIndex { - device +fn index(device: Option<&str>) -> Option { + let index = device .and_then(|name| { nokhwa::query(nokhwa::utils::ApiBackend::Auto) .ok()? @@ -118,7 +135,64 @@ fn index(device: Option<&str>) -> CameraIndex { .find(|info| info.human_name() == name) .map(|info| info.index().clone()) }) - .unwrap_or(CameraIndex::Index(0)) + .unwrap_or(CameraIndex::Index(0)); + if held().contains(&index) { + tracing::warn!(?index, "camera still held by a stuck thread"); + return None; + } + let count = format_count(&index); + if count > MAX_FORMATS { + tracing::warn!(?index, count, "camera reports too many formats, device not ready"); + return None; + } + Some(index) +} + +#[cfg(target_os = "linux")] +fn format_count(index: &CameraIndex) -> u64 { + use v4l::{frameinterval::FrameIntervalEnum, framesize::FrameSizeEnum, video::Capture}; + let steps = |min: u32, max: u32, step: u32| u64::from(max.saturating_sub(min) / step.max(1)) + 1; + let Some(device) = index + .as_index() + .ok() + .and_then(|number| v4l::Device::new(number as usize).ok()) + else { + return 0; + }; + let mut count = 0u64; + for format in device.enum_formats().unwrap_or_default() { + for size in device.enum_framesizes(format.fourcc).unwrap_or_default() { + let (sizes, width, height) = match size.size { + FrameSizeEnum::Discrete(size) => (1, size.width, size.height), + FrameSizeEnum::Stepwise(size) => ( + steps(size.min_width, size.max_width, size.step_width) + .min(steps(size.min_height, size.max_height, size.step_height)), + size.min_width, + size.min_height, + ), + }; + let intervals: u64 = device + .enum_frameintervals(format.fourcc, width, height) + .unwrap_or_default() + .iter() + .map(|interval| match &interval.interval { + FrameIntervalEnum::Discrete(_) => 1, + FrameIntervalEnum::Stepwise(range) => steps( + range.min.numerator, + range.max.numerator, + range.step.numerator, + ), + }) + .sum(); + count = count.saturating_add(sizes.saturating_mul(intervals.max(1))); + } + } + count +} + +#[cfg(not(target_os = "linux"))] +fn format_count(_: &CameraIndex) -> u64 { + 0 } pub fn open(top: Quality, device: Option) -> Result { @@ -142,6 +216,7 @@ pub fn open(top: Quality, device: Option) -> Result { if !available() { 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 (negotiated_tx, negotiated_rx) = sync_channel::>(1); let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); let stop = Arc::new(AtomicBool::new(false)); @@ -150,7 +225,7 @@ 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) = (stop.clone(), fps.clone(), alive.clone()); + let (stop, fps, alive, index) = (stop.clone(), fps.clone(), alive.clone(), index.clone()); std::thread::Builder::new() .name("camera-capture".to_string()) .spawn(move || { @@ -159,7 +234,7 @@ pub fn open(top: Quality, device: Option) -> Result { opened, alive: &alive, }; - run(top, device, &stop, &fps, &clock, negotiated_tx, frames_tx) + run(top, &index, &stop, &fps, &clock, negotiated_tx, frames_tx) }) .map_err(|error| error.to_string())? }; @@ -188,7 +263,7 @@ pub fn open(top: Quality, device: Option) -> Result { alive, opened, stop, - thread: Some((thread, done)), + thread: Some((thread, done, index)), _fake: None, }) } @@ -206,8 +281,11 @@ pub fn list(device: Option<&str>) -> Vec { if !available() { return Vec::new(); } + let Some(index) = index(device) else { + return Vec::new(); + }; let any = RequestedFormat::new::(RequestedFormatType::None); - Device::new(index(device), any) + Device::new(index, any) .and_then(|mut camera| camera.compatible_camera_formats()) .map(|formats| modes(&decodable(formats))) .unwrap_or_default() @@ -260,9 +338,8 @@ fn open_fitting(top: Quality, index: &CameraIndex) -> Option<(Device, Vec) -> Result<(Device, Vec), String> { - let index = index(device); - if let Some(opened) = open_fitting(top, &index) { +fn open_device(top: Quality, index: &CameraIndex) -> Result<(Device, Vec), String> { + if let Some(opened) = open_fitting(top, index) { return Ok(opened); } for wanted in WANTED_FORMATS { @@ -293,14 +370,14 @@ impl Clock<'_> { fn run( top: Quality, - device: Option, + index: &CameraIndex, stop: &AtomicBool, fps: &AtomicU32, clock: &Clock, negotiated: SyncSender>, frames: SyncSender, ) { - let (mut camera, formats) = match open_device(top, device.as_deref()) { + let (mut camera, formats) = match open_device(top, index) { Ok(opened) => opened, Err(error) => { let _ = negotiated.send(Err(error));