| 1 | use std::sync::Arc; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use libwebrtc::native::yuv_helper::abgr_to_i420; |
| 5 | use libwebrtc::video_frame::I420Buffer; |
| 6 | use nokhwa::pixel_format::RgbAFormat; |
| 7 | use nokhwa::utils::{ApiBackend, CameraIndex, RequestedFormat, RequestedFormatType}; |
| 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 | |
| 19 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 20 | pub struct CameraDevice { |
| 21 | pub key: String, |
| 22 | pub name: String, |
| 23 | } |
| 24 | |
| 25 | pub fn list_cameras() -> Vec<CameraDevice> { |
| 26 | query(ApiBackend::Auto) |
| 27 | .unwrap_or_default() |
| 28 | .into_iter() |
| 29 | .map(|info| CameraDevice { |
| 30 | key: match info.index() { |
| 31 | CameraIndex::Index(number) => number.to_string(), |
| 32 | CameraIndex::String(text) => text.clone(), |
| 33 | }, |
| 34 | name: info.human_name(), |
| 35 | }) |
| 36 | .collect() |
| 37 | } |
| 38 | |
| 39 | fn camera_index(choice: &DeviceChoice) -> CameraIndex { |
| 40 | match choice { |
| 41 | DeviceChoice::SystemDefault => CameraIndex::Index(0), |
| 42 | DeviceChoice::Device(key) => key.parse().map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index), |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer { |
| 47 | let mut buffer = I420Buffer::new(width, height); |
| 48 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 49 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 50 | abgr_to_i420( |
| 51 | rgba, |
| 52 | width * BYTES_PER_PIXEL, |
| 53 | plane_y, |
| 54 | stride_y, |
| 55 | plane_u, |
| 56 | stride_u, |
| 57 | plane_v, |
| 58 | stride_v, |
| 59 | width as i32, |
| 60 | height as i32, |
| 61 | ); |
| 62 | buffer |
| 63 | } |
| 64 | |
| 65 | pub fn start_camera( |
| 66 | choice: &DeviceChoice, |
| 67 | blur: Arc<BlurSettings>, |
| 68 | mut deliver: impl FnMut(I420Buffer) + Send + 'static, |
| 69 | failed: impl FnOnce(String) + Send + 'static, |
| 70 | ) -> Result<Capture> { |
| 71 | let index = camera_index(choice); |
| 72 | Capture::spawn_thread("camera", move |stop| { |
| 73 | let format = RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate); |
| 74 | let mut camera = match Camera::new(index, format).and_then(|mut camera| camera.open_stream().map(|()| camera)) { |
| 75 | Ok(camera) => camera, |
| 76 | Err(error) => return failed(error.to_string()), |
| 77 | }; |
| 78 | let mut blur_stage = BlurStage::new(blur); |
| 79 | while !stop.load(Ordering::SeqCst) { |
| 80 | let Ok(frame) = camera.frame() else { |
| 81 | std::thread::sleep(RETRY_PAUSE); |
| 82 | continue; |
| 83 | }; |
| 84 | let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { continue }; |
| 85 | let (width, height) = (decoded.width(), decoded.height()); |
| 86 | if width >= 2 && height >= 2 && width % 2 == 0 && height % 2 == 0 { |
| 87 | let mut rgba = decoded.into_raw(); |
| 88 | blur_stage.apply_rgba(&mut rgba, width as usize, height as usize); |
| 89 | deliver(i420_from_rgba(&rgba, width, height)); |
| 90 | } |
| 91 | } |
| 92 | let _ = camera.stop_stream(); |
| 93 | }) |
| 94 | .map_err(|error| Error::Webrtc(format!("camera thread: {error}"))) |
| 95 | } |
| 96 | |
| 97 | pub const DEFAULT_CAMERA_LABEL: &str = "Default camera"; |
| 98 | |
| 99 | pub fn camera_entries(cameras: &[CameraDevice]) -> Vec<DeviceEntry> { |
| 100 | let default_entry = DeviceEntry { |
| 101 | choice: DeviceChoice::SystemDefault, |
| 102 | label: DEFAULT_CAMERA_LABEL.to_owned(), |
| 103 | }; |
| 104 | let named = cameras |
| 105 | .iter() |
| 106 | .filter(|camera| !camera.name.trim().is_empty()) |
| 107 | .map(|camera| DeviceEntry { |
| 108 | choice: DeviceChoice::Device(camera.key.clone()), |
| 109 | label: camera.name.clone(), |
| 110 | }); |
| 111 | std::iter::once(default_entry).chain(named).collect() |
| 112 | } |
| 113 | |
| 114 | #[cfg(test)] |
| 115 | mod tests { |
| 116 | use super::*; |
| 117 | |
| 118 | #[test] |
| 119 | fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() { |
| 120 | let cameras = [ |
| 121 | CameraDevice { key: "0".into(), name: "Integrated Camera".into() }, |
| 122 | CameraDevice { key: "1".into(), name: " ".into() }, |
| 123 | ]; |
| 124 | let entries = camera_entries(&cameras); |
| 125 | assert_eq!(entries.len(), 2); |
| 126 | assert_eq!(entries[0].choice, DeviceChoice::SystemDefault); |
| 127 | assert_eq!(entries[1].choice, DeviceChoice::Device("0".into())); |
| 128 | } |
| 129 | |
| 130 | #[test] |
| 131 | fn camera_choices_map_to_indices_or_names() { |
| 132 | assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0))); |
| 133 | assert!(matches!(camera_index(&DeviceChoice::Device("2".into())), CameraIndex::Index(2))); |
| 134 | assert!(matches!(camera_index(&DeviceChoice::Device("video0".into())), CameraIndex::String(_))); |
| 135 | } |
| 136 | } |