BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / camera.rs

camera.rs

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