1use std::ptr::NonNull;
12
13pub use crate::vision::types::CameraCaptureConfig;
14use sdl3::sys::camera::{
15 SDL_AcquireCameraFrame, SDL_Camera, SDL_CameraID, SDL_CameraPermissionState, SDL_CameraSpec,
16 SDL_CloseCamera, SDL_GetCameraFormat, SDL_GetCameraPermissionState, SDL_GetCameras,
17 SDL_OpenCamera, SDL_ReleaseCameraFrame,
18};
19use sdl3::sys::pixels::SDL_PixelFormat;
20use sdl3::sys::stdinc::SDL_free;
21use sdl3::sys::surface::SDL_Surface;
22
23use crate::runtime::RuntimeHandle;
24use crate::video::{
25 self, VideoColorInfo, VideoColorMatrix, VideoColorRange, VideoFrame, VideoFrameTiming,
26};
27use crate::{DType, Error, Matrix, Result, Runtime};
28
29const CAMERA_PIXEL_FORMAT: SDL_PixelFormat = SDL_PixelFormat::RGBA32;
32
33impl Default for CameraCaptureConfig {
34 fn default() -> Self {
35 Self {
36 device_index: 0,
37 width: 1280,
38 height: 720,
39 fps: 30,
40 }
41 }
42}
43
44pub struct CameraCapture {
53 runtime: RuntimeHandle,
54 _sdl: sdl3::Sdl,
57 _camera_subsystem: sdl3::CameraSubsystem,
58 camera: Option<NonNull<SDL_Camera>>,
59 width: u32,
60 height: u32,
61 fps_numerator: u32,
62 fps_denominator: u32,
63}
64
65impl CameraCapture {
66 pub fn open(runtime: &Runtime, config: &CameraCaptureConfig) -> Result<Self> {
80 if config.width == 0 || config.height == 0 {
81 return Err(Error::invalid_argument(
82 "camera capture extent must be non-zero",
83 ));
84 }
85 if config.fps == 0 {
86 return Err(Error::invalid_argument(
87 "camera capture frame rate must be non-zero",
88 ));
89 }
90 let sdl =
91 sdl3::init().map_err(|source| Error::backend_failure("SDL3", "initialization", source))?;
92 let subsystem = sdl
93 .camera()
94 .map_err(|source| Error::backend_failure("SDL3", "camera subsystem", source))?;
95 let camera_id = camera_id_for_index(config.device_index)?;
96 let request = SDL_CameraSpec {
97 format: CAMERA_PIXEL_FORMAT,
98 width: config.width as i32,
99 height: config.height as i32,
100 framerate_numerator: config.fps as i32,
101 framerate_denominator: 1,
102 ..Default::default()
103 };
104 let raw = unsafe { SDL_OpenCamera(camera_id, &request) };
107 let camera = NonNull::new(raw)
108 .ok_or_else(|| Error::backend_failure("SDL3", "camera open", sdl3::get_error()))?;
109 let mut actual = SDL_CameraSpec::default();
110 if !unsafe { SDL_GetCameraFormat(camera.as_ptr(), &mut actual) } {
112 let source = sdl3::get_error();
113 unsafe { SDL_CloseCamera(camera.as_ptr()) };
115 return Err(Error::backend_failure(
116 "SDL3",
117 "camera format query",
118 source,
119 ));
120 }
121 let fps_numerator = actual.framerate_numerator.max(0) as u32;
122 let fps_denominator = actual.framerate_denominator.max(0) as u32;
123 Ok(Self {
124 runtime: runtime.handle().clone(),
125 _sdl: sdl,
126 _camera_subsystem: subsystem,
127 camera: Some(camera),
128 width: actual.width.max(0) as u32,
129 height: actual.height.max(0) as u32,
130 fps_numerator: fps_numerator.max(1),
131 fps_denominator: fps_denominator.max(1),
132 })
133 }
134
135 pub fn poll(&mut self) -> Result<Option<VideoFrame>> {
147 let camera = self
148 .camera
149 .ok_or_else(|| Error::failed_precondition("CameraCapture is closed"))?;
150 let mut timestamp_ns = 0_u64;
151 let frame_ptr = unsafe { SDL_AcquireCameraFrame(camera.as_ptr(), &mut timestamp_ns) };
154 if frame_ptr.is_null() {
155 return match unsafe { SDL_GetCameraPermissionState(camera.as_ptr()) } {
157 SDL_CameraPermissionState::DENIED => Err(Error::missing_capability(
158 "camera access was denied by the platform",
159 )),
160 _ => Ok(None),
161 };
162 }
163 let result = unsafe { self.upload_surface(&*frame_ptr, timestamp_ns) };
166 unsafe { SDL_ReleaseCameraFrame(camera.as_ptr(), frame_ptr) };
168 result.map(Some)
169 }
170
171 pub fn close(&mut self) {
176 if let Some(camera) = self.camera.take() {
177 unsafe { SDL_CloseCamera(camera.as_ptr()) };
179 }
180 }
181
182 #[must_use]
184 pub const fn is_streaming(&self) -> bool {
185 self.camera.is_some()
186 }
187
188 #[must_use]
190 pub const fn width(&self) -> u32 {
191 self.width
192 }
193
194 #[must_use]
196 pub const fn height(&self) -> u32 {
197 self.height
198 }
199
200 #[must_use]
202 pub fn frame_rate(&self) -> f64 {
203 if self.fps_denominator == 0 {
204 return 0.0;
205 }
206 f64::from(self.fps_numerator) / f64::from(self.fps_denominator)
207 }
208
209 unsafe fn upload_surface(&self, surface: &SDL_Surface, timestamp_ns: u64) -> Result<VideoFrame> {
210 if surface.format != CAMERA_PIXEL_FORMAT {
211 return Err(Error::backend_failure(
212 "SDL3",
213 "camera frame format",
214 std::io::Error::other(format!("expected RGBA32, got {:?}", surface.format)),
215 ));
216 }
217 let width = usize::try_from(surface.w)
218 .map_err(|_| Error::out_of_range("camera frame width is negative"))?;
219 let height = usize::try_from(surface.h)
220 .map_err(|_| Error::out_of_range("camera frame height is negative"))?;
221 let pitch = usize::try_from(surface.pitch)
222 .map_err(|_| Error::out_of_range("camera frame pitch is negative"))?;
223 if surface.pixels.is_null() || width == 0 || height == 0 {
224 return Err(Error::data_loss("camera produced an empty frame"));
225 }
226 let row_bytes = width
227 .checked_mul(4)
228 .ok_or_else(|| Error::out_of_range("camera frame row size overflows"))?;
229 if pitch < row_bytes {
230 return Err(Error::data_loss(
231 "camera frame pitch is smaller than its RGBA8 row",
232 ));
233 }
234 let source_len = pitch
237 .checked_mul(height)
238 .ok_or_else(|| Error::out_of_range("camera surface byte count overflows"))?;
239 let source = unsafe { std::slice::from_raw_parts(surface.pixels.cast::<u8>(), source_len) };
240 let rgba = if pitch == row_bytes {
241 source.to_vec()
242 } else {
243 let mut packed = Vec::with_capacity(row_bytes * height);
244 for row in source.chunks_exact(pitch) {
245 packed.extend_from_slice(&row[..row_bytes]);
246 }
247 packed
248 };
249 let element_count = width
250 .checked_mul(height)
251 .and_then(|pixels| pixels.checked_mul(4))
252 .ok_or_else(|| Error::out_of_range("camera frame byte count overflows"))?;
253 let data = Matrix::allocate(
254 &self.runtime,
255 vec![height, width, 4],
256 element_count,
257 DType::U8,
258 )?;
259 data.write_values(&rgba)?;
260 let texture = crate::render::texture_from_matrix(data, width, height)?;
261 let duration_micros =
262 u64::from(self.fps_denominator).saturating_mul(1_000_000) / u64::from(self.fps_numerator);
263 let timing = VideoFrameTiming::new_from_microseconds(timestamp_ns / 1_000, duration_micros);
264 video::from_texture(
265 &texture,
266 timing,
267 VideoColorInfo::new(VideoColorMatrix::Bt709, VideoColorRange::Full),
268 )
269 }
270}
271
272#[cfg(test)]
273#[path = "../../../../test/rs/vision/camera_unit.rs"]
274mod tests;
275
276impl Drop for CameraCapture {
277 fn drop(&mut self) {
278 self.close();
279 }
280}
281
282fn camera_id_for_index(index: u32) -> Result<SDL_CameraID> {
283 let mut count = 0_i32;
284 let list = unsafe { SDL_GetCameras(&mut count) };
287 if list.is_null() {
288 let source = sdl3::get_error();
289 return if source.is_empty() {
290 Err(Error::missing_capability("no camera devices are present"))
291 } else {
292 Err(Error::backend_failure("SDL3", "camera enumeration", source))
293 };
294 }
295 let ids = unsafe { std::slice::from_raw_parts(list, count.max(0) as usize) };
297 let found = ids.get(index as usize).copied();
298 unsafe { SDL_free(list.cast()) };
300 found.ok_or_else(|| {
301 Error::invalid_argument(format!(
302 "camera device index {index} exceeds the {count} enumerated devices"
303 ))
304 })
305}