BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / camera.rs

camera.rs

camera.rs 38.0 KiB Download Raw
1#[cfg(target_os = "linux")]
2use std::process::Command;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::{Duration, Instant};
6
7use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420, yuy2_to_i420};
8use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
9use nokhwa::pixel_format::RgbAFormat;
10use nokhwa::utils::{
11 ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType,
12 Resolution,
13};
14use nokhwa::{Camera, query};
15use zune_core::bytestream::ZCursor;
16use zune_core::colorspace::ColorSpace;
17use zune_core::options::DecoderOptions;
18use zune_jpeg::JpegDecoder;
19
20use crate::blur::BlurSettings;
21use crate::capture::Capture;
22use crate::devices::{DeviceChoice, DeviceEntry};
23use crate::effects::EffectsThread;
24use crate::error::{Error, Result};
25use crate::video_quality::VideoQuality;
26
27const RETRY_PAUSE: Duration = Duration::from_millis(20);
28const BYTES_PER_PIXEL: u32 = 4;
29const CAPTURE_FPS: u32 = 30;
30const ASPECT_WIDTH: u32 = 16;
31const ASPECT_HEIGHT: u32 = 9;
32const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
33const USABLE_FORMATS: [FrameFormat; 3] = [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct CameraDevice {
37 pub key: String,
38 pub name: String,
39}
40
41/// Shared capture counters for call-report stats (format + fps + decode time).
42#[derive(Debug, Default)]
43pub struct CameraCaptureStats {
44 format: std::sync::Mutex<String>,
45 started: std::sync::Mutex<Option<Instant>>,
46 frames: AtomicU64,
47 decode_ns: AtomicU64,
48}
49
50impl CameraCaptureStats {
51 pub fn new() -> Arc<Self> {
52 Arc::new(Self::default())
53 }
54
55 fn set_format(&self, label: impl Into<String>) {
56 if let Ok(mut slot) = self.format.lock() {
57 *slot = label.into();
58 }
59 if let Ok(mut started) = self.started.lock() {
60 *started = Some(Instant::now());
61 }
62 self.frames.store(0, Ordering::Relaxed);
63 self.decode_ns.store(0, Ordering::Relaxed);
64 }
65
66 fn note_frame(&self, decode: Duration) {
67 self.frames.fetch_add(1, Ordering::Relaxed);
68 self.decode_ns
69 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
70 }
71
72 pub fn format_label(&self) -> String {
73 self.format
74 .lock()
75 .map(|label| label.clone())
76 .unwrap_or_default()
77 }
78
79 pub fn summary(&self) -> Option<String> {
80 let label = self.format_label();
81 if label.is_empty() {
82 return None;
83 }
84 let frames = self.frames.load(Ordering::Relaxed);
85 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
86 let decode_ms = if frames == 0 {
87 0.0
88 } else {
89 (decode_ns as f64 / frames as f64) / 1_000_000.0
90 };
91 let fps = self
92 .started
93 .lock()
94 .ok()
95 .and_then(|started| *started)
96 .map(|started| {
97 let seconds = started.elapsed().as_secs_f64().max(0.001);
98 frames as f64 / seconds
99 })
100 .unwrap_or(0.0);
101 Some(format!(
102 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
103 ))
104 }
105}
106
107pub fn list_cameras() -> Vec<CameraDevice> {
108 query_camera_infos()
109 .into_iter()
110 .map(camera_device)
111 .collect()
112}
113
114fn camera_device(info: nokhwa::utils::CameraInfo) -> CameraDevice {
115 let fallback_key = match info.index() {
116 CameraIndex::Index(number) => number.to_string(),
117 CameraIndex::String(text) => text.clone(),
118 };
119 #[cfg(windows)]
120 let key = {
121 let misc = info.misc();
122 if misc.trim().is_empty() {
123 fallback_key
124 } else {
125 misc
126 }
127 };
128 #[cfg(not(windows))]
129 let key = fallback_key;
130 CameraDevice {
131 key,
132 name: info.human_name(),
133 }
134}
135
136fn query_camera_infos() -> Vec<nokhwa::utils::CameraInfo> {
137 let queried = query(ApiBackend::Auto).unwrap_or_default();
138 #[cfg(target_os = "linux")]
139 {
140 return queried.into_iter().filter(linux_keeps_camera).collect();
141 }
142 #[cfg(not(target_os = "linux"))]
143 queried
144}
145
146/// Keep a node unless we know it cannot capture video. Unknown stays listed.
147#[cfg(any(target_os = "linux", test))]
148fn keeps_when_capture_known(captures: Option<bool>) -> bool {
149 captures.unwrap_or(true)
150}
151
152#[cfg(any(target_os = "linux", test))]
153fn captures_from_querycap(capabilities: u32, device_caps: u32) -> bool {
154 const VIDEO_CAPTURE: u32 = 0x0000_0001;
155 const DEVICE_CAPS: u32 = 0x8000_0000;
156 let caps = if capabilities & DEVICE_CAPS != 0 {
157 device_caps
158 } else {
159 capabilities
160 };
161 caps & VIDEO_CAPTURE != 0
162}
163
164#[cfg(test)]
165fn first_listed_index(nodes: &[(u32, Option<bool>)]) -> u32 {
166 nodes
167 .iter()
168 .find(|(_, captures)| keeps_when_capture_known(*captures))
169 .map(|(index, _)| *index)
170 .unwrap_or(0)
171}
172
173#[cfg(target_os = "linux")]
174fn linux_keeps_camera(info: &nokhwa::utils::CameraInfo) -> bool {
175 let CameraIndex::Index(number) = info.index() else {
176 return true;
177 };
178 keeps_when_capture_known(node_captures_video(*number))
179}
180
181#[cfg(target_os = "linux")]
182fn node_captures_video(index: u32) -> Option<bool> {
183 let path = std::ffi::CString::new(format!("/dev/video{index}")).ok()?;
184 // QUERYCAP does not need write access. O_RDWR hides a metadata node the
185 // user can read but not write, and that node then stays in the list.
186 let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_NONBLOCK) };
187 if fd < 0 {
188 return None;
189 }
190 let mut caps = V4l2Capability::default();
191 let rc = unsafe { libc::ioctl(fd, V4L2_QUERYCAP, &mut caps) };
192 unsafe { libc::close(fd) };
193 if rc < 0 {
194 return None;
195 }
196 Some(captures_from_querycap(caps.capabilities, caps.device_caps))
197}
198
199#[cfg(target_os = "linux")]
200const V4L2_QUERYCAP: libc::c_ulong = 0x8068_5600;
201
202#[cfg(target_os = "linux")]
203#[repr(C)]
204#[derive(Default)]
205struct V4l2Capability {
206 driver: [u8; 16],
207 card: [u8; 32],
208 bus_info: [u8; 32],
209 version: u32,
210 capabilities: u32,
211 device_caps: u32,
212 reserved: [u32; 3],
213}
214
215fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {
216 #[cfg(windows)]
217 {
218 let queried = query(ApiBackend::Auto).unwrap_or_default();
219 match choice {
220 DeviceChoice::SystemDefault => {
221 let tune_target = queried
222 .first()
223 .map(|info| {
224 let misc = info.misc();
225 if misc.trim().is_empty() {
226 info.human_name()
227 } else {
228 misc
229 }
230 })
231 .unwrap_or_default();
232 let index = queried
233 .first()
234 .map_or(CameraIndex::Index(0), |info| info.index().clone());
235 return (index, tune_target);
236 }
237 DeviceChoice::Device(key) => {
238 if let Some(found) = queried.iter().find(|info| {
239 let misc = info.misc();
240 (!misc.is_empty() && misc.eq_ignore_ascii_case(key))
241 || info.human_name().eq_ignore_ascii_case(key)
242 }) {
243 let misc = found.misc();
244 let tune_target = if misc.trim().is_empty() {
245 found.human_name()
246 } else {
247 misc
248 };
249 return (found.index().clone(), tune_target);
250 }
251 // Backward compatibility for previously saved numeric indices ("0", "1").
252 if let Ok(number) = key.parse::<u32>() {
253 let tune_target = queried
254 .iter()
255 .find(|info| *info.index() == CameraIndex::Index(number))
256 .map(|info| {
257 let misc = info.misc();
258 if misc.trim().is_empty() {
259 info.human_name()
260 } else {
261 misc
262 }
263 })
264 .unwrap_or_default();
265 return (CameraIndex::Index(number), tune_target);
266 }
267 return (CameraIndex::String(key.clone()), key.clone());
268 }
269 }
270 }
271 #[cfg(not(windows))]
272 {
273 let index = match choice {
274 DeviceChoice::SystemDefault => query_camera_infos()
275 .first()
276 .map(|info| info.index().clone())
277 .unwrap_or(CameraIndex::Index(0)),
278 DeviceChoice::Device(key) => key
279 .parse()
280 .map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
281 };
282 (index, String::new())
283 }
284}
285
286pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
287 let mut buffer = I420Buffer::new(width, height);
288 let (stride_y, stride_u, stride_v) = buffer.strides();
289 let (plane_y, plane_u, plane_v) = buffer.data_mut();
290 abgr_to_i420(
291 rgba,
292 width * BYTES_PER_PIXEL,
293 plane_y,
294 stride_y,
295 plane_u,
296 stride_u,
297 plane_v,
298 stride_v,
299 width as i32,
300 height as i32,
301 );
302 buffer
303}
304
305fn format_rank(frame_format: FrameFormat) -> u8 {
306 match frame_format {
307 FrameFormat::NV12 => 3,
308 FrameFormat::YUYV => 2,
309 FrameFormat::MJPEG => 1,
310 _ => 0,
311 }
312}
313
314fn format_short_name(frame_format: FrameFormat) -> String {
315 match frame_format {
316 FrameFormat::MJPEG => "MJPG".into(),
317 FrameFormat::NV12 => "NV12".into(),
318 FrameFormat::YUYV => "YUYV".into(),
319 other => other.to_string(),
320 }
321}
322
323fn format_label(format: &CameraFormat) -> String {
324 format!(
325 "{} {}x{} @{}",
326 format_short_name(format.format()),
327 format.width(),
328 format.height(),
329 format.frame_rate()
330 )
331}
332
333fn is_widescreen(width: u32, height: u32) -> bool {
334 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
335}
336
337fn widescreen_tier(format: &CameraFormat, capture_height: u32) -> u8 {
338 match (
339 is_widescreen(format.width(), format.height()),
340 format.height(),
341 ) {
342 (true, height) if height == capture_height => 3,
343 (true, height) if height > capture_height => 2,
344 (true, _) => 1,
345 (false, _) => 0,
346 }
347}
348
349fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<CameraFormat> {
350 let capture_height = quality.capture_height();
351 let largest = quality.largest_sensor_height();
352 formats
353 .iter()
354 .copied()
355 .filter(|format| USABLE_FORMATS.contains(&format.format()))
356 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
357 .filter(|format| {
358 format.height() <= capture_height
359 || (is_widescreen(format.width(), format.height()) && format.height() <= largest)
360 })
361 .max_by_key(|format| {
362 (
363 widescreen_tier(format, capture_height),
364 std::cmp::Reverse(format.height().abs_diff(capture_height)),
365 format_rank(format.format()),
366 std::cmp::Reverse(format.frame_rate()),
367 )
368 })
369}
370
371fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
372 match quality {
373 VideoQuality::Auto | VideoQuality::P720 => vec![720, 540, 360],
374 VideoQuality::P1080 => vec![1080, 720, 540, 360],
375 }
376}
377
378fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
379 let mut candidates = Vec::new();
380 for height in candidate_heights(quality) {
381 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
382 candidates.push(CameraFormat::new(
383 Resolution::new(width, height),
384 FrameFormat::MJPEG,
385 CAPTURE_FPS,
386 ));
387 for frame_format in DIRECT_FORMATS {
388 candidates.push(CameraFormat::new(
389 Resolution::new(width, height),
390 frame_format,
391 CAPTURE_FPS,
392 ));
393 }
394 }
395 candidates
396}
397
398fn even(value: u32) -> u32 {
399 value & !1
400}
401
402fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32) -> I420Buffer {
403 let mut cropped = I420Buffer::new(width, height);
404 let (source_strides, source_planes) = (buffer.strides(), buffer.data());
405 let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut());
406 let planes = [
407 (
408 source_planes.0,
409 source_strides.0,
410 target_planes.0,
411 target_strides.0,
412 1,
413 ),
414 (
415 source_planes.1,
416 source_strides.1,
417 target_planes.1,
418 target_strides.1,
419 2,
420 ),
421 (
422 source_planes.2,
423 source_strides.2,
424 target_planes.2,
425 target_strides.2,
426 2,
427 ),
428 ];
429 for (source, source_stride, target, target_stride, divisor) in planes {
430 let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize);
431 let (plane_width, plane_height) = (
432 width.div_ceil(divisor) as usize,
433 height.div_ceil(divisor) as usize,
434 );
435 for row in 0..plane_height {
436 let from = (plane_top + row) * source_stride as usize + plane_left;
437 let to = row * target_stride as usize;
438 target[to..to + plane_width].copy_from_slice(&source[from..from + plane_width]);
439 }
440 }
441 cropped
442}
443
444pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I420Buffer {
445 let capture_height = quality.capture_height();
446 let (width, height) = (buffer.width(), buffer.height());
447 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
448 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
449 } else {
450 (width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH))
451 };
452 if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 {
453 buffer = crop_i420(
454 &buffer,
455 even((width - crop_width) / 2),
456 even((height - crop_height) / 2),
457 crop_width,
458 crop_height,
459 );
460 }
461 let (width, height) = (buffer.width(), buffer.height());
462 if height > capture_height {
463 let scaled_width = even(width * capture_height / height);
464 return buffer.scale(scaled_width as i32, capture_height as i32);
465 }
466 buffer
467}
468
469fn open_with_request(
470 index: CameraIndex,
471 request: RequestedFormatType,
472) -> std::result::Result<Camera, nokhwa::NokhwaError> {
473 let format = RequestedFormat::new::<RgbAFormat>(request);
474 let mut camera = Camera::new(index, format)?;
475 camera.open_stream()?;
476 Ok(camera)
477}
478
479#[cfg(target_os = "linux")]
480fn device_path(index: &CameraIndex) -> Option<String> {
481 match index {
482 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
483 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
484 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
485 Some(format!("/dev/video{text}"))
486 }
487 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
488 _ => None,
489 }
490}
491
492fn tune_uvc_controls(index: &CameraIndex, windows_target: &str) {
493 #[cfg(target_os = "linux")]
494 {
495 let _ = windows_target;
496 let Some(device) = device_path(index) else {
497 return;
498 };
499 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH/EU).
500 let _ = Command::new("v4l2-ctl")
501 .args([
502 "-d",
503 &device,
504 "-c",
505 "exposure_dynamic_framerate=0,power_line_frequency=1",
506 ])
507 .stdout(std::process::Stdio::null())
508 .stderr(std::process::Stdio::null())
509 .status();
510 }
511 #[cfg(windows)]
512 {
513 let _ = index;
514 // Best effort: 50 Hz anti-flicker & disable low-light FPS drop via DirectShow UVC KSPROPERTY.
515 webrtc_sys::webrtc::ffi::tune_windows_camera(windows_target);
516 }
517 #[cfg(not(any(target_os = "linux", windows)))]
518 {
519 let _ = (index, windows_target);
520 }
521}
522
523fn accept_opened(
524 index: &CameraIndex,
525 windows_target: &str,
526 mut camera: Camera,
527) -> Option<(Camera, String)> {
528 let got = camera.camera_format();
529 if got.frame_rate() < CAPTURE_FPS {
530 let _ = camera.stop_stream();
531 return None;
532 }
533 tune_uvc_controls(index, windows_target);
534 let label = format_label(&got);
535 Some((camera, label))
536}
537
538fn try_exact_or_closest(
539 index: CameraIndex,
540 format: CameraFormat,
541) -> std::result::Result<Camera, nokhwa::NokhwaError> {
542 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
543 Ok(camera) => Ok(camera),
544 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
545 }
546}
547
548fn open_from_list(
549 index: CameraIndex,
550 windows_target: &str,
551 quality: VideoQuality,
552 formats: &[CameraFormat],
553) -> Option<(Camera, String)> {
554 let Some(wanted) = pick_format(formats, quality) else {
555 return None;
556 };
557 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
558 accept_opened(&index, windows_target, camera)
559}
560
561fn open_picked_format(
562 index: CameraIndex,
563 windows_target: &str,
564 quality: VideoQuality,
565) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
566 let mut camera = Camera::new(
567 index.clone(),
568 RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),
569 )?;
570 let formats = camera.compatible_camera_formats()?;
571 let format = pick_format(&formats, quality).ok_or_else(|| {
572 nokhwa::NokhwaError::GeneralError("no camera format at 30 fps".to_owned())
573 })?;
574 camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(
575 RequestedFormatType::Exact(format),
576 ))?;
577 camera.open_stream()?;
578 tune_uvc_controls(&index, windows_target);
579 Ok((camera, format_label(&format)))
580}
581
582fn open_camera(
583 index: CameraIndex,
584 windows_target: &str,
585 quality: VideoQuality,
586) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
587 if cfg!(windows)
588 && let Ok(opened) = open_picked_format(index.clone(), windows_target, quality)
589 {
590 return Ok(opened);
591 }
592 // Probe the device list without committing to a slow Closest(NV12) open.
593 for probe in preferred_candidates(quality) {
594 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
595 continue;
596 };
597 if let Ok(formats) = camera.compatible_camera_formats() {
598 let _ = camera.stop_stream();
599 drop(camera);
600 if let Some(opened) = open_from_list(index.clone(), windows_target, quality, &formats) {
601 return Ok(opened);
602 }
603 } else if let Some(opened) = accept_opened(&index, windows_target, camera) {
604 return Ok(opened);
605 }
606 }
607
608 let mut last_error = None;
609 for candidate in preferred_candidates(quality) {
610 match try_exact_or_closest(index.clone(), candidate) {
611 Ok(camera) => {
612 if let Some(opened) = accept_opened(&index, windows_target, camera) {
613 return Ok(opened);
614 }
615 }
616 Err(error) => last_error = Some(error),
617 }
618 }
619
620 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
621 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
622 Ok(camera) => {
623 tune_uvc_controls(&index, windows_target);
624 let label = format_label(&camera.camera_format());
625 Ok((camera, label))
626 }
627 Err(error) => Err(last_error.unwrap_or(error)),
628 }
629}
630
631pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
632 let luma_len = width as usize * height as usize;
633 if data.len() < luma_len + luma_len / 2 {
634 return None;
635 }
636 let mut buffer = I420Buffer::new(width, height);
637 let (stride_y, stride_u, stride_v) = buffer.strides();
638 let (plane_y, plane_u, plane_v) = buffer.data_mut();
639 let (source_y, source_uv) = data.split_at(luma_len);
640 nv12_to_i420(
641 source_y,
642 width,
643 source_uv,
644 width,
645 plane_y,
646 stride_y,
647 plane_u,
648 stride_u,
649 plane_v,
650 stride_v,
651 width as i32,
652 height as i32,
653 );
654 Some(buffer)
655}
656
657pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
658 let row_bytes = width as usize * 2;
659 if data.len() < row_bytes * height as usize {
660 return None;
661 }
662 let mut buffer = I420Buffer::new(width, height);
663 let (stride_y, stride_u, stride_v) = buffer.strides();
664 let (plane_y, plane_u, plane_v) = buffer.data_mut();
665 yuy2_to_i420(
666 data,
667 row_bytes as u32,
668 plane_y,
669 stride_y,
670 plane_u,
671 stride_u,
672 plane_v,
673 stride_v,
674 width as i32,
675 height as i32,
676 );
677 Some(buffer)
678}
679
680fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
681 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
682 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
683 let pixels = decoder.decode().ok()?;
684 let info = decoder.info()?;
685 let (width, height) = (u32::from(info.width), u32::from(info.height));
686 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
687 return None;
688 }
689 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
690 let rgba = if pixels.len() == rgba_len {
691 pixels.as_slice()
692 } else if pixels.len() == (width * height * 3) as usize {
693 rgba_scratch.clear();
694 rgba_scratch.reserve(rgba_len);
695 for chunk in pixels.chunks_exact(3) {
696 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
697 }
698 rgba_scratch.as_slice()
699 } else {
700 return None;
701 };
702 Some((i420_from_rgba(rgba, width, height), width, height))
703}
704
705fn direct_i420(
706 frame_format: FrameFormat,
707 data: &[u8],
708 width: u32,
709 height: u32,
710 rgba_scratch: &mut Vec<u8>,
711) -> Option<I420Buffer> {
712 match frame_format {
713 FrameFormat::NV12 => i420_from_nv12(data, width, height),
714 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
715 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
716 _ => None,
717 }
718}
719
720pub fn start_camera(
721 choice: &DeviceChoice,
722 quality: VideoQuality,
723 blur: Arc<BlurSettings>,
724 stats: Arc<CameraCaptureStats>,
725 on_opened: impl FnOnce(String) + Send + 'static,
726 deliver: impl FnMut(I420Buffer) + Send + 'static,
727 failed: impl FnOnce(String) + Send + 'static,
728) -> Result<Capture> {
729 let (index, windows_target) = resolve_camera(choice);
730 Capture::spawn_thread("camera", move |stop| {
731 let (mut camera, label) = match open_camera(index, &windows_target, quality) {
732 Ok(opened) => opened,
733 Err(error) => return failed(error.to_string()),
734 };
735 stats.set_format(&label);
736 on_opened(label);
737 let effects = match EffectsThread::spawn(blur, deliver) {
738 Ok(effects) => effects,
739 Err(error) => return failed(format!("effects thread: {error}")),
740 };
741 let mut warned_undecodable = false;
742 let mut rgba_scratch = Vec::new();
743 while !stop.load(Ordering::SeqCst) {
744 let Ok(frame) = camera.frame() else {
745 std::thread::sleep(RETRY_PAUSE);
746 continue;
747 };
748 let resolution = frame.resolution();
749 let (width, height) = (resolution.width(), resolution.height());
750 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
751 continue;
752 }
753 let started = Instant::now();
754 let buffer = match direct_i420(
755 frame.source_frame_format(),
756 frame.buffer(),
757 width,
758 height,
759 &mut rgba_scratch,
760 ) {
761 Some(buffer) => buffer,
762 None => {
763 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
764 if !std::mem::replace(&mut warned_undecodable, true) {
765 eprintln!(
766 "calls: camera delivers {} and no decoder is available",
767 frame.source_frame_format()
768 );
769 }
770 continue;
771 };
772 i420_from_rgba(&decoded.into_raw(), width, height)
773 }
774 };
775 stats.note_frame(started.elapsed());
776 effects.submit(fit_widescreen(buffer, quality));
777 }
778 let _ = camera.stop_stream();
779 })
780 .map_err(|error| Error::Webrtc(format!("camera thread: {error}")))
781}
782
783pub const DEFAULT_CAMERA_LABEL: &str = "Default camera";
784
785pub fn camera_entries(cameras: &[CameraDevice]) -> Vec<DeviceEntry> {
786 let default_entry = DeviceEntry {
787 choice: DeviceChoice::SystemDefault,
788 label: DEFAULT_CAMERA_LABEL.to_owned(),
789 };
790 let named = cameras
791 .iter()
792 .filter(|camera| !camera.name.trim().is_empty())
793 .map(|camera| DeviceEntry {
794 choice: DeviceChoice::Device(camera.key.clone()),
795 label: camera.name.clone(),
796 });
797 std::iter::once(default_entry).chain(named).collect()
798}
799
800#[cfg(test)]
801mod tests {
802 use super::*;
803
804 #[test]
805 fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() {
806 let cameras = [
807 CameraDevice {
808 key: "0".into(),
809 name: "Integrated Camera".into(),
810 },
811 CameraDevice {
812 key: "1".into(),
813 name: " ".into(),
814 },
815 ];
816 let entries = camera_entries(&cameras);
817 assert_eq!(entries.len(), 2);
818 assert_eq!(entries[0].choice, DeviceChoice::SystemDefault);
819 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
820 }
821
822 #[test]
823 fn linux_metadata_node_is_dropped_and_same_name_capture_stays() {
824 let devices = [
825 CameraDevice {
826 key: "0".into(),
827 name: "Logitech Webcam C930e".into(),
828 },
829 CameraDevice {
830 key: "1".into(),
831 name: "Logitech Webcam C930e".into(),
832 },
833 ];
834 let caps = [
835 Some(captures_from_querycap(0x84a0_0001, 0x0420_0001)),
836 Some(captures_from_querycap(0x84a0_0001, 0x04a0_0000)),
837 ];
838 let listed: Vec<_> = devices
839 .into_iter()
840 .zip(caps)
841 .filter(|(_, captures)| keeps_when_capture_known(*captures))
842 .map(|(device, _)| device)
843 .collect();
844 assert_eq!(listed.len(), 1);
845 assert_eq!(listed[0].key, "0");
846 assert_eq!(listed[0].name, "Logitech Webcam C930e");
847 assert!(keeps_when_capture_known(None));
848 }
849
850 #[test]
851 fn system_default_uses_the_first_remaining_capture_node() {
852 assert_eq!(first_listed_index(&[(0, Some(false)), (1, Some(true))]), 1);
853 let (index, _) = resolve_camera(&DeviceChoice::SystemDefault);
854 let expected = list_cameras()
855 .first()
856 .map(|camera| {
857 camera.key.parse().map_or_else(
858 |_| CameraIndex::String(camera.key.clone()),
859 CameraIndex::Index,
860 )
861 })
862 .unwrap_or(CameraIndex::Index(0));
863 assert_eq!(index, expected);
864 }
865
866 #[cfg(target_os = "linux")]
867 #[test]
868 fn this_machine_lists_one_c930e_capture_node() {
869 let logitech: Vec<_> = list_cameras()
870 .into_iter()
871 .filter(|camera| camera.name.contains("C930e"))
872 .collect();
873 if logitech.is_empty() {
874 return;
875 }
876 assert_eq!(logitech.len(), 1);
877 assert_eq!(logitech[0].key, "0");
878 }
879
880 #[test]
881 fn yuyv_converts_to_i420_with_averaged_chroma() {
882 let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60];
883 let row_b = [11u8, 120, 21, 220, 31, 70, 41, 80];
884 let data: Vec<u8> = row_a.iter().chain(row_b.iter()).copied().collect();
885 let mut buffer = i420_from_yuyv(&data, 4, 2).expect("converted");
886 let (plane_y, plane_u, plane_v) = buffer.data_mut();
887 assert_eq!(&plane_y[..4], &[10, 20, 30, 40]);
888 assert_eq!(plane_u[0], 110);
889 assert_eq!(plane_u[1], 60);
890 assert_eq!(plane_v[0], 210);
891 assert_eq!(plane_v[1], 70);
892 }
893
894 #[test]
895 fn short_raw_frames_are_rejected() {
896 assert!(i420_from_yuyv(&[0; 8], 4, 2).is_none());
897 assert!(i420_from_nv12(&[0; 8], 4, 2).is_none());
898 }
899
900 fn format(width: u32, height: u32, frame_format: FrameFormat, fps: u32) -> CameraFormat {
901 CameraFormat::new(Resolution::new(width, height), frame_format, fps)
902 }
903
904 #[test]
905 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
906 let formats = [
907 format(1280, 720, FrameFormat::YUYV, 10),
908 format(640, 480, FrameFormat::YUYV, 30),
909 format(1280, 720, FrameFormat::MJPEG, 30),
910 ];
911 assert_eq!(
912 pick_format(&formats, VideoQuality::P720),
913 Some(format(1280, 720, FrameFormat::MJPEG, 30))
914 );
915 }
916
917 #[test]
918 fn raw_at_the_same_height_beats_mjpeg() {
919 let formats = [
920 format(1280, 720, FrameFormat::MJPEG, 30),
921 format(1280, 720, FrameFormat::NV12, 30),
922 ];
923 assert_eq!(
924 pick_format(&formats, VideoQuality::P720),
925 Some(format(1280, 720, FrameFormat::NV12, 30))
926 );
927 }
928
929 #[test]
930 fn a_c930e_like_list_picks_mjpeg_720_for_auto() {
931 let formats = [
932 format(1920, 1080, FrameFormat::YUYV, 5),
933 format(1280, 720, FrameFormat::YUYV, 10),
934 format(640, 360, FrameFormat::YUYV, 30),
935 format(1920, 1080, FrameFormat::MJPEG, 30),
936 format(1280, 720, FrameFormat::MJPEG, 30),
937 format(960, 540, FrameFormat::MJPEG, 30),
938 ];
939 assert_eq!(
940 pick_format(&formats, VideoQuality::Auto),
941 Some(format(1280, 720, FrameFormat::MJPEG, 30))
942 );
943 assert_eq!(
944 pick_format(&formats, VideoQuality::P720),
945 Some(format(1280, 720, FrameFormat::MJPEG, 30))
946 );
947 assert_eq!(
948 pick_format(&formats, VideoQuality::P1080),
949 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
950 );
951 }
952
953 #[test]
954 fn auto_prefers_720p_nv12_over_1080p() {
955 let formats = [
956 format(1920, 1080, FrameFormat::NV12, 30),
957 format(640, 480, FrameFormat::NV12, 30),
958 format(1280, 720, FrameFormat::YUYV, 30),
959 format(1280, 720, FrameFormat::NV12, 30),
960 ];
961 assert_eq!(
962 pick_format(&formats, VideoQuality::Auto),
963 Some(format(1280, 720, FrameFormat::NV12, 30))
964 );
965 assert_eq!(
966 pick_format(&formats, VideoQuality::P720),
967 Some(format(1280, 720, FrameFormat::NV12, 30))
968 );
969 }
970
971 #[test]
972 fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() {
973 let formats = [
974 format(960, 720, FrameFormat::NV12, 30),
975 format(1280, 720, FrameFormat::YUYV, 30),
976 format(640, 480, FrameFormat::NV12, 30),
977 ];
978 assert_eq!(
979 pick_format(&formats, VideoQuality::P720),
980 Some(format(1280, 720, FrameFormat::YUYV, 30))
981 );
982 }
983
984 #[test]
985 fn locked_720_keeps_1080_as_downscale_candidate_but_prefers_exact_720() {
986 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
987 let hd = format(1280, 720, FrameFormat::NV12, 30);
988 let small = format(640, 360, FrameFormat::NV12, 30);
989 let classic = format(960, 720, FrameFormat::NV12, 30);
990 assert_eq!(
991 pick_format(&[classic, small, full_hd], VideoQuality::Auto),
992 Some(full_hd)
993 );
994 assert_eq!(
995 pick_format(&[classic, small, full_hd, hd], VideoQuality::P720),
996 Some(hd)
997 );
998 assert_eq!(
999 pick_format(
1000 &[classic, format(2560, 1440, FrameFormat::NV12, 30)],
1001 VideoQuality::P720
1002 ),
1003 Some(classic)
1004 );
1005 }
1006
1007 fn gradient(width: u32, height: u32) -> I420Buffer {
1008 let mut buffer = I420Buffer::new(width, height);
1009 let (stride_y, stride_u, _) = buffer.strides();
1010 let (plane_y, plane_u, _) = buffer.data_mut();
1011 for row in 0..height as usize {
1012 plane_y[row * stride_y as usize..][..width as usize].fill(row as u8);
1013 }
1014 for row in 0..height.div_ceil(2) as usize {
1015 plane_u[row * stride_u as usize..][..width.div_ceil(2) as usize].fill(row as u8);
1016 }
1017 buffer
1018 }
1019
1020 #[test]
1021 fn a_4_3_frame_is_centre_cropped_to_16_9() {
1022 let cropped = fit_widescreen(gradient(960, 720), VideoQuality::P720);
1023 assert_eq!((cropped.width(), cropped.height()), (960, 540));
1024 let (stride_y, stride_u, _) = cropped.strides();
1025 let (plane_y, plane_u, _) = cropped.data();
1026 assert_eq!(plane_y[0], 90);
1027 assert_eq!(plane_y[539 * stride_y as usize], 629_u32 as u8);
1028 assert_eq!(plane_u[0], 45);
1029 assert_eq!(plane_u[269 * stride_u as usize], 314_u32 as u8);
1030 }
1031
1032 #[test]
1033 fn auto_and_720_scale_1080_down_while_1080_lock_keeps_it() {
1034 assert_eq!(
1035 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
1036 1280
1037 );
1038 let auto = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
1039 assert_eq!((auto.width(), auto.height()), (1280, 720));
1040 let locked = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
1041 assert_eq!((locked.width(), locked.height()), (1280, 720));
1042 let full = fit_widescreen(gradient(1920, 1080), VideoQuality::P1080);
1043 assert_eq!((full.width(), full.height()), (1920, 1080));
1044 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
1045 assert_eq!((wide.width(), wide.height()), (1280, 720));
1046 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
1047 assert_eq!((classic.width(), classic.height()), (640, 360));
1048 }
1049
1050 #[test]
1051 fn no_usable_format_picks_nothing() {
1052 let formats = [
1053 format(1280, 720, FrameFormat::MJPEG, 15),
1054 format(1280, 720, FrameFormat::YUYV, 15),
1055 ];
1056 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
1057 assert_eq!(pick_format(&[], VideoQuality::Auto), None);
1058 }
1059
1060 #[test]
1061 fn camera_choices_map_to_indices_or_names() {
1062 assert!(matches!(
1063 resolve_camera(&DeviceChoice::SystemDefault).0,
1064 CameraIndex::Index(_)
1065 ));
1066 assert!(matches!(
1067 resolve_camera(&DeviceChoice::Device("2".into())).0,
1068 CameraIndex::Index(2)
1069 ));
1070 assert!(matches!(
1071 resolve_camera(&DeviceChoice::Device("video0".into())).0,
1072 CameraIndex::String(_)
1073 ));
1074 }
1075
1076 #[test]
1077 fn mjpeg_decodes_to_i420() {
1078 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
1079 let mut rgb = image::RgbImage::new(16, 16);
1080 for pixel in rgb.pixels_mut() {
1081 *pixel = image::Rgb([40, 80, 120]);
1082 }
1083 let mut jpeg = Vec::new();
1084 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
1085 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
1086 .expect("encode");
1087 let mut scratch = Vec::new();
1088 let (buffer, width, height) = i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
1089 assert_eq!((width, height), (16, 16));
1090 assert_eq!((buffer.width(), buffer.height()), (16, 16));
1091 }
1092
1093 #[test]
1094 #[ignore = "timing; run with --release --ignored"]
1095 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
1096 let mut rgb = image::RgbImage::new(1920, 1080);
1097 for (index, pixel) in rgb.pixels_mut().enumerate() {
1098 let value = (index % 255) as u8;
1099 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
1100 }
1101 let mut jpeg = Vec::new();
1102 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
1103 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
1104 .expect("encode");
1105 let mut scratch = Vec::new();
1106 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
1107 for _ in 0..3 {
1108 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
1109 }
1110 let started = Instant::now();
1111 for _ in 0..10 {
1112 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
1113 }
1114 let average = started.elapsed() / 10;
1115 assert!(
1116 average < Duration::from_millis(20),
1117 "average decode {average:?} exceeds 20 ms"
1118 );
1119 }
1120
1121 #[test]
1122 #[ignore = "needs a connected camera"]
1123 fn open_picks_at_least_thirty_fps_when_available() {
1124 if list_cameras().is_empty() {
1125 return;
1126 }
1127 let (mut camera, label) =
1128 open_camera(CameraIndex::Index(0), "", VideoQuality::Auto).expect("camera opens");
1129 assert!(
1130 camera.camera_format().frame_rate() >= CAPTURE_FPS,
1131 "opened {label} under 30 fps"
1132 );
1133 // Warm up buffers, then count for one second.
1134 for _ in 0..10 {
1135 let _ = camera.frame();
1136 }
1137 let deadline = Instant::now() + Duration::from_secs(1);
1138 let mut frames = 0u32;
1139 while Instant::now() < deadline {
1140 if camera.frame().is_ok() {
1141 frames += 1;
1142 }
1143 }
1144 let _ = camera.stop_stream();
1145 assert!(
1146 frames >= 20,
1147 "expected >= 20 frames in 1 s from {label}, got {frames}"
1148 );
1149 }
1150}