BlueGit

ict rusty-teams

fix(linux): list only camera nodes that can capture (#102)

Co-authored-by: Daniel Däschle <daniel.daeschle@gmail.com>

metis Joe Mild · pushed by metis

Authored 2026-11-25 · 6 days ago

Hash
befd73a1d828ae0186c0d5cf1844ccf8ba71561d
Parent
a0a3165f
3 files changed +169 −24
Cargo.lock +1 −0
@@ -1217,6 +1217,7 @@ dependencies = [
1217 1217 "flate2",
1218 1218 "futures-util",
1219 1219 "image",
1220 "libc",
1220 1221 "libwebrtc",
1221 1222 "ndarray",
1222 1223 "nokhwa",
@@ -1217,6 +1217,7 @@ dependencies = [
1217 "flate2",
1217 "flate2",
1218 "futures-util",
1218 "futures-util",
1219 "image",
1219 "image",
1220 "libc",
1220 "libwebrtc",
1221 "libwebrtc",
1221 "ndarray",
1222 "ndarray",
1222 "nokhwa",
1223 "nokhwa",
crates/calling/Cargo.toml +3 −0
@@ -28,6 +28,9 @@ tract-onnx = "0.23"
28 28 tokio.workspace = true
29 29 uuid.workspace = true
30 30
31 [target.'cfg(target_os = "linux")'.dependencies]
32 libc = "0.2"
33
31 34 [target.'cfg(not(windows))'.dependencies]
32 35 ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }
33 36
@@ -28,6 +28,9 @@ tract-onnx = "0.23"
28tokio.workspace = true
28tokio.workspace = true
29uuid.workspace = true
29uuid.workspace = true
30
30
31[target.'cfg(target_os = "linux")'.dependencies]
32libc = "0.2"
33
31[target.'cfg(not(windows))'.dependencies]
34[target.'cfg(not(windows))'.dependencies]
32ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }
35ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }
33
36
crates/calling/src/camera.rs +165 −24
@@ -105,33 +105,113 @@ impl CameraCaptureStats {
105 105 }
106 106
107 107 pub fn list_cameras() -> Vec<CameraDevice> {
108 query(ApiBackend::Auto)
109 .unwrap_or_default()
108 query_camera_infos()
110 109 .into_iter()
111 .map(|info| {
112 let fallback_key = match info.index() {
113 CameraIndex::Index(number) => number.to_string(),
114 CameraIndex::String(text) => text.clone(),
115 };
116 #[cfg(windows)]
117 let key = {
118 let misc = info.misc();
119 if misc.trim().is_empty() {
120 fallback_key
121 } else {
122 misc
123 }
124 };
125 #[cfg(not(windows))]
126 let key = fallback_key;
127 CameraDevice {
128 key,
129 name: info.human_name(),
130 }
131 })
110 .map(camera_device)
132 111 .collect()
133 112 }
134 113
114 fn camera_device(info: nokhwa::utils::CameraInfo) -> CameraDevice {
115 let fallback_key = match info.index() {
116 CameraIndex::Index(number) => number.to_string(),
117 CameraIndex::String(text) => text.clone(),
118 };
119 #[cfg(windows)]
120 let key = {
121 let misc = info.misc();
122 if misc.trim().is_empty() {
123 fallback_key
124 } else {
125 misc
126 }
127 };
128 #[cfg(not(windows))]
129 let key = fallback_key;
130 CameraDevice {
131 key,
132 name: info.human_name(),
133 }
134 }
135
136 fn query_camera_infos() -> Vec<nokhwa::utils::CameraInfo> {
137 let queried = query(ApiBackend::Auto).unwrap_or_default();
138 #[cfg(target_os = "linux")]
139 {
140 return queried.into_iter().filter(linux_keeps_camera).collect();
141 }
142 #[cfg(not(target_os = "linux"))]
143 queried
144 }
145
146 /// Keep a node unless we know it cannot capture video. Unknown stays listed.
147 #[cfg(any(target_os = "linux", test))]
148 fn keeps_when_capture_known(captures: Option<bool>) -> bool {
149 captures.unwrap_or(true)
150 }
151
152 #[cfg(any(target_os = "linux", test))]
153 fn captures_from_querycap(capabilities: u32, device_caps: u32) -> bool {
154 const VIDEO_CAPTURE: u32 = 0x0000_0001;
155 const DEVICE_CAPS: u32 = 0x8000_0000;
156 let caps = if capabilities & DEVICE_CAPS != 0 {
157 device_caps
158 } else {
159 capabilities
160 };
161 caps & VIDEO_CAPTURE != 0
162 }
163
164 #[cfg(test)]
165 fn first_listed_index(nodes: &[(u32, Option<bool>)]) -> u32 {
166 nodes
167 .iter()
168 .find(|(_, captures)| keeps_when_capture_known(*captures))
169 .map(|(index, _)| *index)
170 .unwrap_or(0)
171 }
172
173 #[cfg(target_os = "linux")]
174 fn linux_keeps_camera(info: &nokhwa::utils::CameraInfo) -> bool {
175 let CameraIndex::Index(number) = info.index() else {
176 return true;
177 };
178 keeps_when_capture_known(node_captures_video(*number))
179 }
180
181 #[cfg(target_os = "linux")]
182 fn node_captures_video(index: u32) -> Option<bool> {
183 let path = std::ffi::CString::new(format!("/dev/video{index}")).ok()?;
184 // QUERYCAP does not need write access. O_RDWR hides a metadata node the
185 // user can read but not write, and that node then stays in the list.
186 let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_NONBLOCK) };
187 if fd < 0 {
188 return None;
189 }
190 let mut caps = V4l2Capability::default();
191 let rc = unsafe { libc::ioctl(fd, V4L2_QUERYCAP, &mut caps) };
192 unsafe { libc::close(fd) };
193 if rc < 0 {
194 return None;
195 }
196 Some(captures_from_querycap(caps.capabilities, caps.device_caps))
197 }
198
199 #[cfg(target_os = "linux")]
200 const V4L2_QUERYCAP: libc::c_ulong = 0x8068_5600;
201
202 #[cfg(target_os = "linux")]
203 #[repr(C)]
204 #[derive(Default)]
205 struct V4l2Capability {
206 driver: [u8; 16],
207 card: [u8; 32],
208 bus_info: [u8; 32],
209 version: u32,
210 capabilities: u32,
211 device_caps: u32,
212 reserved: [u32; 3],
213 }
214
135 215 fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {
136 216 #[cfg(windows)]
137 217 {
@@ -191,7 +271,10 @@ fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {
191 271 #[cfg(not(windows))]
192 272 {
193 273 let index = match choice {
194 DeviceChoice::SystemDefault => CameraIndex::Index(0),
274 DeviceChoice::SystemDefault => query_camera_infos()
275 .first()
276 .map(|info| info.index().clone())
277 .unwrap_or(CameraIndex::Index(0)),
195 278 DeviceChoice::Device(key) => key
196 279 .parse()
197 280 .map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
@@ -736,6 +819,64 @@ mod tests {
736 819 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
737 820 }
738 821
822 #[test]
823 fn linux_metadata_node_is_dropped_and_same_name_capture_stays() {
824 let devices = [
825 CameraDevice {
826 key: "0".into(),
827 name: "Logitech Webcam C930e".into(),
828 },
829 CameraDevice {
830 key: "1".into(),
831 name: "Logitech Webcam C930e".into(),
832 },
833 ];
834 let caps = [
835 Some(captures_from_querycap(0x84a0_0001, 0x0420_0001)),
836 Some(captures_from_querycap(0x84a0_0001, 0x04a0_0000)),
837 ];
838 let listed: Vec<_> = devices
839 .into_iter()
840 .zip(caps)
841 .filter(|(_, captures)| keeps_when_capture_known(*captures))
842 .map(|(device, _)| device)
843 .collect();
844 assert_eq!(listed.len(), 1);
845 assert_eq!(listed[0].key, "0");
846 assert_eq!(listed[0].name, "Logitech Webcam C930e");
847 assert!(keeps_when_capture_known(None));
848 }
849
850 #[test]
851 fn system_default_uses_the_first_remaining_capture_node() {
852 assert_eq!(first_listed_index(&[(0, Some(false)), (1, Some(true))]), 1);
853 let (index, _) = resolve_camera(&DeviceChoice::SystemDefault);
854 let expected = list_cameras()
855 .first()
856 .map(|camera| {
857 camera.key.parse().map_or_else(
858 |_| CameraIndex::String(camera.key.clone()),
859 CameraIndex::Index,
860 )
861 })
862 .unwrap_or(CameraIndex::Index(0));
863 assert_eq!(index, expected);
864 }
865
866 #[cfg(target_os = "linux")]
867 #[test]
868 fn this_machine_lists_one_c930e_capture_node() {
869 let logitech: Vec<_> = list_cameras()
870 .into_iter()
871 .filter(|camera| camera.name.contains("C930e"))
872 .collect();
873 if logitech.is_empty() {
874 return;
875 }
876 assert_eq!(logitech.len(), 1);
877 assert_eq!(logitech[0].key, "0");
878 }
879
739 880 #[test]
740 881 fn yuyv_converts_to_i420_with_averaged_chroma() {
741 882 let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60];
@@ -105,33 +105,113 @@ impl CameraCaptureStats {
105}
105}
106
106
107pub fn list_cameras() -> Vec<CameraDevice> {
107pub fn list_cameras() -> Vec<CameraDevice> {
108 query(ApiBackend::Auto)
108 query_camera_infos()
109 .unwrap_or_default()
110 .into_iter()
109 .into_iter()
111 .map(|info| {
110 .map(camera_device)
112 let fallback_key = match info.index() {
113 CameraIndex::Index(number) => number.to_string(),
114 CameraIndex::String(text) => text.clone(),
115 };
116 #[cfg(windows)]
117 let key = {
118 let misc = info.misc();
119 if misc.trim().is_empty() {
120 fallback_key
121 } else {
122 misc
123 }
124 };
125 #[cfg(not(windows))]
126 let key = fallback_key;
127 CameraDevice {
128 key,
129 name: info.human_name(),
130 }
131 })
132 .collect()
111 .collect()
133}
112}
134
113
114fn camera_device(info: nokhwa::utils::CameraInfo) -> CameraDevice {
115 let fallback_key = match info.index() {
116 CameraIndex::Index(number) => number.to_string(),
117 CameraIndex::String(text) => text.clone(),
118 };
119 #[cfg(windows)]
120 let key = {
121 let misc = info.misc();
122 if misc.trim().is_empty() {
123 fallback_key
124 } else {
125 misc
126 }
127 };
128 #[cfg(not(windows))]
129 let key = fallback_key;
130 CameraDevice {
131 key,
132 name: info.human_name(),
133 }
134}
135
136fn query_camera_infos() -> Vec<nokhwa::utils::CameraInfo> {
137 let queried = query(ApiBackend::Auto).unwrap_or_default();
138 #[cfg(target_os = "linux")]
139 {
140 return queried.into_iter().filter(linux_keeps_camera).collect();
141 }
142 #[cfg(not(target_os = "linux"))]
143 queried
144}
145
146/// Keep a node unless we know it cannot capture video. Unknown stays listed.
147#[cfg(any(target_os = "linux", test))]
148fn keeps_when_capture_known(captures: Option<bool>) -> bool {
149 captures.unwrap_or(true)
150}
151
152#[cfg(any(target_os = "linux", test))]
153fn captures_from_querycap(capabilities: u32, device_caps: u32) -> bool {
154 const VIDEO_CAPTURE: u32 = 0x0000_0001;
155 const DEVICE_CAPS: u32 = 0x8000_0000;
156 let caps = if capabilities & DEVICE_CAPS != 0 {
157 device_caps
158 } else {
159 capabilities
160 };
161 caps & VIDEO_CAPTURE != 0
162}
163
164#[cfg(test)]
165fn first_listed_index(nodes: &[(u32, Option<bool>)]) -> u32 {
166 nodes
167 .iter()
168 .find(|(_, captures)| keeps_when_capture_known(*captures))
169 .map(|(index, _)| *index)
170 .unwrap_or(0)
171}
172
173#[cfg(target_os = "linux")]
174fn linux_keeps_camera(info: &nokhwa::utils::CameraInfo) -> bool {
175 let CameraIndex::Index(number) = info.index() else {
176 return true;
177 };
178 keeps_when_capture_known(node_captures_video(*number))
179}
180
181#[cfg(target_os = "linux")]
182fn node_captures_video(index: u32) -> Option<bool> {
183 let path = std::ffi::CString::new(format!("/dev/video{index}")).ok()?;
184 // QUERYCAP does not need write access. O_RDWR hides a metadata node the
185 // user can read but not write, and that node then stays in the list.
186 let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_NONBLOCK) };
187 if fd < 0 {
188 return None;
189 }
190 let mut caps = V4l2Capability::default();
191 let rc = unsafe { libc::ioctl(fd, V4L2_QUERYCAP, &mut caps) };
192 unsafe { libc::close(fd) };
193 if rc < 0 {
194 return None;
195 }
196 Some(captures_from_querycap(caps.capabilities, caps.device_caps))
197}
198
199#[cfg(target_os = "linux")]
200const V4L2_QUERYCAP: libc::c_ulong = 0x8068_5600;
201
202#[cfg(target_os = "linux")]
203#[repr(C)]
204#[derive(Default)]
205struct V4l2Capability {
206 driver: [u8; 16],
207 card: [u8; 32],
208 bus_info: [u8; 32],
209 version: u32,
210 capabilities: u32,
211 device_caps: u32,
212 reserved: [u32; 3],
213}
214
135fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {
215fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {
136 #[cfg(windows)]
216 #[cfg(windows)]
137 {
217 {
@@ -191,7 +271,10 @@ fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {
191 #[cfg(not(windows))]
271 #[cfg(not(windows))]
192 {
272 {
193 let index = match choice {
273 let index = match choice {
194 DeviceChoice::SystemDefault => CameraIndex::Index(0),
274 DeviceChoice::SystemDefault => query_camera_infos()
275 .first()
276 .map(|info| info.index().clone())
277 .unwrap_or(CameraIndex::Index(0)),
195 DeviceChoice::Device(key) => key
278 DeviceChoice::Device(key) => key
196 .parse()
279 .parse()
197 .map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
280 .map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
@@ -736,6 +819,64 @@ mod tests {
736 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
819 assert_eq!(entries[1].choice, DeviceChoice::Device("0".into()));
737 }
820 }
738
821
822 #[test]
823 fn linux_metadata_node_is_dropped_and_same_name_capture_stays() {
824 let devices = [
825 CameraDevice {
826 key: "0".into(),
827 name: "Logitech Webcam C930e".into(),
828 },
829 CameraDevice {
830 key: "1".into(),
831 name: "Logitech Webcam C930e".into(),
832 },
833 ];
834 let caps = [
835 Some(captures_from_querycap(0x84a0_0001, 0x0420_0001)),
836 Some(captures_from_querycap(0x84a0_0001, 0x04a0_0000)),
837 ];
838 let listed: Vec<_> = devices
839 .into_iter()
840 .zip(caps)
841 .filter(|(_, captures)| keeps_when_capture_known(*captures))
842 .map(|(device, _)| device)
843 .collect();
844 assert_eq!(listed.len(), 1);
845 assert_eq!(listed[0].key, "0");
846 assert_eq!(listed[0].name, "Logitech Webcam C930e");
847 assert!(keeps_when_capture_known(None));
848 }
849
850 #[test]
851 fn system_default_uses_the_first_remaining_capture_node() {
852 assert_eq!(first_listed_index(&[(0, Some(false)), (1, Some(true))]), 1);
853 let (index, _) = resolve_camera(&DeviceChoice::SystemDefault);
854 let expected = list_cameras()
855 .first()
856 .map(|camera| {
857 camera.key.parse().map_or_else(
858 |_| CameraIndex::String(camera.key.clone()),
859 CameraIndex::Index,
860 )
861 })
862 .unwrap_or(CameraIndex::Index(0));
863 assert_eq!(index, expected);
864 }
865
866 #[cfg(target_os = "linux")]
867 #[test]
868 fn this_machine_lists_one_c930e_capture_node() {
869 let logitech: Vec<_> = list_cameras()
870 .into_iter()
871 .filter(|camera| camera.name.contains("C930e"))
872 .collect();
873 if logitech.is_empty() {
874 return;
875 }
876 assert_eq!(logitech.len(), 1);
877 assert_eq!(logitech[0].key, "0");
878 }
879
739 #[test]
880 #[test]
740 fn yuyv_converts_to_i420_with_averaged_chroma() {
881 fn yuyv_converts_to_i420_with_averaged_chroma() {
741 let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60];
882 let row_a = [10u8, 100, 20, 200, 30, 50, 40, 60];