use serde::{Deserialize, Serialize};
use crate::error::IronError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CameraConnection {
Internal,
USB,
Network,
CSI,
Virtual,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CameraCapability {
VideoCapture,
StillCapture,
Streaming,
HardwareEncoding,
Infrared,
DepthSensing,
Autofocus,
PTZ,
Microphone,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CameraInfo {
pub name: Option<String>,
pub connection: Option<CameraConnection>,
pub device_path: String,
pub driver: String,
pub vendor: Option<String>,
pub max_width: u32,
pub max_height: u32,
pub formats: Option<Vec<String>>,
pub capabilities: Vec<CameraCapability>,
pub infrared: Option<bool>,
pub is_active: Option<bool>,
pub index: u32,
}
impl CameraInfo {
pub fn resolution(&self) -> String {
if self.max_width > 0 && self.max_height > 0 {
format!("{}x{}", self.max_width, self.max_height)
} else {
"unknown".into()
}
}
pub fn megapixels(&self) -> f64 {
(self.max_width as f64 * self.max_height as f64) / 1_000_000.0
}
}
#[cfg(target_os = "linux")]
const VIDIOC_ENUM_FMT: u32 = 0xC040_5602;
#[cfg(target_os = "linux")]
const V4L2_BUF_TYPE_VIDEO_CAPTURE: u32 = 1;
#[cfg(target_os = "linux")]
const V4L2_ENUM_FMT_LIMIT: u32 = 256;
#[cfg(target_os = "linux")]
#[repr(C)]
#[derive(Default)]
struct V4l2Fmtdesc {
index: u32,
buf_type: u32,
flags: u32,
description: [u8; 32],
pixelformat: u32,
mbus_code: u32,
reserved: [u32; 3],
}
#[cfg(target_os = "linux")]
const _: () = assert!(std::mem::size_of::<V4l2Fmtdesc>() == 64);
#[cfg(any(target_os = "linux", test))]
fn fourcc_to_string(code: u32) -> String {
String::from_utf8_lossy(&code.to_le_bytes())
.trim_end()
.to_string()
}
#[cfg(any(target_os = "linux", test))]
const LUMINANCE_FORMATS: &[&str] = &["GREY", "Y8", "Y8I", "Y10", "Y12", "Y16"];
#[cfg(any(target_os = "linux", test))]
const DEPTH_FORMATS: &[&str] = &["Z16", "INZI"];
#[cfg(any(target_os = "linux", test))]
fn infrared_from_formats(formats: Option<&[String]>) -> Option<bool> {
let formats = formats.filter(|f| !f.is_empty())?;
let is = |list: &[&str], f: &String| list.contains(&f.as_str());
if formats
.iter()
.any(|f| !is(LUMINANCE_FORMATS, f) && !is(DEPTH_FORMATS, f))
{
Some(false)
} else if formats.iter().all(|f| is(LUMINANCE_FORMATS, f)) {
Some(true)
} else {
None
}
}
pub struct CameraMonitor {
cameras: Vec<CameraInfo>,
}
impl CameraMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self {
cameras: Vec::new(),
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.cameras.clear();
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
Ok(())
}
pub fn cameras(&self) -> &[CameraInfo] {
&self.cameras
}
pub fn count(&self) -> usize {
self.cameras.len()
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), IronError> {
let v4l_path = std::path::Path::new("/sys/class/video4linux");
if !v4l_path.exists() {
return Ok(());
}
let entries = std::fs::read_dir(v4l_path)
.map_err(|e| IronError::System(format!("cannot read /sys/class/video4linux: {e}")))?;
for entry in entries.flatten() {
let dev_name = entry.file_name().to_string_lossy().to_string();
if !dev_name.starts_with("video") {
continue;
}
let index: u32 = dev_name
.strip_prefix("video")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let base = entry.path();
let name = std::fs::read_to_string(base.join("name"))
.unwrap_or_default()
.trim()
.to_string();
let uevent = std::fs::read_to_string(base.join("uevent")).unwrap_or_default();
if uevent.contains("DEVTYPE=video4linux-subdev") {
continue;
}
let driver = Self::read_sysfs_link_name(&base.join("device/driver"));
let dev_path_str = base.to_string_lossy().to_string();
let connection = if dev_path_str.contains("usb") {
Some(CameraConnection::USB)
} else if dev_path_str.contains("platform") || dev_path_str.contains("csi") {
Some(CameraConnection::CSI)
} else if name.to_lowercase().contains("virtual") || name.to_lowercase().contains("obs")
{
Some(CameraConnection::Virtual)
} else if dev_path_str.contains("pci") {
Some(CameraConnection::Internal)
} else {
None
};
let mut capabilities = vec![CameraCapability::VideoCapture];
let dev_file = format!("/dev/{}", dev_name);
let formats = Self::read_v4l2_formats(&dev_file);
if let Some(list) = &formats {
if list.iter().any(|f| f == "H264" || f == "HEVC") {
capabilities.push(CameraCapability::HardwareEncoding);
}
if list.iter().any(|f| f.contains("Z16") || f.contains("INZI")) {
capabilities.push(CameraCapability::DepthSensing);
}
}
let infrared = infrared_from_formats(formats.as_deref());
if infrared == Some(true) {
capabilities.push(CameraCapability::Infrared);
}
let vendor = Self::read_usb_vendor(&base);
self.cameras.push(CameraInfo {
name: (!name.is_empty()).then_some(name),
connection,
device_path: dev_file,
driver,
vendor,
max_width: 0, max_height: 0,
formats,
capabilities,
infrared,
is_active: Self::is_device_busy(&format!("/dev/{}", dev_name)),
index,
});
}
Ok(())
}
#[cfg(target_os = "linux")]
fn read_sysfs_link_name(path: &std::path::Path) -> String {
std::fs::read_link(path)
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
.unwrap_or_default()
}
#[cfg(target_os = "linux")]
fn read_v4l2_formats(dev: &str) -> Option<Vec<String>> {
use std::os::unix::io::AsRawFd;
let file = std::fs::OpenOptions::new().read(true).open(dev).ok()?;
let fd = file.as_raw_fd();
let mut formats = Vec::new();
for index in 0..V4L2_ENUM_FMT_LIMIT {
let mut desc = V4l2Fmtdesc {
index,
buf_type: V4L2_BUF_TYPE_VIDEO_CAPTURE,
..Default::default()
};
let rc = unsafe {
libc::ioctl(
fd,
VIDIOC_ENUM_FMT as libc::c_ulong,
&mut desc as *mut V4l2Fmtdesc,
)
};
if rc < 0 {
let end_of_list =
std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL);
return if end_of_list && index > 0 {
Some(formats)
} else {
None
};
}
formats.push(fourcc_to_string(desc.pixelformat));
}
None
}
#[cfg(target_os = "linux")]
fn read_usb_vendor(base: &std::path::Path) -> Option<String> {
let mut path = base.to_path_buf();
for _ in 0..5 {
let vendor_path = path.join("manufacturer");
if let Ok(v) = std::fs::read_to_string(&vendor_path) {
let v = v.trim();
if !v.is_empty() {
return Some(v.to_string());
}
}
if !path.pop() {
break;
}
}
None
}
#[cfg(target_os = "linux")]
fn is_device_busy(dev: &str) -> Option<bool> {
use std::fs::OpenOptions;
match OpenOptions::new().read(true).open(dev) {
Ok(_) => Some(false),
Err(e) if e.raw_os_error() == Some(16) => Some(true), Err(_) => None,
}
}
#[cfg(target_os = "windows")]
fn camera_in_use_windows() -> Option<bool> {
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
use winreg::RegKey;
const STORE: &str = concat!(
r"SOFTWARE\Microsoft\Windows\CurrentVersion",
r"\CapabilityAccessManager\ConsentStore\webcam"
);
let mut saw_a_key = false;
let mut any_open = false;
for root in [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE] {
let Ok(store) = RegKey::predef(root).open_subkey(STORE) else {
continue;
};
let mut groups = vec![store];
if let Ok(np) = groups[0].open_subkey("NonPackaged") {
groups.push(np);
}
for group in &groups {
for name in group.enum_keys().flatten() {
let Ok(app) = group.open_subkey(&name) else {
continue;
};
let Ok(stop) = app.get_value::<u64, _>("LastUsedTimeStop") else {
continue;
};
saw_a_key = true;
if stop == 0 {
any_open = true;
}
}
}
}
match (saw_a_key, any_open) {
(true, false) => Some(false),
(true, true) => None,
(false, _) => None,
}
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
let in_use = Self::camera_in_use_windows();
let json = crate::core::command::capture_json(
"powershell",
&["-NoProfile", "-Command",
"Get-CimInstance Win32_PnPEntity | Where-Object { $_.PNPClass -eq 'Camera' } | Select-Object Name, Manufacturer, DeviceID, Status, PNPClass, Service | ConvertTo-Json -Compress"],
)?;
let Some(val) = json else {
return Ok(());
};
let items = crate::core::command::json_items(&val);
for (i, item) in items.iter().enumerate() {
let name = item["Name"].as_str().map(str::to_string);
let name_lower = name.as_deref().unwrap_or("").to_lowercase();
let vendor = item["Manufacturer"]
.as_str()
.filter(|s| !s.trim().is_empty())
.map(str::to_string);
let device_id = item["DeviceID"].as_str().unwrap_or("").to_string();
let lower = device_id.to_lowercase();
let connection = if lower.contains("usb") {
Some(CameraConnection::USB)
} else if lower.contains("pci") {
Some(CameraConnection::Internal)
} else if name_lower.contains("virtual") || name_lower.contains("obs") {
Some(CameraConnection::Virtual)
} else {
None
};
self.cameras.push(CameraInfo {
name,
connection,
device_path: device_id,
driver: item["Service"].as_str().unwrap_or("").to_string(),
vendor,
max_width: 0,
max_height: 0,
formats: None,
capabilities: vec![CameraCapability::VideoCapture],
infrared: None,
is_active: in_use,
index: i as u32,
});
}
Ok(())
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), IronError> {
let text = crate::core::command::capture(
"system_profiler",
&["SPCameraDataType", "-detailLevel", "full"],
)?;
self.cameras = parse_macos_cameras(&text);
Ok(())
}
}
#[cfg(any(target_os = "macos", test))]
#[derive(Default)]
struct MacCameraBlock {
name: String,
model_id: String,
unique_id: String,
vendor: Option<String>,
}
#[cfg(any(target_os = "macos", test))]
fn parse_macos_cameras(text: &str) -> Vec<CameraInfo> {
let mut blocks: Vec<MacCameraBlock> = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
let is_attribute = ["Model ID:", "Unique ID:", "Manufacturer:"]
.iter()
.any(|key| trimmed.starts_with(key));
if trimmed.ends_with(':')
&& !is_attribute
&& !trimmed.starts_with("Camera")
&& !trimmed.is_empty()
{
blocks.push(MacCameraBlock {
name: trimmed.trim_end_matches(':').to_string(),
..Default::default()
});
} else if let Some(block) = blocks.last_mut() {
if let Some(v) = trimmed.strip_prefix("Model ID:") {
block.model_id = v.trim().to_string();
} else if let Some(v) = trimmed.strip_prefix("Unique ID:") {
block.unique_id = v.trim().to_string();
} else if let Some(v) = trimmed.strip_prefix("Manufacturer:") {
let v = v.trim();
if !v.is_empty() {
block.vendor = Some(v.to_string());
}
}
}
}
blocks
.into_iter()
.filter(|b| !b.name.is_empty())
.enumerate()
.map(|(i, b)| {
let model = b.model_id.to_lowercase();
let connection = if model.contains("usb") {
Some(CameraConnection::USB)
} else if model.contains("virtual") {
Some(CameraConnection::Virtual)
} else {
None
};
CameraInfo {
name: Some(b.name),
connection,
device_path: b.unique_id,
driver: String::new(),
vendor: b.vendor,
max_width: 0,
max_height: 0,
formats: None,
capabilities: vec![CameraCapability::VideoCapture],
infrared: None,
is_active: None,
index: i as u32,
}
})
.collect()
}
impl Default for CameraMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
cameras: Vec::new(),
})
}
}
impl std::fmt::Display for CameraConnection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Internal => write!(f, "Internal"),
Self::USB => write!(f, "USB"),
Self::Network => write!(f, "Network"),
Self::CSI => write!(f, "CSI/MIPI"),
Self::Virtual => write!(f, "Virtual"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_camera_monitor_creation() {
match CameraMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_camera_monitor_default() {
let monitor = CameraMonitor::default();
let _ = monitor.cameras();
}
#[test]
fn test_camera_info_resolution() {
let cam = CameraInfo {
name: Some("Test".into()),
connection: Some(CameraConnection::USB),
device_path: String::new(),
driver: String::new(),
vendor: None,
max_width: 1920,
max_height: 1080,
formats: None,
capabilities: Vec::new(),
infrared: None,
is_active: Some(false),
index: 0,
};
assert_eq!(cam.resolution(), "1920x1080");
assert!((cam.megapixels() - 2.0736).abs() < 0.01);
}
#[test]
fn test_camera_serialization() {
let cam = CameraInfo {
name: Some("Test Camera".into()),
connection: Some(CameraConnection::Internal),
device_path: "/dev/video0".into(),
driver: "uvcvideo".into(),
vendor: Some("Logitech".into()),
max_width: 1920,
max_height: 1080,
formats: Some(vec!["YUYV".into(), "MJPG".into()]),
capabilities: vec![CameraCapability::VideoCapture],
infrared: Some(false),
is_active: Some(false),
index: 0,
};
let json = serde_json::to_string(&cam).unwrap();
assert!(json.contains("Test Camera"));
let _: CameraInfo = serde_json::from_str(&json).unwrap();
}
#[test]
fn test_fourcc_spelling() {
assert_eq!(fourcc_to_string(0x5659_5559), "YUYV");
assert_eq!(fourcc_to_string(0x4750_4A4D), "MJPG");
assert_eq!(fourcc_to_string(0x3436_3248), "H264");
assert_eq!(fourcc_to_string(0x2036_315A), "Z16");
}
#[cfg(target_os = "linux")]
#[test]
fn test_v4l2_fmtdesc_matches_kernel_layout() {
assert_eq!(std::mem::size_of::<V4l2Fmtdesc>(), 64);
assert_eq!(std::mem::offset_of!(V4l2Fmtdesc, pixelformat), 44);
assert_eq!(VIDIOC_ENUM_FMT, 0xC040_5602);
}
const MACOS_CAMERAS: &str = concat!(
"Camera:\n",
"\n",
" FaceTime HD Camera:\n",
"\n",
" Model ID: FaceTime HD Camera\n",
" Unique ID: 3F2A0000000000000000000000000001\n",
"\n",
" Logi C920 HD Pro Webcam:\n",
"\n",
" Model ID: UVC Camera (046d:08e5) USB\n",
" Unique ID: 0x14100000046d08e5\n",
" Manufacturer: Logitech\n",
);
#[test]
fn test_macos_camera_parse_keeps_every_device_on_one_path() {
let cams = parse_macos_cameras(MACOS_CAMERAS);
assert_eq!(cams.len(), 2);
assert_eq!(cams[0].name.as_deref(), Some("FaceTime HD Camera"));
assert_eq!(cams[0].index, 0);
assert_eq!(cams[0].connection, None);
assert_eq!(cams[0].device_path, "3F2A0000000000000000000000000001");
assert_eq!(cams[1].name.as_deref(), Some("Logi C920 HD Pro Webcam"));
assert_eq!(cams[1].index, 1);
assert_eq!(cams[1].connection, Some(CameraConnection::USB));
assert_eq!(cams[1].device_path, "0x14100000046d08e5");
}
#[test]
fn test_macos_camera_vendor_is_only_what_the_output_names() {
let cams = parse_macos_cameras(MACOS_CAMERAS);
assert_eq!(cams[0].vendor, None);
assert_eq!(cams[1].vendor.as_deref(), Some("Logitech"));
}
#[test]
fn test_macos_camera_does_not_claim_autofocus() {
for cam in parse_macos_cameras(MACOS_CAMERAS) {
assert_eq!(cam.capabilities, vec![CameraCapability::VideoCapture]);
assert_eq!(cam.is_active, None);
assert_eq!(cam.infrared, None);
}
}
fn formats(list: &[&str]) -> Vec<String> {
list.iter().map(|f| f.to_string()).collect()
}
#[test]
fn test_infrared_colour_formats_mean_not_infrared() {
let f = formats(&["YUYV", "MJPG"]);
assert_eq!(infrared_from_formats(Some(&f)), Some(false));
let mixed = formats(&["GREY", "YUYV"]);
assert_eq!(infrared_from_formats(Some(&mixed)), Some(false));
}
#[test]
fn test_infrared_luminance_only_formats_mean_infrared() {
let grey = formats(&["GREY"]);
assert_eq!(infrared_from_formats(Some(&grey)), Some(true));
let y8_y16 = formats(&["Y8", "Y16"]);
assert_eq!(infrared_from_formats(Some(&y8_y16)), Some(true));
}
#[test]
fn test_infrared_depth_only_is_unknown() {
let depth = formats(&["Z16"]);
assert_eq!(infrared_from_formats(Some(&depth)), None);
let depth_and_grey = formats(&["Z16", "GREY"]);
assert_eq!(infrared_from_formats(Some(&depth_and_grey)), None);
}
#[test]
fn test_infrared_without_a_format_list_is_unknown() {
assert_eq!(infrared_from_formats(None), None);
assert_eq!(infrared_from_formats(Some(&[])), None);
}
#[test]
fn test_macos_camera_parse_of_empty_output_is_empty() {
assert!(parse_macos_cameras("Camera:\n\n").is_empty());
}
}