BlueGit

ict rusty-teams

Files

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

camera.rs

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