| 1 | use std::sync::Arc; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420}; |
| 5 | use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _}; |
| 6 | use nokhwa::pixel_format::RgbAFormat; |
| 7 | use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution}; |
| 8 | use nokhwa::{Camera, query}; |
| 9 | use std::sync::atomic::Ordering; |
| 10 | |
| 11 | use crate::blur::BlurSettings; |
| 12 | use crate::effects::EffectsStage; |
| 13 | use crate::capture::Capture; |
| 14 | use crate::devices::{DeviceChoice, DeviceEntry}; |
| 15 | use crate::error::{Error, Result}; |
| 16 | |
| 17 | const RETRY_PAUSE: Duration = Duration::from_millis(20); |
| 18 | const BYTES_PER_PIXEL: u32 = 4; |
| 19 | const CAPTURE_WIDTH: u32 = 1280; |
| 20 | const CAPTURE_HEIGHT: u32 = 720; |
| 21 | const CAPTURE_FPS: u32 = 30; |
| 22 | const LARGEST_DOWNSCALED_HEIGHT: u32 = 1080; |
| 23 | const ASPECT_WIDTH: u32 = 16; |
| 24 | const ASPECT_HEIGHT: u32 = 9; |
| 25 | const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV]; |
| 26 | |
| 27 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 28 | pub struct CameraDevice { |
| 29 | pub key: String, |
| 30 | pub name: String, |
| 31 | } |
| 32 | |
| 33 | pub fn list_cameras() -> Vec<CameraDevice> { |
| 34 | query(ApiBackend::Auto) |
| 35 | .unwrap_or_default() |
| 36 | .into_iter() |
| 37 | .map(|info| CameraDevice { |
| 38 | key: match info.index() { |
| 39 | CameraIndex::Index(number) => number.to_string(), |
| 40 | CameraIndex::String(text) => text.clone(), |
| 41 | }, |
| 42 | name: info.human_name(), |
| 43 | }) |
| 44 | .collect() |
| 45 | } |
| 46 | |
| 47 | fn camera_index(choice: &DeviceChoice) -> CameraIndex { |
| 48 | match choice { |
| 49 | DeviceChoice::SystemDefault => CameraIndex::Index(0), |
| 50 | DeviceChoice::Device(key) => key.parse().map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer { |
| 55 | let mut buffer = I420Buffer::new(width, height); |
| 56 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 57 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 58 | abgr_to_i420( |
| 59 | rgba, |
| 60 | width * BYTES_PER_PIXEL, |
| 61 | plane_y, |
| 62 | stride_y, |
| 63 | plane_u, |
| 64 | stride_u, |
| 65 | plane_v, |
| 66 | stride_v, |
| 67 | width as i32, |
| 68 | height as i32, |
| 69 | ); |
| 70 | buffer |
| 71 | } |
| 72 | |
| 73 | fn format_rank(frame_format: FrameFormat) -> u8 { |
| 74 | match frame_format { |
| 75 | FrameFormat::NV12 => 1, |
| 76 | _ => 0, |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | fn is_widescreen(width: u32, height: u32) -> bool { |
| 81 | width * ASPECT_HEIGHT == height * ASPECT_WIDTH |
| 82 | } |
| 83 | |
| 84 | fn widescreen_tier(format: &CameraFormat) -> u8 { |
| 85 | match (is_widescreen(format.width(), format.height()), format.height()) { |
| 86 | (true, CAPTURE_HEIGHT) => 3, |
| 87 | (true, height) if height > CAPTURE_HEIGHT => 2, |
| 88 | (true, _) => 1, |
| 89 | (false, _) => 0, |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> { |
| 94 | formats |
| 95 | .iter() |
| 96 | .copied() |
| 97 | .filter(|format| DIRECT_FORMATS.contains(&format.format())) |
| 98 | .filter(|format| format.frame_rate() >= CAPTURE_FPS) |
| 99 | .filter(|format| { |
| 100 | format.height() <= CAPTURE_HEIGHT |
| 101 | || (is_widescreen(format.width(), format.height()) && format.height() <= LARGEST_DOWNSCALED_HEIGHT) |
| 102 | }) |
| 103 | .max_by_key(|format| { |
| 104 | ( |
| 105 | widescreen_tier(format), |
| 106 | std::cmp::Reverse(format.height().abs_diff(CAPTURE_HEIGHT)), |
| 107 | format_rank(format.format()), |
| 108 | std::cmp::Reverse(format.frame_rate()), |
| 109 | ) |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | fn even(value: u32) -> u32 { |
| 114 | value & !1 |
| 115 | } |
| 116 | |
| 117 | fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32) -> I420Buffer { |
| 118 | let mut cropped = I420Buffer::new(width, height); |
| 119 | let (source_strides, source_planes) = (buffer.strides(), buffer.data()); |
| 120 | let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut()); |
| 121 | let planes = [ |
| 122 | (source_planes.0, source_strides.0, target_planes.0, target_strides.0, 1), |
| 123 | (source_planes.1, source_strides.1, target_planes.1, target_strides.1, 2), |
| 124 | (source_planes.2, source_strides.2, target_planes.2, target_strides.2, 2), |
| 125 | ]; |
| 126 | for (source, source_stride, target, target_stride, divisor) in planes { |
| 127 | let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize); |
| 128 | let (plane_width, plane_height) = (width.div_ceil(divisor) as usize, height.div_ceil(divisor) as usize); |
| 129 | for row in 0..plane_height { |
| 130 | let from = (plane_top + row) * source_stride as usize + plane_left; |
| 131 | let to = row * target_stride as usize; |
| 132 | target[to..to + plane_width].copy_from_slice(&source[from..from + plane_width]); |
| 133 | } |
| 134 | } |
| 135 | cropped |
| 136 | } |
| 137 | |
| 138 | pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer { |
| 139 | let (width, height) = (buffer.width(), buffer.height()); |
| 140 | let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH { |
| 141 | (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height) |
| 142 | } else { |
| 143 | (width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH)) |
| 144 | }; |
| 145 | if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 { |
| 146 | buffer = crop_i420(&buffer, even((width - crop_width) / 2), even((height - crop_height) / 2), crop_width, crop_height); |
| 147 | } |
| 148 | let (width, height) = (buffer.width(), buffer.height()); |
| 149 | if height > CAPTURE_HEIGHT { |
| 150 | let scaled_width = even(width * CAPTURE_HEIGHT / height); |
| 151 | return buffer.scale(scaled_width as i32, CAPTURE_HEIGHT as i32); |
| 152 | } |
| 153 | buffer |
| 154 | } |
| 155 | |
| 156 | fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> { |
| 157 | let mut camera = Camera::new(index, RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate))?; |
| 158 | let formats = camera.compatible_camera_formats()?; |
| 159 | let format = pick_format(&formats).ok_or_else(|| nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned()))?; |
| 160 | camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(RequestedFormatType::Exact(format)))?; |
| 161 | camera.open_stream()?; |
| 162 | Ok(camera) |
| 163 | } |
| 164 | |
| 165 | fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> { |
| 166 | if let Ok(camera) = open_picked_format(index.clone()) { |
| 167 | return Ok(camera); |
| 168 | } |
| 169 | let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT); |
| 170 | let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS |
| 171 | .into_iter() |
| 172 | .map(|frame_format| RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS))) |
| 173 | .collect(); |
| 174 | requests.push(RequestedFormatType::AbsoluteHighestFrameRate); |
| 175 | let mut last_error = None; |
| 176 | for request in requests { |
| 177 | let format = RequestedFormat::new::<RgbAFormat>(request); |
| 178 | match Camera::new(index.clone(), format).and_then(|mut camera| camera.open_stream().map(|()| camera)) { |
| 179 | Ok(camera) => return Ok(camera), |
| 180 | Err(error) => last_error = Some(error), |
| 181 | } |
| 182 | } |
| 183 | Err(last_error.expect("at least one request")) |
| 184 | } |
| 185 | |
| 186 | pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> { |
| 187 | let luma_len = width as usize * height as usize; |
| 188 | if data.len() < luma_len + luma_len / 2 { |
| 189 | return None; |
| 190 | } |
| 191 | let mut buffer = I420Buffer::new(width, height); |
| 192 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 193 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 194 | let (source_y, source_uv) = data.split_at(luma_len); |
| 195 | nv12_to_i420(source_y, width, source_uv, width, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32); |
| 196 | Some(buffer) |
| 197 | } |
| 198 | |
| 199 | pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> { |
| 200 | let (width_pixels, height_rows) = (width as usize, height as usize); |
| 201 | let row_bytes = width_pixels * 2; |
| 202 | if data.len() < row_bytes * height_rows { |
| 203 | return None; |
| 204 | } |
| 205 | let mut buffer = I420Buffer::new(width, height); |
| 206 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 207 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 208 | for row in 0..height_rows { |
| 209 | let source = &data[row * row_bytes..(row + 1) * row_bytes]; |
| 210 | let luma_row = &mut plane_y[row * stride_y as usize..][..width_pixels]; |
| 211 | for (luma, pair) in luma_row.chunks_exact_mut(2).zip(source.chunks_exact(4)) { |
| 212 | luma[0] = pair[0]; |
| 213 | luma[1] = pair[2]; |
| 214 | } |
| 215 | } |
| 216 | for row in 0..height_rows / 2 { |
| 217 | let upper = &data[row * 2 * row_bytes..][..row_bytes]; |
| 218 | let lower = &data[(row * 2 + 1) * row_bytes..][..row_bytes]; |
| 219 | let blue_row = &mut plane_u[row * stride_u as usize..][..width_pixels / 2]; |
| 220 | let red_row = &mut plane_v[row * stride_v as usize..][..width_pixels / 2]; |
| 221 | for (column, (blue, red)) in blue_row.iter_mut().zip(red_row.iter_mut()).enumerate() { |
| 222 | let offset = column * 4; |
| 223 | *blue = ((u16::from(upper[offset + 1]) + u16::from(lower[offset + 1]) + 1) / 2) as u8; |
| 224 | *red = ((u16::from(upper[offset + 3]) + u16::from(lower[offset + 3]) + 1) / 2) as u8; |
| 225 | } |
| 226 | } |
| 227 | Some(buffer) |
| 228 | } |
| 229 | |
| 230 | fn direct_i420(frame_format: FrameFormat, data: &[u8], width: u32, height: u32) -> Option<I420Buffer> { |
| 231 | match frame_format { |
| 232 | FrameFormat::NV12 => i420_from_nv12(data, width, height), |
| 233 | FrameFormat::YUYV => i420_from_yuyv(data, width, height), |
| 234 | _ => None, |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | pub fn start_camera( |
| 239 | choice: &DeviceChoice, |
| 240 | blur: Arc<BlurSettings>, |
| 241 | mut deliver: impl FnMut(I420Buffer) + Send + 'static, |
| 242 | failed: impl FnOnce(String) + Send + 'static, |
| 243 | ) -> Result<Capture> { |
| 244 | let index = camera_index(choice); |
| 245 | Capture::spawn_thread("camera", move |stop| { |
| 246 | let mut camera = match open_camera(index) { |
| 247 | Ok(camera) => camera, |
| 248 | Err(error) => return failed(error.to_string()), |
| 249 | }; |
| 250 | let mut stage = EffectsStage::new(blur); |
| 251 | let mut warned_undecodable = false; |
| 252 | while !stop.load(Ordering::SeqCst) { |
| 253 | let Ok(frame) = camera.frame() else { |
| 254 | std::thread::sleep(RETRY_PAUSE); |
| 255 | continue; |
| 256 | }; |
| 257 | let resolution = frame.resolution(); |
| 258 | let (width, height) = (resolution.width(), resolution.height()); |
| 259 | if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 { |
| 260 | continue; |
| 261 | } |
| 262 | let buffer = match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) { |
| 263 | Some(buffer) => buffer, |
| 264 | None => { |
| 265 | let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { |
| 266 | if !std::mem::replace(&mut warned_undecodable, true) { |
| 267 | eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format()); |
| 268 | } |
| 269 | continue; |
| 270 | }; |
| 271 | i420_from_rgba(&decoded.into_raw(), width, height) |
| 272 | } |
| 273 | }; |
| 274 | deliver(stage.apply_i420(fit_widescreen(buffer))); |
| 275 | } |
| 276 | let _ = camera.stop_stream(); |
| 277 | }) |
| 278 | .map_err(|error| Error::Webrtc(format!("camera thread: {error}"))) |
| 279 | } |
| 280 | |
| 281 | pub const DEFAULT_CAMERA_LABEL: &str = "Default camera"; |
| 282 | |
| 283 | pub fn camera_entries(cameras: &[CameraDevice]) -> Vec<DeviceEntry> { |
| 284 | let default_entry = DeviceEntry { |
| 285 | choice: DeviceChoice::SystemDefault, |
| 286 | label: DEFAULT_CAMERA_LABEL.to_owned(), |
| 287 | }; |
| 288 | let named = cameras |
| 289 | .iter() |
| 290 | .filter(|camera| !camera.name.trim().is_empty()) |
| 291 | .map(|camera| DeviceEntry { |
| 292 | choice: DeviceChoice::Device(camera.key.clone()), |
| 293 | label: camera.name.clone(), |
| 294 | }); |
| 295 | std::iter::once(default_entry).chain(named).collect() |
| 296 | } |
| 297 | |
| 298 | #[cfg(test)] |
| 299 | mod tests { |
| 300 | use super::*; |
| 301 | |
| 302 | #[test] |
| 303 | fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() { |
| 304 | let cameras = [ |
| 305 | CameraDevice { key: "0".into(), name: "Integrated Camera".into() }, |
| 306 | CameraDevice { key: "1".into(), name: " ".into() }, |
| 307 | ]; |
| 308 | let entries = camera_entries(&cameras); |
| 309 | assert_eq!(entries.len(), 2); |
| 310 | assert_eq!(entries[0].choice, DeviceChoice::SystemDefault); |
| 311 | assert_eq!(entries[1].choice, DeviceChoice::Device("0".into())); |
| 312 | } |
| 313 | |
| 314 | #[test] |
| 315 | fn yuyv_converts_to_i420_with_averaged_chroma() { |
| 316 | let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60]; |
| 317 | let row_b = [11u8, 120, 21, 220, 31, 70, 41, 80]; |
| 318 | let data: Vec<u8> = row_a.iter().chain(row_b.iter()).copied().collect(); |
| 319 | let mut buffer = i420_from_yuyv(&data, 4, 2).expect("converted"); |
| 320 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 321 | assert_eq!(&plane_y[..4], &[10, 20, 30, 40]); |
| 322 | assert_eq!(plane_u[0], 110); |
| 323 | assert_eq!(plane_u[1], 60); |
| 324 | assert_eq!(plane_v[0], 210); |
| 325 | assert_eq!(plane_v[1], 70); |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn short_raw_frames_are_rejected() { |
| 330 | assert!(i420_from_yuyv(&[0; 8], 4, 2).is_none()); |
| 331 | assert!(i420_from_nv12(&[0; 8], 4, 2).is_none()); |
| 332 | } |
| 333 | |
| 334 | fn format(width: u32, height: u32, frame_format: FrameFormat, fps: u32) -> CameraFormat { |
| 335 | CameraFormat::new(Resolution::new(width, height), frame_format, fps) |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() { |
| 340 | let formats = [ |
| 341 | format(1280, 720, FrameFormat::YUYV, 10), |
| 342 | format(640, 480, FrameFormat::YUYV, 30), |
| 343 | format(1280, 720, FrameFormat::MJPEG, 30), |
| 344 | ]; |
| 345 | assert_eq!(pick_format(&formats), Some(format(640, 480, FrameFormat::YUYV, 30))); |
| 346 | } |
| 347 | |
| 348 | #[test] |
| 349 | fn the_largest_height_up_to_720_wins_then_nv12() { |
| 350 | let formats = [ |
| 351 | format(1920, 1080, FrameFormat::NV12, 30), |
| 352 | format(640, 480, FrameFormat::NV12, 30), |
| 353 | format(1280, 720, FrameFormat::YUYV, 30), |
| 354 | format(1280, 720, FrameFormat::NV12, 30), |
| 355 | ]; |
| 356 | assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30))); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() { |
| 361 | let formats = [format(960, 720, FrameFormat::NV12, 30), format(1280, 720, FrameFormat::YUYV, 30), format(640, 480, FrameFormat::NV12, 30)]; |
| 362 | assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::YUYV, 30))); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn without_720p_the_order_is_1080p_then_360p_then_4_3() { |
| 367 | let full_hd = format(1920, 1080, FrameFormat::NV12, 30); |
| 368 | let small = format(640, 360, FrameFormat::NV12, 30); |
| 369 | let classic = format(960, 720, FrameFormat::NV12, 30); |
| 370 | assert_eq!(pick_format(&[classic, small, full_hd]), Some(full_hd)); |
| 371 | assert_eq!(pick_format(&[classic, small]), Some(small)); |
| 372 | assert_eq!(pick_format(&[classic, format(2560, 1440, FrameFormat::NV12, 30)]), Some(classic)); |
| 373 | } |
| 374 | |
| 375 | fn gradient(width: u32, height: u32) -> I420Buffer { |
| 376 | let mut buffer = I420Buffer::new(width, height); |
| 377 | let (stride_y, stride_u, _) = buffer.strides(); |
| 378 | let (plane_y, plane_u, _) = buffer.data_mut(); |
| 379 | for row in 0..height as usize { |
| 380 | plane_y[row * stride_y as usize..][..width as usize].fill(row as u8); |
| 381 | } |
| 382 | for row in 0..height.div_ceil(2) as usize { |
| 383 | plane_u[row * stride_u as usize..][..width.div_ceil(2) as usize].fill(row as u8); |
| 384 | } |
| 385 | buffer |
| 386 | } |
| 387 | |
| 388 | #[test] |
| 389 | fn a_4_3_frame_is_centre_cropped_to_16_9() { |
| 390 | let cropped = fit_widescreen(gradient(960, 720)); |
| 391 | assert_eq!((cropped.width(), cropped.height()), (960, 540)); |
| 392 | let (stride_y, stride_u, _) = cropped.strides(); |
| 393 | let (plane_y, plane_u, _) = cropped.data(); |
| 394 | assert_eq!(plane_y[0], 90); |
| 395 | assert_eq!(plane_y[539 * stride_y as usize], 629_u32 as u8); |
| 396 | assert_eq!(plane_u[0], 45); |
| 397 | assert_eq!(plane_u[269 * stride_u as usize], 314_u32 as u8); |
| 398 | } |
| 399 | |
| 400 | #[test] |
| 401 | fn a_widescreen_frame_passes_and_1080p_is_scaled_to_720p() { |
| 402 | assert_eq!(fit_widescreen(gradient(1280, 720)).width(), 1280); |
| 403 | let scaled = fit_widescreen(gradient(1920, 1080)); |
| 404 | assert_eq!((scaled.width(), scaled.height()), (1280, 720)); |
| 405 | let wide = fit_widescreen(gradient(2560, 1080)); |
| 406 | assert_eq!((wide.width(), wide.height()), (1280, 720)); |
| 407 | let classic = fit_widescreen(gradient(640, 480)); |
| 408 | assert_eq!((classic.width(), classic.height()), (640, 360)); |
| 409 | } |
| 410 | |
| 411 | #[test] |
| 412 | fn no_usable_format_picks_nothing() { |
| 413 | let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)]; |
| 414 | assert_eq!(pick_format(&formats), None); |
| 415 | assert_eq!(pick_format(&[]), None); |
| 416 | } |
| 417 | |
| 418 | #[test] |
| 419 | fn camera_choices_map_to_indices_or_names() { |
| 420 | assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0))); |
| 421 | assert!(matches!(camera_index(&DeviceChoice::Device("2".into())), CameraIndex::Index(2))); |
| 422 | assert!(matches!(camera_index(&DeviceChoice::Device("video0".into())), CameraIndex::String(_))); |
| 423 | } |
| 424 | } |