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