forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

camera.rs512 lines, 15.4 KiBHistoryRawDownload
1use std::{
2 sync::{
3 Arc, Mutex,
4 atomic::{AtomicBool, AtomicU32, Ordering},
5 mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel},
6 },
7 thread::JoinHandle,
8 time::{Duration, Instant},
9};
10
11use crate::lang::w;
12use common::share::{Mode, Quality, clamp};
13use nokhwa::{
14 Buffer, Camera as Device,
15 pixel_format::RgbFormat,
16 utils::{CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType},
17};
18
19use super::{
20 fake,
21 frame::{BYTES_PER_PIXEL, FRAME_QUEUE, Frame},
22};
23
24const OPEN_TIMEOUT: Duration = Duration::from_secs(10);
25const RETRY_DELAY: Duration = Duration::from_millis(5);
26const SLACK_MS: u32 = 4;
27const MAX_FAILURES: u32 = 200;
28const STALL: Duration = Duration::from_secs(5);
29const JOIN_TIMEOUT: Duration = Duration::from_secs(1);
30const MAX_FORMATS: u64 = 100_000;
31const WANTED_FORMATS: [RequestedFormatType; 4] = [
32 RequestedFormatType::HighestFrameRate(30),
33 RequestedFormatType::HighestFrameRate(60),
34 RequestedFormatType::HighestFrameRate(25),
35 RequestedFormatType::AbsoluteHighestFrameRate,
36];
37
38const DECODABLE: [FrameFormat; 3] = [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
39
40type Negotiated = (u32, u32, u32, (u32, u32), Vec<Mode>);
41
42pub struct Camera {
43 pub width: u32,
44 pub height: u32,
45 pub refresh: u32,
46 pub size: (u32, u32),
47 pub modes: Vec<Mode>,
48 pub frames: Receiver<Frame>,
49 pub fps: Arc<AtomicU32>,
50 alive: Arc<AtomicU32>,
51 opened: Instant,
52 stop: Arc<AtomicBool>,
53 thread: Option<(JoinHandle<()>, Receiver<()>)>,
54 _fake: Option<fake::Generator>,
55}
56
57static HELD: Mutex<Vec<CameraIndex>> = Mutex::new(Vec::new());
58
59fn held() -> std::sync::MutexGuard<'static, Vec<CameraIndex>> {
60 HELD.lock()
61 .unwrap_or_else(std::sync::PoisonError::into_inner)
62}
63
64impl Drop for Camera {
65 fn drop(&mut self) {
66 self.stop.store(true, Ordering::Relaxed);
67 if let Some((thread, done)) = self.thread.take()
68 && done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout)
69 {
70 let _ = thread.join();
71 }
72 }
73}
74
75struct Hold(CameraIndex);
76
77impl Hold {
78 fn take(index: CameraIndex) -> Option<Self> {
79 let mut held = held();
80 if held.contains(&index) {
81 return None;
82 }
83 held.push(index.clone());
84 Some(Self(index))
85 }
86}
87
88impl Drop for Hold {
89 fn drop(&mut self) {
90 held().retain(|busy| *busy != self.0);
91 }
92}
93
94impl Camera {
95 pub fn stalled(&self) -> bool {
96 let alive = Duration::from_millis(self.alive.load(Ordering::Relaxed).into());
97 self.thread.is_some() && self.opened.elapsed().saturating_sub(alive) > STALL
98 }
99}
100
101const MEDIA_FOUNDATION: [&str; 3] = ["mf.dll", "mfplat.dll", "mfreadwrite.dll"];
102
103fn available() -> bool {
104 if !cfg!(windows) {
105 return true;
106 }
107 let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_string());
108 MEDIA_FOUNDATION.iter().all(|dll| {
109 std::path::Path::new(&system)
110 .join("System32")
111 .join(dll)
112 .exists()
113 })
114}
115
116pub fn devices() -> Vec<String> {
117 if std::env::var_os("YUMUSH_TEST_CAMERA").is_some() {
118 return vec!["Test camera".to_string()];
119 }
120 if !available() {
121 return Vec::new();
122 }
123 let mut names: Vec<String> = nodes().into_iter().map(|info| info.human_name()).collect();
124 names.dedup();
125 names
126}
127
128fn nodes() -> Vec<nokhwa::utils::CameraInfo> {
129 nokhwa::query(nokhwa::utils::ApiBackend::Auto)
130 .unwrap_or_default()
131 .into_iter()
132 .filter(|info| captures(info.index()))
133 .collect()
134}
135
136pub fn label(name: &str) -> &str {
137 match name.split_once(": ") {
138 Some((left, right)) if left == right => left,
139 _ => name,
140 }
141}
142
143fn index(device: Option<&str>) -> Option<CameraIndex> {
144 let nodes = nodes();
145 let index = nodes
146 .iter()
147 .find(|info| Some(info.human_name().as_str()) == device)
148 .or(nodes.first())
149 .map_or(CameraIndex::Index(0), |info| info.index().clone());
150 if held().contains(&index) {
151 tracing::warn!(?index, "camera still held by our capture thread");
152 return None;
153 }
154 let count = format_count(&index);
155 if count > MAX_FORMATS {
156 tracing::warn!(
157 ?index,
158 count,
159 "camera reports too many formats, device not ready"
160 );
161 return None;
162 }
163 Some(index)
164}
165
166#[cfg(target_os = "linux")]
167fn steps(min: u32, max: u32, step: u32) -> u64 {
168 u64::from(max.saturating_sub(min) / step.max(1)) + 1
169}
170
171#[cfg(target_os = "linux")]
172fn format_count(index: &CameraIndex) -> u64 {
173 use v4l::{frameinterval::FrameIntervalEnum, framesize::FrameSizeEnum, video::Capture};
174 let Some(device) = index
175 .as_index()
176 .ok()
177 .and_then(|number| v4l::Device::new(number as usize).ok())
178 else {
179 return 0;
180 };
181 let mut count = 0u64;
182 for format in device.enum_formats().unwrap_or_default() {
183 for size in device.enum_framesizes(format.fourcc).unwrap_or_default() {
184 let (sizes, width, height) = match size.size {
185 FrameSizeEnum::Discrete(size) => (1, size.width, size.height),
186 FrameSizeEnum::Stepwise(size) => (
187 steps(size.min_width, size.max_width, size.step_width).min(steps(
188 size.min_height,
189 size.max_height,
190 size.step_height,
191 )),
192 size.min_width,
193 size.min_height,
194 ),
195 };
196 let intervals: u64 = device
197 .enum_frameintervals(format.fourcc, width, height)
198 .unwrap_or_default()
199 .iter()
200 .map(|interval| match &interval.interval {
201 FrameIntervalEnum::Discrete(_) => 1,
202 FrameIntervalEnum::Stepwise(range) => steps(
203 range.min.numerator,
204 range.max.numerator,
205 range.step.numerator,
206 ),
207 })
208 .sum();
209 count = count.saturating_add(sizes.saturating_mul(intervals.max(1)));
210 }
211 }
212 count
213}
214
215#[cfg(target_os = "linux")]
216fn captures(index: &CameraIndex) -> bool {
217 index
218 .as_index()
219 .ok()
220 .and_then(|number| v4l::Device::new(number as usize).ok())
221 .and_then(|device| device.query_caps().ok())
222 .is_some_and(|caps| {
223 caps.capabilities
224 .contains(v4l::capability::Flags::VIDEO_CAPTURE)
225 })
226}
227
228#[cfg(not(target_os = "linux"))]
229fn captures(_: &CameraIndex) -> bool {
230 true
231}
232
233#[cfg(not(target_os = "linux"))]
234fn format_count(_: &CameraIndex) -> u64 {
235 0
236}
237
238pub fn open(top: Quality, device: Option<String>) -> Result<Camera, String> {
239 if let Ok(spec) = std::env::var("YUMUSH_TEST_CAMERA") {
240 let (width, height, refresh, frames, generator) = fake::start(&spec);
241 return Ok(Camera {
242 width,
243 height,
244 refresh,
245 size: (width, height),
246 modes: vec![(height, refresh)],
247 frames,
248 fps: Arc::new(AtomicU32::new(refresh)),
249 alive: Arc::new(AtomicU32::new(0)),
250 opened: Instant::now(),
251 stop: Arc::new(AtomicBool::new(false)),
252 thread: None,
253 _fake: Some(generator),
254 });
255 }
256 if !available() {
257 return Err(w().camera.needs_media_pack.to_string());
258 }
259 let index = index(device.as_deref()).ok_or_else(|| w().camera.no_response.to_string())?;
260 let hold = Hold::take(index.clone()).ok_or_else(|| w().camera.no_response.to_string())?;
261 let (negotiated_tx, negotiated_rx) = sync_channel::<Result<Negotiated, String>>(1);
262 let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE);
263 let stop = Arc::new(AtomicBool::new(false));
264 let fps = Arc::new(AtomicU32::new(u32::MAX));
265 let alive = Arc::new(AtomicU32::new(0));
266 let opened = Instant::now();
267 let (done_tx, done) = sync_channel::<()>(0);
268 let thread = {
269 let (stop, fps, alive) = (stop.clone(), fps.clone(), alive.clone());
270 std::thread::Builder::new()
271 .name("camera-capture".to_string())
272 .spawn(move || {
273 let _done = done_tx;
274 let _hold = hold;
275 let clock = Clock {
276 opened,
277 alive: &alive,
278 };
279 run(top, &index, &stop, &fps, &clock, negotiated_tx, frames_tx)
280 })
281 .map_err(|error| error.to_string())?
282 };
283 let negotiated = match negotiated_rx.recv_timeout(OPEN_TIMEOUT) {
284 Ok(negotiated) => negotiated,
285 Err(_) => {
286 stop.store(true, Ordering::Relaxed);
287 return Err(w().camera.no_response.to_string());
288 }
289 };
290 let (width, height, refresh, size, modes) = match negotiated {
291 Ok(negotiated) => negotiated,
292 Err(error) => {
293 let _ = thread.join();
294 return Err(error);
295 }
296 };
297 Ok(Camera {
298 width,
299 height,
300 refresh,
301 size,
302 modes,
303 frames: frames_rx,
304 fps,
305 alive,
306 opened,
307 stop,
308 thread: Some((thread, done)),
309 _fake: None,
310 })
311}
312
313pub fn list(device: Option<&str>) -> Vec<Mode> {
314 if let Ok(spec) = std::env::var("YUMUSH_TEST_CAMERA") {
315 return spec
316 .split_once('@')
317 .and_then(|(size, fps)| {
318 Some((size.split_once('x')?.1.parse().ok()?, fps.parse().ok()?))
319 })
320 .into_iter()
321 .collect();
322 }
323 if !available() {
324 return Vec::new();
325 }
326 let Some(index) = index(device) else {
327 return Vec::new();
328 };
329 let any = RequestedFormat::new::<RgbFormat>(RequestedFormatType::None);
330 Device::new(index, any)
331 .and_then(|mut camera| camera.compatible_camera_formats())
332 .map(|formats| modes(&decodable(formats)))
333 .unwrap_or_default()
334}
335
336fn decodable(formats: Vec<CameraFormat>) -> Vec<CameraFormat> {
337 formats
338 .into_iter()
339 .filter(|format| DECODABLE.contains(&format.format()))
340 .collect()
341}
342
343fn modes(formats: &[CameraFormat]) -> Vec<Mode> {
344 let mut modes: Vec<Mode> = formats
345 .iter()
346 .map(|format| (format.height(), format.frame_rate()))
347 .collect();
348 modes.sort_unstable();
349 modes.dedup();
350 modes
351}
352
353fn size(formats: &[CameraFormat]) -> Option<(u32, u32)> {
354 formats
355 .iter()
356 .map(|format| (format.width(), format.height()))
357 .max_by_key(|(width, height)| (*height, *width))
358}
359
360fn pick(formats: &[CameraFormat], top: Quality) -> Option<CameraFormat> {
361 let quality = clamp(top, &modes(formats), u32::MAX);
362 let height = quality.resolution.height();
363 let refresh = quality.fps.value();
364 formats.iter().copied().min_by_key(|format| {
365 (
366 format.height() < height,
367 std::cmp::Reverse(format.frame_rate().min(refresh)),
368 format.height(),
369 format.format() == FrameFormat::MJPEG,
370 format.frame_rate().abs_diff(refresh),
371 )
372 })
373}
374
375fn open_fitting(top: Quality, index: &CameraIndex) -> Option<(Device, Vec<CameraFormat>)> {
376 let any = RequestedFormat::new::<RgbFormat>(RequestedFormatType::None);
377 let mut camera = Device::new(index.clone(), any).ok()?;
378 let formats = decodable(camera.compatible_camera_formats().ok()?);
379 let chosen = pick(&formats, top)?;
380 let exact = RequestedFormat::new::<RgbFormat>(RequestedFormatType::Exact(chosen));
381 camera.set_camera_requset(exact).ok()?;
382 camera.open_stream().ok()?;
383 Some((camera, formats))
384}
385
386fn open_device(top: Quality, index: &CameraIndex) -> Result<(Device, Vec<CameraFormat>), String> {
387 if let Some(opened) = open_fitting(top, index) {
388 return Ok(opened);
389 }
390 for wanted in WANTED_FORMATS {
391 let requested = RequestedFormat::new::<RgbFormat>(wanted);
392 let opened = Device::new(index.clone(), requested).and_then(|mut camera| {
393 camera.open_stream()?;
394 Ok(camera)
395 });
396 match opened {
397 Ok(camera) => return Ok((camera, Vec::new())),
398 Err(error) => tracing::warn!(%error, "camera open failed"),
399 }
400 }
401 Err(w().camera.not_found.to_string())
402}
403
404struct Clock<'a> {
405 opened: Instant,
406 alive: &'a AtomicU32,
407}
408
409impl Clock<'_> {
410 fn beat(&self) {
411 let elapsed = u32::try_from(self.opened.elapsed().as_millis()).unwrap_or(u32::MAX);
412 self.alive.store(elapsed, Ordering::Relaxed);
413 }
414}
415
416fn run(
417 top: Quality,
418 index: &CameraIndex,
419 stop: &AtomicBool,
420 fps: &AtomicU32,
421 clock: &Clock,
422 negotiated: SyncSender<Result<Negotiated, String>>,
423 frames: SyncSender<Frame>,
424) {
425 let (mut camera, formats) = match open_device(top, index) {
426 Ok(opened) => opened,
427 Err(error) => {
428 let _ = negotiated.send(Err(error));
429 return;
430 }
431 };
432 let format = camera.camera_format();
433 let formats = if formats.is_empty() {
434 vec![format]
435 } else {
436 formats
437 };
438 tracing::info!(?format, "camera opened");
439 clock.beat();
440 let _ = negotiated.send(Ok((
441 format.width(),
442 format.height(),
443 format.frame_rate(),
444 size(&formats).unwrap_or((format.width(), format.height())),
445 modes(&formats),
446 )));
447 let started = Instant::now();
448 let mut failures = 0;
449 let mut due = 0u32;
450 while !stop.load(Ordering::Relaxed) {
451 crate::usage::tick(crate::usage::Group::Camera);
452 let buffer = match camera.frame() {
453 Ok(buffer) => buffer,
454 Err(error) => {
455 failures += 1;
456 if failures >= MAX_FAILURES {
457 tracing::warn!(%error, "camera lost");
458 break;
459 }
460 std::thread::sleep(RETRY_DELAY);
461 continue;
462 }
463 };
464 failures = 0;
465 clock.beat();
466 let timestamp_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
467 let wanted = fps.load(Ordering::Relaxed);
468 if wanted == 0 || timestamp_ms + SLACK_MS < due {
469 continue;
470 }
471 due = due.max(timestamp_ms.saturating_sub(SLACK_MS)) + 1000 / wanted;
472 let Some((width, height, bgra)) = to_bgra(&buffer) else {
473 continue;
474 };
475 let frame = Frame {
476 width,
477 height,
478 stride: width * BYTES_PER_PIXEL as u32,
479 timestamp_ms,
480 bgra,
481 gpu: None,
482 };
483 let _ = frames.try_send(frame);
484 }
485 let _ = camera.stop_stream();
486}
487
488fn to_bgra(buffer: &Buffer) -> Option<(u32, u32, Vec<u8>)> {
489 let resolution = buffer.resolution();
490 let (width, height) = (resolution.width(), resolution.height());
491 let data = buffer.buffer();
492 match buffer.source_frame_format() {
493 FrameFormat::YUYV => Some((width, height, pixel::yuyv_to_bgra(data, width, height)?)),
494 FrameFormat::NV12 => Some((width, height, pixel::nv12_to_bgra(data, width, height)?)),
495 FrameFormat::MJPEG => pixel::jpeg_to_bgra(data),
496 _ => None,
497 }
498}
499
500#[cfg(test)]
501mod tests {
502 use super::*;
503
504 #[cfg(target_os = "linux")]
505 #[test]
506 fn loopback_ranges_exceed_limit() {
507 let sizes = steps(2, 8192, 1).min(steps(1, 8192, 1));
508 let intervals = steps(1, i32::MAX as u32, 1);
509 assert!(sizes * intervals > MAX_FORMATS);
510 assert_eq!(steps(640, 640, 0), 1);
511 }
512}