BlueGit

ict rusty-teams

Files

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

camera.rs

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