BlueGit

ict rusty-teams

Files

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

camera.rs

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