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