BlueGit

ict rusty-teams

Files

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

camera.rs

camera.rs 30.0 KiB Download Raw
1use std::process::Command;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::time::{Duration, Instant};
5
6use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
7use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
8use nokhwa::pixel_format::RgbAFormat;
9use nokhwa::utils::{
10 ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType,
11 Resolution,
12};
13use nokhwa::{Camera, query};
14use zune_core::bytestream::ZCursor;
15use zune_core::colorspace::ColorSpace;
16use zune_core::options::DecoderOptions;
17use zune_jpeg::JpegDecoder;
18
19use crate::blur::BlurSettings;
20use crate::capture::Capture;
21use crate::devices::{DeviceChoice, DeviceEntry};
22use crate::effects::EffectsThread;
23use crate::error::{Error, Result};
24use crate::video_quality::VideoQuality;
25
26const RETRY_PAUSE: Duration = Duration::from_millis(20);
27const BYTES_PER_PIXEL: u32 = 4;
28const CAPTURE_FPS: u32 = 30;
29const ASPECT_WIDTH: u32 = 16;
30const ASPECT_HEIGHT: u32 = 9;
31const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
32const USABLE_FORMATS: [FrameFormat; 3] =
33 [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct CameraDevice {
37 pub key: String,
38 pub name: String,
39}
40
41/// Shared capture counters for call-report stats (format + fps + decode time).
42#[derive(Debug, Default)]
43pub struct CameraCaptureStats {
44 format: std::sync::Mutex<String>,
45 started: std::sync::Mutex<Option<Instant>>,
46 frames: AtomicU64,
47 decode_ns: AtomicU64,
48}
49
50impl CameraCaptureStats {
51 pub fn new() -> Arc<Self> {
52 Arc::new(Self::default())
53 }
54
55 fn set_format(&self, label: impl Into<String>) {
56 if let Ok(mut slot) = self.format.lock() {
57 *slot = label.into();
58 }
59 if let Ok(mut started) = self.started.lock() {
60 *started = Some(Instant::now());
61 }
62 self.frames.store(0, Ordering::Relaxed);
63 self.decode_ns.store(0, Ordering::Relaxed);
64 }
65
66 fn note_frame(&self, decode: Duration) {
67 self.frames.fetch_add(1, Ordering::Relaxed);
68 self.decode_ns
69 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
70 }
71
72 pub fn format_label(&self) -> String {
73 self.format
74 .lock()
75 .map(|label| label.clone())
76 .unwrap_or_default()
77 }
78
79 pub fn summary(&self) -> Option<String> {
80 let label = self.format_label();
81 if label.is_empty() {
82 return None;
83 }
84 let frames = self.frames.load(Ordering::Relaxed);
85 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
86 let decode_ms = if frames == 0 {
87 0.0
88 } else {
89 (decode_ns as f64 / frames as f64) / 1_000_000.0
90 };
91 let fps = self
92 .started
93 .lock()
94 .ok()
95 .and_then(|started| *started)
96 .map(|started| {
97 let seconds = started.elapsed().as_secs_f64().max(0.001);
98 frames as f64 / seconds
99 })
100 .unwrap_or(0.0);
101 Some(format!(
102 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
103 ))
104 }
105}
106
107pub fn list_cameras() -> Vec<CameraDevice> {
108 query(ApiBackend::Auto)
109 .unwrap_or_default()
110 .into_iter()
111 .map(|info| CameraDevice {
112 key: match info.index() {
113 CameraIndex::Index(number) => number.to_string(),
114 CameraIndex::String(text) => text.clone(),
115 },
116 name: info.human_name(),
117 })
118 .collect()
119}
120
121fn camera_index(choice: &DeviceChoice) -> CameraIndex {
122 match choice {
123 DeviceChoice::SystemDefault => CameraIndex::Index(0),
124 DeviceChoice::Device(key) => key
125 .parse()
126 .map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
127 }
128}
129
130pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
131 let mut buffer = I420Buffer::new(width, height);
132 let (stride_y, stride_u, stride_v) = buffer.strides();
133 let (plane_y, plane_u, plane_v) = buffer.data_mut();
134 abgr_to_i420(
135 rgba,
136 width * BYTES_PER_PIXEL,
137 plane_y,
138 stride_y,
139 plane_u,
140 stride_u,
141 plane_v,
142 stride_v,
143 width as i32,
144 height as i32,
145 );
146 buffer
147}
148
149fn format_rank(frame_format: FrameFormat) -> u8 {
150 match frame_format {
151 FrameFormat::NV12 => 3,
152 FrameFormat::YUYV => 2,
153 FrameFormat::MJPEG => 1,
154 _ => 0,
155 }
156}
157
158fn format_short_name(frame_format: FrameFormat) -> String {
159 match frame_format {
160 FrameFormat::MJPEG => "MJPG".into(),
161 FrameFormat::NV12 => "NV12".into(),
162 FrameFormat::YUYV => "YUYV".into(),
163 other => other.to_string(),
164 }
165}
166
167fn format_label(format: &CameraFormat) -> String {
168 format!(
169 "{} {}x{} @{}",
170 format_short_name(format.format()),
171 format.width(),
172 format.height(),
173 format.frame_rate()
174 )
175}
176
177fn is_widescreen(width: u32, height: u32) -> bool {
178 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
179}
180
181fn widescreen_tier(format: &CameraFormat, capture_height: u32) -> u8 {
182 match (
183 is_widescreen(format.width(), format.height()),
184 format.height(),
185 ) {
186 (true, height) if height == capture_height => 3,
187 (true, height) if height > capture_height => 2,
188 (true, _) => 1,
189 (false, _) => 0,
190 }
191}
192
193fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<CameraFormat> {
194 let capture_height = quality.capture_height();
195 let largest = quality.largest_sensor_height();
196 formats
197 .iter()
198 .copied()
199 .filter(|format| USABLE_FORMATS.contains(&format.format()))
200 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
201 .filter(|format| {
202 format.height() <= capture_height
203 || (is_widescreen(format.width(), format.height()) && format.height() <= largest)
204 })
205 .max_by_key(|format| {
206 (
207 widescreen_tier(format, capture_height),
208 std::cmp::Reverse(format.height().abs_diff(capture_height)),
209 format_rank(format.format()),
210 std::cmp::Reverse(format.frame_rate()),
211 )
212 })
213}
214
215fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
216 match quality {
217 VideoQuality::P720 => vec![720, 540, 360],
218 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
219 }
220}
221
222fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
223 let mut candidates = Vec::new();
224 for height in candidate_heights(quality) {
225 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
226 candidates.push(CameraFormat::new(
227 Resolution::new(width, height),
228 FrameFormat::MJPEG,
229 CAPTURE_FPS,
230 ));
231 for frame_format in DIRECT_FORMATS {
232 candidates.push(CameraFormat::new(
233 Resolution::new(width, height),
234 frame_format,
235 CAPTURE_FPS,
236 ));
237 }
238 }
239 candidates
240}
241
242fn even(value: u32) -> u32 {
243 value & !1
244}
245
246fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32) -> I420Buffer {
247 let mut cropped = I420Buffer::new(width, height);
248 let (source_strides, source_planes) = (buffer.strides(), buffer.data());
249 let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut());
250 let planes = [
251 (
252 source_planes.0,
253 source_strides.0,
254 target_planes.0,
255 target_strides.0,
256 1,
257 ),
258 (
259 source_planes.1,
260 source_strides.1,
261 target_planes.1,
262 target_strides.1,
263 2,
264 ),
265 (
266 source_planes.2,
267 source_strides.2,
268 target_planes.2,
269 target_strides.2,
270 2,
271 ),
272 ];
273 for (source, source_stride, target, target_stride, divisor) in planes {
274 let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize);
275 let (plane_width, plane_height) = (
276 width.div_ceil(divisor) as usize,
277 height.div_ceil(divisor) as usize,
278 );
279 for row in 0..plane_height {
280 let from = (plane_top + row) * source_stride as usize + plane_left;
281 let to = row * target_stride as usize;
282 target[to..to + plane_width].copy_from_slice(&source[from..from + plane_width]);
283 }
284 }
285 cropped
286}
287
288pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I420Buffer {
289 let capture_height = quality.capture_height();
290 let (width, height) = (buffer.width(), buffer.height());
291 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
292 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
293 } else {
294 (width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH))
295 };
296 if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 {
297 buffer = crop_i420(
298 &buffer,
299 even((width - crop_width) / 2),
300 even((height - crop_height) / 2),
301 crop_width,
302 crop_height,
303 );
304 }
305 let (width, height) = (buffer.width(), buffer.height());
306 if height > capture_height {
307 let scaled_width = even(width * capture_height / height);
308 return buffer.scale(scaled_width as i32, capture_height as i32);
309 }
310 buffer
311}
312
313fn open_with_request(
314 index: CameraIndex,
315 request: RequestedFormatType,
316) -> std::result::Result<Camera, nokhwa::NokhwaError> {
317 let format = RequestedFormat::new::<RgbAFormat>(request);
318 let mut camera = Camera::new(index, format)?;
319 camera.open_stream()?;
320 Ok(camera)
321}
322
323fn device_path(index: &CameraIndex) -> Option<String> {
324 match index {
325 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
326 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
327 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
328 Some(format!("/dev/video{text}"))
329 }
330 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
331 _ => None,
332 }
333}
334
335fn tune_uvc_controls(index: &CameraIndex) {
336 let Some(device) = device_path(index) else {
337 return;
338 };
339 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
340 let _ = Command::new("v4l2-ctl")
341 .args([
342 "-d",
343 &device,
344 "-c",
345 "exposure_dynamic_framerate=0,power_line_frequency=1",
346 ])
347 .stdout(std::process::Stdio::null())
348 .stderr(std::process::Stdio::null())
349 .status();
350}
351
352fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
353 let got = camera.camera_format();
354 if got.frame_rate() < CAPTURE_FPS {
355 let _ = camera.stop_stream();
356 return None;
357 }
358 tune_uvc_controls(index);
359 let label = format_label(&got);
360 Some((camera, label))
361}
362
363fn try_exact_or_closest(
364 index: CameraIndex,
365 format: CameraFormat,
366) -> std::result::Result<Camera, nokhwa::NokhwaError> {
367 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
368 Ok(camera) => Ok(camera),
369 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
370 }
371}
372
373fn open_from_list(
374 index: CameraIndex,
375 quality: VideoQuality,
376 formats: &[CameraFormat],
377) -> Option<(Camera, String)> {
378 let Some(wanted) = pick_format(formats, quality) else {
379 return None;
380 };
381 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
382 accept_opened(&index, camera)
383}
384
385fn open_camera(
386 index: CameraIndex,
387 quality: VideoQuality,
388) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
389 // Probe the device list without committing to a slow Closest(NV12) open.
390 for probe in preferred_candidates(quality) {
391 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
392 continue;
393 };
394 if let Ok(formats) = camera.compatible_camera_formats() {
395 let _ = camera.stop_stream();
396 drop(camera);
397 if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
398 return Ok(opened);
399 }
400 } else if let Some(opened) = accept_opened(&index, camera) {
401 return Ok(opened);
402 }
403 }
404
405 let mut last_error = None;
406 for candidate in preferred_candidates(quality) {
407 match try_exact_or_closest(index.clone(), candidate) {
408 Ok(camera) => {
409 if let Some(opened) = accept_opened(&index, camera) {
410 return Ok(opened);
411 }
412 }
413 Err(error) => last_error = Some(error),
414 }
415 }
416
417 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
418 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
419 Ok(camera) => {
420 tune_uvc_controls(&index);
421 let label = format_label(&camera.camera_format());
422 Ok((camera, label))
423 }
424 Err(error) => Err(last_error.unwrap_or(error)),
425 }
426}
427
428pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
429 let luma_len = width as usize * height as usize;
430 if data.len() < luma_len + luma_len / 2 {
431 return None;
432 }
433 let mut buffer = I420Buffer::new(width, height);
434 let (stride_y, stride_u, stride_v) = buffer.strides();
435 let (plane_y, plane_u, plane_v) = buffer.data_mut();
436 let (source_y, source_uv) = data.split_at(luma_len);
437 nv12_to_i420(
438 source_y,
439 width,
440 source_uv,
441 width,
442 plane_y,
443 stride_y,
444 plane_u,
445 stride_u,
446 plane_v,
447 stride_v,
448 width as i32,
449 height as i32,
450 );
451 Some(buffer)
452}
453
454pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
455 let (width_pixels, height_rows) = (width as usize, height as usize);
456 let row_bytes = width_pixels * 2;
457 if data.len() < row_bytes * height_rows {
458 return None;
459 }
460 let mut buffer = I420Buffer::new(width, height);
461 let (stride_y, stride_u, stride_v) = buffer.strides();
462 let (plane_y, plane_u, plane_v) = buffer.data_mut();
463 for row in 0..height_rows {
464 let source = &data[row * row_bytes..(row + 1) * row_bytes];
465 let luma_row = &mut plane_y[row * stride_y as usize..][..width_pixels];
466 for (luma, pair) in luma_row.chunks_exact_mut(2).zip(source.chunks_exact(4)) {
467 luma[0] = pair[0];
468 luma[1] = pair[2];
469 }
470 }
471 for row in 0..height_rows / 2 {
472 let upper = &data[row * 2 * row_bytes..][..row_bytes];
473 let lower = &data[(row * 2 + 1) * row_bytes..][..row_bytes];
474 let blue_row = &mut plane_u[row * stride_u as usize..][..width_pixels / 2];
475 let red_row = &mut plane_v[row * stride_v as usize..][..width_pixels / 2];
476 for (column, (blue, red)) in blue_row.iter_mut().zip(red_row.iter_mut()).enumerate() {
477 let offset = column * 4;
478 *blue = ((u16::from(upper[offset + 1]) + u16::from(lower[offset + 1]) + 1) / 2) as u8;
479 *red = ((u16::from(upper[offset + 3]) + u16::from(lower[offset + 3]) + 1) / 2) as u8;
480 }
481 }
482 Some(buffer)
483}
484
485fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
486 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
487 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
488 let pixels = decoder.decode().ok()?;
489 let info = decoder.info()?;
490 let (width, height) = (u32::from(info.width), u32::from(info.height));
491 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
492 return None;
493 }
494 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
495 let rgba = if pixels.len() == rgba_len {
496 pixels.as_slice()
497 } else if pixels.len() == (width * height * 3) as usize {
498 rgba_scratch.clear();
499 rgba_scratch.reserve(rgba_len);
500 for chunk in pixels.chunks_exact(3) {
501 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
502 }
503 rgba_scratch.as_slice()
504 } else {
505 return None;
506 };
507 Some((i420_from_rgba(rgba, width, height), width, height))
508}
509
510fn direct_i420(
511 frame_format: FrameFormat,
512 data: &[u8],
513 width: u32,
514 height: u32,
515 rgba_scratch: &mut Vec<u8>,
516) -> Option<I420Buffer> {
517 match frame_format {
518 FrameFormat::NV12 => i420_from_nv12(data, width, height),
519 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
520 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
521 _ => None,
522 }
523}
524
525pub fn start_camera(
526 choice: &DeviceChoice,
527 quality: VideoQuality,
528 blur: Arc<BlurSettings>,
529 stats: Arc<CameraCaptureStats>,
530 on_opened: impl FnOnce(String) + Send + 'static,
531 deliver: impl FnMut(I420Buffer) + Send + 'static,
532 failed: impl FnOnce(String) + Send + 'static,
533) -> Result<Capture> {
534 let index = camera_index(choice);
535 Capture::spawn_thread("camera", move |stop| {
536 let (mut camera, label) = match open_camera(index, quality) {
537 Ok(opened) => opened,
538 Err(error) => return failed(error.to_string()),
539 };
540 stats.set_format(&label);
541 on_opened(label);
542 let effects = match EffectsThread::spawn(blur, deliver) {
543 Ok(effects) => effects,
544 Err(error) => return failed(format!("effects thread: {error}")),
545 };
546 let mut warned_undecodable = false;
547 let mut rgba_scratch = Vec::new();
548 while !stop.load(Ordering::SeqCst) {
549 let Ok(frame) = camera.frame() else {
550 std::thread::sleep(RETRY_PAUSE);
551 continue;
552 };
553 let resolution = frame.resolution();
554 let (width, height) = (resolution.width(), resolution.height());
555 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
556 continue;
557 }
558 let started = Instant::now();
559 let buffer = match direct_i420(
560 frame.source_frame_format(),
561 frame.buffer(),
562 width,
563 height,
564 &mut rgba_scratch,
565 ) {
566 Some(buffer) => buffer,
567 None => {
568 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
569 if !std::mem::replace(&mut warned_undecodable, true) {
570 eprintln!(
571 "calls: camera delivers {} and no decoder is available",
572 frame.source_frame_format()
573 );
574 }
575 continue;
576 };
577 i420_from_rgba(&decoded.into_raw(), width, height)
578 }
579 };
580 stats.note_frame(started.elapsed());
581 effects.submit(fit_widescreen(buffer, quality));
582 }
583 let _ = camera.stop_stream();
584 })
585 .map_err(|error| Error::Webrtc(format!("camera thread: {error}")))
586}
587
588pub const DEFAULT_CAMERA_LABEL: &str = "Default camera";
589
590pub fn camera_entries(cameras: &[CameraDevice]) -> Vec<DeviceEntry> {
591 let default_entry = DeviceEntry {
592 choice: DeviceChoice::SystemDefault,
593 label: DEFAULT_CAMERA_LABEL.to_owned(),
594 };
595 let named = cameras
596 .iter()
597 .filter(|camera| !camera.name.trim().is_empty())
598 .map(|camera| DeviceEntry {
599 choice: DeviceChoice::Device(camera.key.clone()),
600 label: camera.name.clone(),
601 });
602 std::iter::once(default_entry).chain(named).collect()
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608
609 #[test]
610 fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() {
611 let cameras = [
612 CameraDevice {
613 key: "0".into(),
614 name: "Integrated Camera".into(),
615 },
616 CameraDevice {
617 key: "1".into(),
618 name: " ".into(),
619 },
620 ];
621 let entries = camera_entries(&cameras);
622 assert_eq!(entries.len(), 2);
623 assert_eq!(entries[0].choice, DeviceChoice::SystemDefault);
624 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
625 }
626
627 #[test]
628 fn yuyv_converts_to_i420_with_averaged_chroma() {
629 let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60];
630 let row_b = [11u8, 120, 21, 220, 31, 70, 41, 80];
631 let data: Vec<u8> = row_a.iter().chain(row_b.iter()).copied().collect();
632 let mut buffer = i420_from_yuyv(&data, 4, 2).expect("converted");
633 let (plane_y, plane_u, plane_v) = buffer.data_mut();
634 assert_eq!(&plane_y[..4], &[10, 20, 30, 40]);
635 assert_eq!(plane_u[0], 110);
636 assert_eq!(plane_u[1], 60);
637 assert_eq!(plane_v[0], 210);
638 assert_eq!(plane_v[1], 70);
639 }
640
641 #[test]
642 fn short_raw_frames_are_rejected() {
643 assert!(i420_from_yuyv(&[0; 8], 4, 2).is_none());
644 assert!(i420_from_nv12(&[0; 8], 4, 2).is_none());
645 }
646
647 fn format(width: u32, height: u32, frame_format: FrameFormat, fps: u32) -> CameraFormat {
648 CameraFormat::new(Resolution::new(width, height), frame_format, fps)
649 }
650
651 #[test]
652 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
653 let formats = [
654 format(1280, 720, FrameFormat::YUYV, 10),
655 format(640, 480, FrameFormat::YUYV, 30),
656 format(1280, 720, FrameFormat::MJPEG, 30),
657 ];
658 assert_eq!(
659 pick_format(&formats, VideoQuality::P720),
660 Some(format(1280, 720, FrameFormat::MJPEG, 30))
661 );
662 }
663
664 #[test]
665 fn raw_at_the_same_height_beats_mjpeg() {
666 let formats = [
667 format(1280, 720, FrameFormat::MJPEG, 30),
668 format(1280, 720, FrameFormat::NV12, 30),
669 ];
670 assert_eq!(
671 pick_format(&formats, VideoQuality::P720),
672 Some(format(1280, 720, FrameFormat::NV12, 30))
673 );
674 }
675
676 #[test]
677 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
678 let formats = [
679 format(1920, 1080, FrameFormat::YUYV, 5),
680 format(1280, 720, FrameFormat::YUYV, 10),
681 format(640, 360, FrameFormat::YUYV, 30),
682 format(1920, 1080, FrameFormat::MJPEG, 30),
683 format(1280, 720, FrameFormat::MJPEG, 30),
684 format(960, 540, FrameFormat::MJPEG, 30),
685 ];
686 assert_eq!(
687 pick_format(&formats, VideoQuality::Auto),
688 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
689 );
690 assert_eq!(
691 pick_format(&formats, VideoQuality::P720),
692 Some(format(1280, 720, FrameFormat::MJPEG, 30))
693 );
694 }
695
696 #[test]
697 fn auto_prefers_1080p_nv12_over_720p() {
698 let formats = [
699 format(1920, 1080, FrameFormat::NV12, 30),
700 format(640, 480, FrameFormat::NV12, 30),
701 format(1280, 720, FrameFormat::YUYV, 30),
702 format(1280, 720, FrameFormat::NV12, 30),
703 ];
704 assert_eq!(
705 pick_format(&formats, VideoQuality::Auto),
706 Some(format(1920, 1080, FrameFormat::NV12, 30))
707 );
708 assert_eq!(
709 pick_format(&formats, VideoQuality::P720),
710 Some(format(1280, 720, FrameFormat::NV12, 30))
711 );
712 }
713
714 #[test]
715 fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() {
716 let formats = [
717 format(960, 720, FrameFormat::NV12, 30),
718 format(1280, 720, FrameFormat::YUYV, 30),
719 format(640, 480, FrameFormat::NV12, 30),
720 ];
721 assert_eq!(
722 pick_format(&formats, VideoQuality::P720),
723 Some(format(1280, 720, FrameFormat::YUYV, 30))
724 );
725 }
726
727 #[test]
728 fn locked_720_keeps_1080_as_downscale_candidate_but_prefers_exact_720() {
729 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
730 let hd = format(1280, 720, FrameFormat::NV12, 30);
731 let small = format(640, 360, FrameFormat::NV12, 30);
732 let classic = format(960, 720, FrameFormat::NV12, 30);
733 assert_eq!(
734 pick_format(&[classic, small, full_hd], VideoQuality::Auto),
735 Some(full_hd)
736 );
737 assert_eq!(
738 pick_format(&[classic, small, full_hd, hd], VideoQuality::P720),
739 Some(hd)
740 );
741 assert_eq!(
742 pick_format(
743 &[classic, format(2560, 1440, FrameFormat::NV12, 30)],
744 VideoQuality::P720
745 ),
746 Some(classic)
747 );
748 }
749
750 fn gradient(width: u32, height: u32) -> I420Buffer {
751 let mut buffer = I420Buffer::new(width, height);
752 let (stride_y, stride_u, _) = buffer.strides();
753 let (plane_y, plane_u, _) = buffer.data_mut();
754 for row in 0..height as usize {
755 plane_y[row * stride_y as usize..][..width as usize].fill(row as u8);
756 }
757 for row in 0..height.div_ceil(2) as usize {
758 plane_u[row * stride_u as usize..][..width.div_ceil(2) as usize].fill(row as u8);
759 }
760 buffer
761 }
762
763 #[test]
764 fn a_4_3_frame_is_centre_cropped_to_16_9() {
765 let cropped = fit_widescreen(gradient(960, 720), VideoQuality::P720);
766 assert_eq!((cropped.width(), cropped.height()), (960, 540));
767 let (stride_y, stride_u, _) = cropped.strides();
768 let (plane_y, plane_u, _) = cropped.data();
769 assert_eq!(plane_y[0], 90);
770 assert_eq!(plane_y[539 * stride_y as usize], 629_u32 as u8);
771 assert_eq!(plane_u[0], 45);
772 assert_eq!(plane_u[269 * stride_u as usize], 314_u32 as u8);
773 }
774
775 #[test]
776 fn auto_keeps_1080p_and_720_lock_scales_it_down() {
777 assert_eq!(
778 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
779 1280
780 );
781 let kept = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
782 assert_eq!((kept.width(), kept.height()), (1920, 1080));
783 let scaled = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
784 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
785 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
786 assert_eq!((wide.width(), wide.height()), (1920, 1080));
787 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
788 assert_eq!((classic.width(), classic.height()), (640, 360));
789 }
790
791 #[test]
792 fn no_usable_format_picks_nothing() {
793 let formats = [
794 format(1280, 720, FrameFormat::MJPEG, 15),
795 format(1280, 720, FrameFormat::YUYV, 15),
796 ];
797 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
798 assert_eq!(pick_format(&[], VideoQuality::Auto), None);
799 }
800
801 #[test]
802 fn camera_choices_map_to_indices_or_names() {
803 assert!(matches!(
804 camera_index(&DeviceChoice::SystemDefault),
805 CameraIndex::Index(0)
806 ));
807 assert!(matches!(
808 camera_index(&DeviceChoice::Device("2".into())),
809 CameraIndex::Index(2)
810 ));
811 assert!(matches!(
812 camera_index(&DeviceChoice::Device("video0".into())),
813 CameraIndex::String(_)
814 ));
815 }
816
817 #[test]
818 fn mjpeg_decodes_to_i420() {
819 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
820 let mut rgb = image::RgbImage::new(16, 16);
821 for pixel in rgb.pixels_mut() {
822 *pixel = image::Rgb([40, 80, 120]);
823 }
824 let mut jpeg = Vec::new();
825 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
826 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
827 .expect("encode");
828 let mut scratch = Vec::new();
829 let (buffer, width, height) =
830 i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
831 assert_eq!((width, height), (16, 16));
832 assert_eq!((buffer.width(), buffer.height()), (16, 16));
833 }
834
835 #[test]
836 #[ignore = "timing; run with --release --ignored"]
837 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
838 let mut rgb = image::RgbImage::new(1920, 1080);
839 for (index, pixel) in rgb.pixels_mut().enumerate() {
840 let value = (index % 255) as u8;
841 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
842 }
843 let mut jpeg = Vec::new();
844 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
845 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
846 .expect("encode");
847 let mut scratch = Vec::new();
848 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
849 for _ in 0..3 {
850 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
851 }
852 let started = Instant::now();
853 for _ in 0..10 {
854 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
855 }
856 let average = started.elapsed() / 10;
857 assert!(
858 average < Duration::from_millis(20),
859 "average decode {average:?} exceeds 20 ms"
860 );
861 }
862
863 #[test]
864 #[ignore = "needs a connected camera"]
865 fn open_picks_at_least_thirty_fps_when_available() {
866 if list_cameras().is_empty() {
867 return;
868 }
869 let (mut camera, label) = open_camera(CameraIndex::Index(0), VideoQuality::Auto)
870 .expect("camera opens");
871 assert!(
872 camera.camera_format().frame_rate() >= CAPTURE_FPS,
873 "opened {label} under 30 fps"
874 );
875 // Warm up buffers, then count for one second.
876 for _ in 0..10 {
877 let _ = camera.frame();
878 }
879 let deadline = Instant::now() + Duration::from_secs(1);
880 let mut frames = 0u32;
881 while Instant::now() < deadline {
882 if camera.frame().is_ok() {
883 frames += 1;
884 }
885 }
886 let _ = camera.stop_stream();
887 assert!(
888 frames >= 20,
889 "expected >= 20 frames in 1 s from {label}, got {frames}"
890 );
891 }
892}