| 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; |
| 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, BlurStage}; |
| 12 | use crate::capture::Capture; |
| 13 | use crate::devices::{DeviceChoice, DeviceEntry}; |
| 14 | use crate::error::{Error, Result}; |
| 15 | |
| 16 | const RETRY_PAUSE: Duration = Duration::from_millis(20); |
| 17 | const BYTES_PER_PIXEL: u32 = 4; |
| 18 | const CAPTURE_WIDTH: u32 = 1280; |
| 19 | const CAPTURE_HEIGHT: u32 = 720; |
| 20 | const CAPTURE_FPS: u32 = 30; |
| 21 | const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV]; |
| 22 | |
| 23 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 24 | pub struct CameraDevice { |
| 25 | pub key: String, |
| 26 | pub name: String, |
| 27 | } |
| 28 | |
| 29 | pub fn list_cameras() -> Vec<CameraDevice> { |
| 30 | query(ApiBackend::Auto) |
| 31 | .unwrap_or_default() |
| 32 | .into_iter() |
| 33 | .map(|info| CameraDevice { |
| 34 | key: match info.index() { |
| 35 | CameraIndex::Index(number) => number.to_string(), |
| 36 | CameraIndex::String(text) => text.clone(), |
| 37 | }, |
| 38 | name: info.human_name(), |
| 39 | }) |
| 40 | .collect() |
| 41 | } |
| 42 | |
| 43 | fn camera_index(choice: &DeviceChoice) -> CameraIndex { |
| 44 | match choice { |
| 45 | DeviceChoice::SystemDefault => CameraIndex::Index(0), |
| 46 | DeviceChoice::Device(key) => key.parse().map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index), |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer { |
| 51 | let mut buffer = I420Buffer::new(width, height); |
| 52 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 53 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 54 | abgr_to_i420( |
| 55 | rgba, |
| 56 | width * BYTES_PER_PIXEL, |
| 57 | plane_y, |
| 58 | stride_y, |
| 59 | plane_u, |
| 60 | stride_u, |
| 61 | plane_v, |
| 62 | stride_v, |
| 63 | width as i32, |
| 64 | height as i32, |
| 65 | ); |
| 66 | buffer |
| 67 | } |
| 68 | |
| 69 | fn format_rank(frame_format: FrameFormat) -> u8 { |
| 70 | match frame_format { |
| 71 | FrameFormat::NV12 => 1, |
| 72 | _ => 0, |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> { |
| 77 | formats |
| 78 | .iter() |
| 79 | .copied() |
| 80 | .filter(|format| DIRECT_FORMATS.contains(&format.format())) |
| 81 | .filter(|format| format.frame_rate() >= CAPTURE_FPS && format.height() <= CAPTURE_HEIGHT) |
| 82 | .max_by_key(|format| (format.height(), format_rank(format.format()), std::cmp::Reverse(format.frame_rate()))) |
| 83 | } |
| 84 | |
| 85 | fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> { |
| 86 | let mut camera = Camera::new(index, RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate))?; |
| 87 | let formats = camera.compatible_camera_formats()?; |
| 88 | let format = pick_format(&formats).ok_or_else(|| nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned()))?; |
| 89 | camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(RequestedFormatType::Exact(format)))?; |
| 90 | camera.open_stream()?; |
| 91 | Ok(camera) |
| 92 | } |
| 93 | |
| 94 | fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> { |
| 95 | if let Ok(camera) = open_picked_format(index.clone()) { |
| 96 | return Ok(camera); |
| 97 | } |
| 98 | let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT); |
| 99 | let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS |
| 100 | .into_iter() |
| 101 | .map(|frame_format| RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS))) |
| 102 | .collect(); |
| 103 | requests.push(RequestedFormatType::AbsoluteHighestFrameRate); |
| 104 | let mut last_error = None; |
| 105 | for request in requests { |
| 106 | let format = RequestedFormat::new::<RgbAFormat>(request); |
| 107 | match Camera::new(index.clone(), format).and_then(|mut camera| camera.open_stream().map(|()| camera)) { |
| 108 | Ok(camera) => return Ok(camera), |
| 109 | Err(error) => last_error = Some(error), |
| 110 | } |
| 111 | } |
| 112 | Err(last_error.expect("at least one request")) |
| 113 | } |
| 114 | |
| 115 | pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> { |
| 116 | let luma_len = width as usize * height as usize; |
| 117 | if data.len() < luma_len + luma_len / 2 { |
| 118 | return None; |
| 119 | } |
| 120 | let mut buffer = I420Buffer::new(width, height); |
| 121 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 122 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 123 | let (source_y, source_uv) = data.split_at(luma_len); |
| 124 | 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); |
| 125 | Some(buffer) |
| 126 | } |
| 127 | |
| 128 | pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> { |
| 129 | let (width_pixels, height_rows) = (width as usize, height as usize); |
| 130 | let row_bytes = width_pixels * 2; |
| 131 | if data.len() < row_bytes * height_rows { |
| 132 | return None; |
| 133 | } |
| 134 | let mut buffer = I420Buffer::new(width, height); |
| 135 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 136 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 137 | for row in 0..height_rows { |
| 138 | let source = &data[row * row_bytes..(row + 1) * row_bytes]; |
| 139 | let luma_row = &mut plane_y[row * stride_y as usize..][..width_pixels]; |
| 140 | for (luma, pair) in luma_row.chunks_exact_mut(2).zip(source.chunks_exact(4)) { |
| 141 | luma[0] = pair[0]; |
| 142 | luma[1] = pair[2]; |
| 143 | } |
| 144 | } |
| 145 | for row in 0..height_rows / 2 { |
| 146 | let upper = &data[row * 2 * row_bytes..][..row_bytes]; |
| 147 | let lower = &data[(row * 2 + 1) * row_bytes..][..row_bytes]; |
| 148 | let blue_row = &mut plane_u[row * stride_u as usize..][..width_pixels / 2]; |
| 149 | let red_row = &mut plane_v[row * stride_v as usize..][..width_pixels / 2]; |
| 150 | for (column, (blue, red)) in blue_row.iter_mut().zip(red_row.iter_mut()).enumerate() { |
| 151 | let offset = column * 4; |
| 152 | *blue = ((u16::from(upper[offset + 1]) + u16::from(lower[offset + 1]) + 1) / 2) as u8; |
| 153 | *red = ((u16::from(upper[offset + 3]) + u16::from(lower[offset + 3]) + 1) / 2) as u8; |
| 154 | } |
| 155 | } |
| 156 | Some(buffer) |
| 157 | } |
| 158 | |
| 159 | fn direct_i420(frame_format: FrameFormat, data: &[u8], width: u32, height: u32) -> Option<I420Buffer> { |
| 160 | match frame_format { |
| 161 | FrameFormat::NV12 => i420_from_nv12(data, width, height), |
| 162 | FrameFormat::YUYV => i420_from_yuyv(data, width, height), |
| 163 | _ => None, |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | pub fn start_camera( |
| 168 | choice: &DeviceChoice, |
| 169 | blur: Arc<BlurSettings>, |
| 170 | mut deliver: impl FnMut(I420Buffer) + Send + 'static, |
| 171 | failed: impl FnOnce(String) + Send + 'static, |
| 172 | ) -> Result<Capture> { |
| 173 | let index = camera_index(choice); |
| 174 | Capture::spawn_thread("camera", move |stop| { |
| 175 | let mut camera = match open_camera(index) { |
| 176 | Ok(camera) => camera, |
| 177 | Err(error) => return failed(error.to_string()), |
| 178 | }; |
| 179 | let mut blur_stage = BlurStage::new(blur.clone()); |
| 180 | let mut warned_undecodable = false; |
| 181 | while !stop.load(Ordering::SeqCst) { |
| 182 | let Ok(frame) = camera.frame() else { |
| 183 | std::thread::sleep(RETRY_PAUSE); |
| 184 | continue; |
| 185 | }; |
| 186 | let resolution = frame.resolution(); |
| 187 | let (width, height) = (resolution.width(), resolution.height()); |
| 188 | if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 { |
| 189 | continue; |
| 190 | } |
| 191 | if !blur.enabled() |
| 192 | && let Some(buffer) = direct_i420(frame.source_frame_format(), frame.buffer(), width, height) |
| 193 | { |
| 194 | deliver(buffer); |
| 195 | continue; |
| 196 | } |
| 197 | let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { |
| 198 | if !std::mem::replace(&mut warned_undecodable, true) { |
| 199 | eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format()); |
| 200 | } |
| 201 | continue; |
| 202 | }; |
| 203 | let mut rgba = decoded.into_raw(); |
| 204 | blur_stage.apply_rgba(&mut rgba, width as usize, height as usize); |
| 205 | deliver(i420_from_rgba(&rgba, width, height)); |
| 206 | } |
| 207 | let _ = camera.stop_stream(); |
| 208 | }) |
| 209 | .map_err(|error| Error::Webrtc(format!("camera thread: {error}"))) |
| 210 | } |
| 211 | |
| 212 | pub const DEFAULT_CAMERA_LABEL: &str = "Default camera"; |
| 213 | |
| 214 | pub fn camera_entries(cameras: &[CameraDevice]) -> Vec<DeviceEntry> { |
| 215 | let default_entry = DeviceEntry { |
| 216 | choice: DeviceChoice::SystemDefault, |
| 217 | label: DEFAULT_CAMERA_LABEL.to_owned(), |
| 218 | }; |
| 219 | let named = cameras |
| 220 | .iter() |
| 221 | .filter(|camera| !camera.name.trim().is_empty()) |
| 222 | .map(|camera| DeviceEntry { |
| 223 | choice: DeviceChoice::Device(camera.key.clone()), |
| 224 | label: camera.name.clone(), |
| 225 | }); |
| 226 | std::iter::once(default_entry).chain(named).collect() |
| 227 | } |
| 228 | |
| 229 | #[cfg(test)] |
| 230 | mod tests { |
| 231 | use super::*; |
| 232 | |
| 233 | #[test] |
| 234 | fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() { |
| 235 | let cameras = [ |
| 236 | CameraDevice { key: "0".into(), name: "Integrated Camera".into() }, |
| 237 | CameraDevice { key: "1".into(), name: " ".into() }, |
| 238 | ]; |
| 239 | let entries = camera_entries(&cameras); |
| 240 | assert_eq!(entries.len(), 2); |
| 241 | assert_eq!(entries[0].choice, DeviceChoice::SystemDefault); |
| 242 | assert_eq!(entries[1].choice, DeviceChoice::Device("0".into())); |
| 243 | } |
| 244 | |
| 245 | #[test] |
| 246 | fn yuyv_converts_to_i420_with_averaged_chroma() { |
| 247 | let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60]; |
| 248 | let row_b = [11u8, 120, 21, 220, 31, 70, 41, 80]; |
| 249 | let data: Vec<u8> = row_a.iter().chain(row_b.iter()).copied().collect(); |
| 250 | let mut buffer = i420_from_yuyv(&data, 4, 2).expect("converted"); |
| 251 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 252 | assert_eq!(&plane_y[..4], &[10, 20, 30, 40]); |
| 253 | assert_eq!(plane_u[0], 110); |
| 254 | assert_eq!(plane_u[1], 60); |
| 255 | assert_eq!(plane_v[0], 210); |
| 256 | assert_eq!(plane_v[1], 70); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn short_raw_frames_are_rejected() { |
| 261 | assert!(i420_from_yuyv(&[0; 8], 4, 2).is_none()); |
| 262 | assert!(i420_from_nv12(&[0; 8], 4, 2).is_none()); |
| 263 | } |
| 264 | |
| 265 | fn format(width: u32, height: u32, frame_format: FrameFormat, fps: u32) -> CameraFormat { |
| 266 | CameraFormat::new(Resolution::new(width, height), frame_format, fps) |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() { |
| 271 | let formats = [ |
| 272 | format(1280, 720, FrameFormat::YUYV, 10), |
| 273 | format(640, 480, FrameFormat::YUYV, 30), |
| 274 | format(1280, 720, FrameFormat::MJPEG, 30), |
| 275 | ]; |
| 276 | assert_eq!(pick_format(&formats), Some(format(640, 480, FrameFormat::YUYV, 30))); |
| 277 | } |
| 278 | |
| 279 | #[test] |
| 280 | fn the_largest_height_up_to_720_wins_then_nv12() { |
| 281 | let formats = [ |
| 282 | format(1920, 1080, FrameFormat::NV12, 30), |
| 283 | format(640, 480, FrameFormat::NV12, 30), |
| 284 | format(1280, 720, FrameFormat::YUYV, 30), |
| 285 | format(1280, 720, FrameFormat::NV12, 30), |
| 286 | ]; |
| 287 | assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30))); |
| 288 | } |
| 289 | |
| 290 | #[test] |
| 291 | fn no_usable_format_picks_nothing() { |
| 292 | let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)]; |
| 293 | assert_eq!(pick_format(&formats), None); |
| 294 | assert_eq!(pick_format(&[]), None); |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn camera_choices_map_to_indices_or_names() { |
| 299 | assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0))); |
| 300 | assert!(matches!(camera_index(&DeviceChoice::Device("2".into())), CameraIndex::Index(2))); |
| 301 | assert!(matches!(camera_index(&DeviceChoice::Device("video0".into())), CameraIndex::String(_))); |
| 302 | } |
| 303 | } |