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