Skip to main content

oa/vision/
camera.rs

1//! Camera capture sessions producing runtime-owned RGBA8 video frames.
2//!
3//! Donor: `source/cpp/include/oa/vision/cameraCapture.h` and
4//! `source/cpp/lib/oa/vision/capture/cameraCapture.cpp`.
5//!
6//! This slice owns the donor's SDL capture route: frames arrive as SDL
7//! surfaces, are repacked into RGBA8, and upload into packed textures through
8//! the session's Runtime. The V4L2 MMAP/DMA-BUF zero-copy ring and reconnect
9//! policy remain a later slice gated on external-memory admission.
10
11use 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
29// RGBA32 names byte order; RGBA8888 names a packed integer and reverses the
30// channels on little-endian hosts. Match the donor's SDL_PIXELFORMAT_RGBA32.
31const 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
44/// Stateful camera capture session over SDL's camera backend.
45///
46/// `poll` acquires the newest queued frame, uploads it into an owned RGBA8
47/// texture, and returns it as a [`VideoFrame`]; the SDL surface is released
48/// immediately, so no ring-slot release contract exists on this route. The
49/// returned frame's presentation timestamp is the camera's hardware capture
50/// timestamp in microseconds and its duration follows the negotiated frame
51/// rate.
52pub struct CameraCapture {
53	runtime: RuntimeHandle,
54	// SDL lifetime owners: dropping the subsystem deinitializes the camera
55	// backend, and dropping the context runs SDL_Quit when it is the last.
56	_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	/// Open the selected camera and negotiate the closest supported format.
67	///
68	/// The session requests RGBA32 output so no pixel conversion happens
69	/// outside SDL. On platforms with a camera permission gate the camera opens
70	/// before approval; `poll` reports [`ErrorKind::MissingCapability`] when the
71	/// user denies access and `None` while approval is pending.
72	///
73	/// # Errors
74	///
75	/// Returns an error for a zero extent, when no camera device matches
76	/// `device_index`, or when SDL cannot open or describe the device.
77	///
78	/// [`ErrorKind::MissingCapability`]: crate::ErrorKind::MissingCapability
79	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		// SAFETY: `request` outlives the call; ownership of a non-null camera
105		// moves into the session.
106		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		// SAFETY: `camera` was just opened and `actual` is a valid out pointer.
111		if !unsafe { SDL_GetCameraFormat(camera.as_ptr(), &mut actual) } {
112			let source = sdl3::get_error();
113			// SAFETY: the camera was opened above and is not yet owned.
114			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	/// Acquire and upload the newest queued camera frame.
136	///
137	/// Returns `Ok(None)` when the camera has not produced another frame yet —
138	/// this is also the steady state while a platform permission request is
139	/// pending. Callers drive this in their own pacing loop; `poll` never
140	/// blocks.
141	///
142	/// # Errors
143	///
144	/// Returns an error after close, when camera access was denied, for an
145	/// unexpected frame layout, or when the texture upload fails.
146	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		// SAFETY: `camera` is open and `timestamp_ns` is a valid out pointer;
152		// a non-null surface is released below before returning.
153		let frame_ptr = unsafe { SDL_AcquireCameraFrame(camera.as_ptr(), &mut timestamp_ns) };
154		if frame_ptr.is_null() {
155			// SAFETY: the camera is open.
156			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		// SAFETY: SDL returns a live surface until released; reading its pixels
164		// and releasing it both happen before this function returns.
165		let result = unsafe { self.upload_surface(&*frame_ptr, timestamp_ns) };
166		// SAFETY: `frame_ptr` came from SDL_AcquireCameraFrame above.
167		unsafe { SDL_ReleaseCameraFrame(camera.as_ptr(), frame_ptr) };
168		result.map(Some)
169	}
170
171	/// Close the session and release the camera.
172	///
173	/// Frames already returned remain owned by their callers; SDL surfaces are
174	/// released eagerly at `poll` time so nothing is deferred to close.
175	pub fn close(&mut self) {
176		if let Some(camera) = self.camera.take() {
177			// SAFETY: the session owns this opened camera.
178			unsafe { SDL_CloseCamera(camera.as_ptr()) };
179		}
180	}
181
182	/// Return whether the session still owns an open camera.
183	#[must_use]
184	pub const fn is_streaming(&self) -> bool {
185		self.camera.is_some()
186	}
187
188	/// Return the negotiated frame width in pixels.
189	#[must_use]
190	pub const fn width(&self) -> u32 {
191		self.width
192	}
193
194	/// Return the negotiated frame height in pixels.
195	#[must_use]
196	pub const fn height(&self) -> u32 {
197		self.height
198	}
199
200	/// Return the negotiated frame rate, or `0.0` when the device reported none.
201	#[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		// SAFETY: SDL owns `surface` for this call and guarantees `pitch * h`
235		// readable bytes for a live camera frame.
236		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	// SAFETY: `count` is a valid out pointer; the returned array is SDL-owned
285	// and freed below.
286	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	// SAFETY: SDL guarantees `count` entries in the returned allocation.
296	let ids = unsafe { std::slice::from_raw_parts(list, count.max(0) as usize) };
297	let found = ids.get(index as usize).copied();
298	// SAFETY: `list` was returned by SDL_GetCameras and is freed exactly once.
299	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}