use std::{ sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU32, Ordering}, mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}, }, thread::JoinHandle, time::{Duration, Instant}, }; use crate::lang::w; use common::share::{Mode, Quality, clamp}; use nokhwa::{ Buffer, Camera as Device, pixel_format::RgbFormat, utils::{CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType}, }; use super::frame::{FRAME_QUEUE, Feed, Frame, elapsed_ms}; const OPEN_TIMEOUT: Duration = Duration::from_secs(10); const RETRY_DELAY: Duration = Duration::from_millis(5); 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), RequestedFormatType::HighestFrameRate(25), RequestedFormatType::AbsoluteHighestFrameRate, ]; const DECODABLE: [FrameFormat; 3] = [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG]; struct Negotiated { width: u32, height: u32, largest: (u32, u32), modes: Vec, } struct Shared { stop: AtomicBool, fps: AtomicU32, alive: AtomicU32, opened: Instant, } impl Shared { fn beat(&self) { self.alive.store(elapsed_ms(self.opened), Ordering::Relaxed); } } pub struct Camera { shared: Arc, thread: Option>, done: Receiver<()>, } 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.shared.stop.store(true, Ordering::Relaxed); if let Some(thread) = self.thread.take() && self.done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) { let _ = thread.join(); } } } 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); } } impl Camera { pub fn stalled(&self) -> bool { let alive = Duration::from_millis(self.shared.alive.load(Ordering::Relaxed).into()); self.shared.opened.elapsed().saturating_sub(alive) > STALL } pub fn set_fps(&self, fps: u32) { self.shared.fps.store(fps, Ordering::Relaxed); } } const MEDIA_FOUNDATION: [&str; 3] = ["mf.dll", "mfplat.dll", "mfreadwrite.dll"]; fn available() -> bool { if !cfg!(windows) { return true; } let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_string()); MEDIA_FOUNDATION.iter().all(|dll| { std::path::Path::new(&system) .join("System32") .join(dll) .exists() }) } pub fn devices() -> Vec { if std::env::var_os("YUMUSH_TEST_CAMERA").is_some() { return vec!["Test camera".to_string()]; } if !available() { return Vec::new(); } named().into_iter().map(|(name, _)| name).collect() } fn named() -> Vec<(String, CameraIndex)> { let nodes: Vec<(String, CameraIndex)> = nokhwa::query(nokhwa::utils::ApiBackend::Auto) .unwrap_or_default() .into_iter() .filter(|info| captures(info.index())) .map(|info| (info.human_name(), info.index().clone())) .collect(); nodes .iter() .enumerate() .map(|(position, (name, index))| { let earlier = nodes[..position] .iter() .filter(|(other, _)| other == name) .count(); let name = match earlier { 0 => name.clone(), copies => format!("{name} ({})", copies + 1), }; (name, index.clone()) }) .collect() } pub fn label(name: &str) -> &str { match name.split_once(": ") { Some((left, right)) if left == right => left, _ => name, } } fn index(device: Option<&str>) -> Option { let nodes = named(); let index = nodes .iter() .find(|(name, _)| Some(name.as_str()) == device) .or(nodes.first()) .map_or(CameraIndex::Index(0), |(_, index)| index.clone()); if held().contains(&index) { tracing::warn!(?index, "camera still held by our capture 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 steps(min: u32, max: u32, step: u32) -> u64 { u64::from(max.saturating_sub(min) / step.max(1)) + 1 } #[cfg(target_os = "linux")] fn format_count(index: &CameraIndex) -> u64 { use v4l::{frameinterval::FrameIntervalEnum, framesize::FrameSizeEnum, video::Capture}; 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(target_os = "linux")] fn captures(index: &CameraIndex) -> bool { index .as_index() .ok() .and_then(|number| v4l::Device::new(number as usize).ok()) .and_then(|device| device.query_caps().ok()) .is_some_and(|caps| { caps.capabilities .contains(v4l::capability::Flags::VIDEO_CAPTURE) }) } #[cfg(not(target_os = "linux"))] fn captures(_: &CameraIndex) -> bool { true } #[cfg(not(target_os = "linux"))] fn format_count(_: &CameraIndex) -> u64 { 0 } pub fn open(top: Quality, device: Option) -> Result<(Feed, Camera), String> { 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 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 shared = Arc::new(Shared { stop: AtomicBool::new(false), fps: AtomicU32::new(u32::MAX), alive: AtomicU32::new(0), opened: Instant::now(), }); let (done_tx, done) = sync_channel::<()>(0); let thread = { let shared = shared.clone(); std::thread::Builder::new() .name("camera-capture".to_string()) .spawn(move || { let _done = done_tx; let _hold = hold; run(top, &index, &shared, negotiated_tx, frames_tx) }) .map_err(|error| error.to_string())? }; let negotiated = match negotiated_rx.recv_timeout(OPEN_TIMEOUT) { Ok(negotiated) => negotiated, Err(_) => { shared.stop.store(true, Ordering::Relaxed); return Err(w().camera.no_response.to_string()); } }; let negotiated = match negotiated { Ok(negotiated) => negotiated, Err(error) => { let _ = thread.join(); return Err(error); } }; let feed = Feed { width: negotiated.width, height: negotiated.height, largest: negotiated.largest, modes: negotiated.modes, frames: frames_rx, }; Ok(( feed, Camera { shared, thread: Some(thread), done, }, )) } pub fn list(device: Option<&str>) -> Vec { if let Ok(spec) = std::env::var("YUMUSH_TEST_CAMERA") { return spec .split_once('@') .and_then(|(size, fps)| { Some((size.split_once('x')?.1.parse().ok()?, fps.parse().ok()?)) }) .into_iter() .collect(); } if !available() { return Vec::new(); } let Some(index) = index(device) else { return Vec::new(); }; let any = RequestedFormat::new::(RequestedFormatType::None); Device::new(index, any) .and_then(|mut camera| camera.compatible_camera_formats()) .map(|formats| modes(&decodable(formats))) .unwrap_or_default() } fn decodable(formats: Vec) -> Vec { formats .into_iter() .filter(|format| DECODABLE.contains(&format.format())) .collect() } fn modes(formats: &[CameraFormat]) -> Vec { let mut modes: Vec = formats .iter() .map(|format| (format.height(), format.frame_rate())) .collect(); modes.sort_unstable(); modes.dedup(); modes } fn size(formats: &[CameraFormat]) -> Option<(u32, u32)> { formats .iter() .map(|format| (format.width(), format.height())) .max_by_key(|(width, height)| (*height, *width)) } fn pick(formats: &[CameraFormat], top: Quality) -> Option { let quality = clamp(top, &modes(formats), u32::MAX); let height = quality.resolution.height(); let refresh = quality.fps.value(); formats.iter().copied().min_by_key(|format| { ( format.height() < height, std::cmp::Reverse(format.frame_rate().min(refresh)), format.height(), format.format() == FrameFormat::MJPEG, format.frame_rate().abs_diff(refresh), ) }) } fn open_fitting(top: Quality, index: &CameraIndex) -> Option<(Device, Vec)> { let any = RequestedFormat::new::(RequestedFormatType::None); let mut camera = Device::new(index.clone(), any).ok()?; let formats = decodable(camera.compatible_camera_formats().ok()?); let chosen = pick(&formats, top)?; let exact = RequestedFormat::new::(RequestedFormatType::Exact(chosen)); camera.set_camera_requset(exact).ok()?; camera.open_stream().ok()?; Some((camera, formats)) } 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 { let requested = RequestedFormat::new::(wanted); let opened = Device::new(index.clone(), requested).and_then(|mut camera| { camera.open_stream()?; Ok(camera) }); match opened { Ok(camera) => { let format = camera.camera_format(); return Ok((camera, vec![format])); } Err(error) => tracing::warn!(%error, "camera open failed"), } } Err(w().camera.not_found.to_string()) } fn run( top: Quality, index: &CameraIndex, shared: &Shared, negotiated: SyncSender>, frames: SyncSender, ) { let (mut camera, formats) = match open_device(top, index) { Ok(opened) => opened, Err(error) => { let _ = negotiated.send(Err(error)); return; } }; let format = camera.camera_format(); tracing::info!(?format, "camera opened"); shared.beat(); let _ = negotiated.send(Ok(Negotiated { width: format.width(), height: format.height(), largest: size(&formats).unwrap_or((format.width(), format.height())), modes: modes(&formats), })); let started = Instant::now(); let mut failures = 0; let mut due = 0u32; while !shared.stop.load(Ordering::Relaxed) { crate::usage::tick(crate::usage::Group::Camera); let buffer = match camera.frame() { Ok(buffer) => buffer, Err(error) => { failures += 1; if failures >= MAX_FAILURES { tracing::warn!(%error, "camera lost"); break; } std::thread::sleep(RETRY_DELAY); continue; } }; failures = 0; shared.beat(); let timestamp_ms = elapsed_ms(started); let wanted = shared.fps.load(Ordering::Relaxed); if wanted == 0 || timestamp_ms + SLACK_MS < due { continue; } due = due.max(timestamp_ms.saturating_sub(SLACK_MS)) + 1000 / wanted; let Some((width, height, bgra)) = to_bgra(&buffer) else { continue; }; let _ = frames.try_send(Frame::cpu(width, height, timestamp_ms, bgra)); } let _ = camera.stop_stream(); } fn to_bgra(buffer: &Buffer) -> Option<(u32, u32, Vec)> { let resolution = buffer.resolution(); let (width, height) = (resolution.width(), resolution.height()); let data = buffer.buffer(); match buffer.source_frame_format() { FrameFormat::YUYV => Some((width, height, pixel::yuyv_to_bgra(data, width, height)?)), FrameFormat::NV12 => Some((width, height, pixel::nv12_to_bgra(data, width, height)?)), FrameFormat::MJPEG => pixel::jpeg_to_bgra(data), _ => None, } }