Skip to main content

camera/
traits.rs

1//! Simplified camera interface definitions.
2//!
3//! The interfaces focus on two core capabilities:
4//! 1. Querying supported camera configurations.
5//! 2. Processing asynchronous video streams.
6
7use crate::pixels::Pixels as Array3;
8use crate::{
9    CameraConfig, CameraControlRange, CameraControlType, CameraControlValue, CameraDeviceInfo,
10    CameraResult,
11};
12use std::time::Duration;
13
14/// Simplified camera management interface.
15pub trait CameraManager {
16    /// Lists all available camera devices.
17    fn list_devices() -> CameraResult<Vec<CameraDeviceInfo>>;
18
19    /// Returns the configurations supported by a device.
20    fn get_supported_configs(device_index: u32) -> CameraResult<Vec<CameraConfig>>;
21
22    /// Checks whether a device supports a specific configuration.
23    fn is_config_supported(device_index: u32, config: &CameraConfig) -> CameraResult<bool>;
24}
25
26/// Streaming camera interface backed by a ring buffer.
27#[allow(async_fn_in_trait)]
28pub trait StreamingCamera: Send + Sync {
29    /// Shared snapshots supplied by native callback/worker backends.
30    fn frame_hub(&self) -> Option<&crate::FrameHub> {
31        None
32    }
33
34    fn get_shared_frame(&self) -> CameraResult<Option<std::sync::Arc<crate::CapturedFrame>>> {
35        self.frame_hub().map(|hub| hub.latest()).ok_or_else(|| {
36            crate::CameraError::stream_error("Shared frames unavailable for this backend".into())
37        })
38    }
39
40    async fn wait_for_shared_frame(
41        &self,
42        after: Option<crate::FrameKey>,
43        timeout: Duration,
44    ) -> CameraResult<std::sync::Arc<crate::CapturedFrame>> {
45        self.frame_hub()
46            .ok_or_else(|| {
47                crate::CameraError::stream_error(
48                    "Shared frames unavailable for this backend".into(),
49                )
50            })?
51            .wait_after(after, timeout)
52            .await
53    }
54    /// Starts the asynchronous video stream.
55    ///
56    /// Once started, frames are captured in the background and stored in the ring buffer.
57    async fn start_stream(&self, config: CameraConfig) -> CameraResult<()>;
58
59    /// Stops the video stream.
60    async fn stop_stream(&self) -> CameraResult<()>;
61
62    /// Returns the latest frame immediately without blocking.
63    ///
64    /// Returns `None` when the buffer is empty.
65    /// The returned `Array3<u8>` contains RGB data shaped as `(height, width, 3)`.
66    fn get_latest_frame(&self) -> CameraResult<Option<Array3<u8>>>;
67
68    /// Waits for the next frame until the timeout expires.
69    /// The returned `Array3<u8>` contains RGB data shaped as `(height, width, 3)`.
70    async fn wait_for_frame(&self, timeout: Duration) -> CameraResult<Array3<u8>>;
71
72    /// Returns whether the stream is running.
73    fn is_streaming(&self) -> bool;
74
75    /// Returns the current configuration.
76    fn get_config(&self) -> Option<CameraConfig>;
77
78    /// Returns stream statistics.
79    fn get_stats(&self) -> StreamStats;
80
81    /// Sets the buffer size by reconfiguring the ring buffer.
82    async fn set_buffer_size(&self, size: usize) -> CameraResult<()>;
83}
84
85/// Stream statistics.
86#[derive(Debug, Clone, Default)]
87pub struct StreamStats {
88    /// Total number of captured frames.
89    pub total_frames: u64,
90    /// Number of frames dropped because the buffer was full.
91    pub dropped_frames: u64,
92    /// Current frame rate.
93    pub current_fps: f64,
94    /// Current buffer capacity.
95    pub buffer_size: usize,
96    /// Current number of frames in the buffer.
97    pub buffered_frames: usize,
98    /// Running time in seconds.
99    pub uptime_seconds: u64,
100}
101
102impl StreamStats {
103    /// Calculates the frame drop ratio.
104    pub fn drop_rate(&self) -> f64 {
105        if self.total_frames == 0 {
106            0.0
107        } else {
108            self.dropped_frames as f64 / self.total_frames as f64
109        }
110    }
111
112    /// Calculates buffer utilization.
113    pub fn buffer_usage(&self) -> f64 {
114        if self.buffer_size == 0 {
115            0.0
116        } else {
117            self.buffered_frames as f64 / self.buffer_size as f64
118        }
119    }
120}
121
122// ============================================================================
123// Camera control interface.
124// ============================================================================
125
126/// Camera control parameter interface.
127#[allow(async_fn_in_trait)]
128pub trait CameraControl {
129    /// Returns the current value of the specified control.
130    fn get_control(&self, control: CameraControlType) -> CameraResult<CameraControlValue>;
131
132    /// Sets the specified control value.
133    fn set_control(
134        &self,
135        control: CameraControlType,
136        value: CameraControlValue,
137    ) -> CameraResult<()>;
138
139    /// Returns the valid range for the specified control.
140    fn get_control_range(&self, control: CameraControlType) -> CameraResult<CameraControlRange>;
141
142    /// Checks whether the device supports the specified control.
143    fn supports_control(&self, control: CameraControlType) -> bool;
144
145    /// Returns all controls supported by the device.
146    fn get_supported_controls(&self) -> Vec<CameraControlType>;
147
148    /// Resets the specified control to its default value.
149    fn reset_control(&self, control: CameraControlType) -> CameraResult<()> {
150        let range = self.get_control_range(control)?;
151        self.set_control(control, CameraControlValue::manual(range.default))
152    }
153
154    /// Resets all controls to their default values.
155    fn reset_all_controls(&self) -> CameraResult<()> {
156        let mut failures = Vec::new();
157        for control in self.get_supported_controls() {
158            if let Err(error) = self.reset_control(control) {
159                failures.push(std::sync::Arc::new(
160                    error.with_operation(format!("{control:?}")),
161                ));
162            }
163        }
164        if failures.is_empty() {
165            Ok(())
166        } else {
167            Err(crate::CameraError::control_batch(failures))
168        }
169    }
170}
171
172#[cfg(test)]
173mod camera_control_tests {
174    use super::*;
175
176    #[test]
177    fn test_stream_stats_default() {
178        let stats = StreamStats::default();
179        assert_eq!(stats.total_frames, 0);
180        assert_eq!(stats.dropped_frames, 0);
181        assert_eq!(stats.current_fps, 0.0);
182        assert_eq!(stats.buffer_size, 0);
183        assert_eq!(stats.buffered_frames, 0);
184        assert_eq!(stats.uptime_seconds, 0);
185    }
186
187    #[test]
188    fn test_stream_stats_drop_rate() {
189        let mut stats = StreamStats::default();
190
191        // No captured frames means a zero drop ratio.
192        assert_eq!(stats.drop_rate(), 0.0);
193
194        // Captured frames with no drops.
195        stats.total_frames = 100;
196        stats.dropped_frames = 0;
197        assert_eq!(stats.drop_rate(), 0.0);
198
199        // Some captured frames were dropped.
200        stats.dropped_frames = 10;
201        assert_eq!(stats.drop_rate(), 0.1);
202
203        // Every captured frame was dropped.
204        stats.dropped_frames = 100;
205        assert_eq!(stats.drop_rate(), 1.0);
206    }
207
208    #[test]
209    fn test_stream_stats_buffer_usage() {
210        let mut stats = StreamStats::default();
211
212        // No buffer means zero utilization.
213        assert_eq!(stats.buffer_usage(), 0.0);
214
215        // Empty buffer.
216        stats.buffer_size = 10;
217        stats.buffered_frames = 0;
218        assert_eq!(stats.buffer_usage(), 0.0);
219
220        // Half-full buffer.
221        stats.buffered_frames = 5;
222        assert_eq!(stats.buffer_usage(), 0.5);
223
224        // Full buffer.
225        stats.buffered_frames = 10;
226        assert_eq!(stats.buffer_usage(), 1.0);
227    }
228
229    #[test]
230    fn test_stream_stats_calculations() {
231        let stats = StreamStats {
232            total_frames: 1000,
233            dropped_frames: 50,
234            current_fps: 29.5,
235            buffer_size: 20,
236            buffered_frames: 15,
237            uptime_seconds: 60,
238        };
239
240        assert_eq!(stats.drop_rate(), 0.05);
241        assert_eq!(stats.buffer_usage(), 0.75);
242    }
243}