BlueGit

ict rusty-teams

Files

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

camera.rs

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