Skip to main content

camera/
extension.rs

1//! Stable extension surface for application-provided camera backends.
2use crate::frame::NativeWriteLease;
3use crate::{
4    BackendId, CameraFacing, CameraResult, CapturePlan, DeviceCapabilities, FrameHub, FrameLayout,
5    IdentityStability, SourceTimestamp, UsbIdentity,
6};
7use std::{fmt, sync::Arc};
8
9#[derive(Clone, Debug)]
10/// Backend-neutral device metadata returned by a custom provider.
11pub struct BackendDeviceInfo {
12    /// Backend-native identifier, unique within the provider.
13    pub native_id: String,
14    /// Human-readable name.
15    pub name: String,
16    /// Human-readable description.
17    pub description: String,
18    /// Persistence guarantee for the identifier.
19    pub stability: IdentityStability,
20    /// Physical camera facing.
21    pub facing: CameraFacing,
22    /// USB identity when available.
23    pub usb: Option<UsbIdentity>,
24}
25
26/// Behavior required by `BackendProvider`.
27pub trait BackendProvider: fmt::Debug + Send + Sync + 'static {
28    /// Returns the provider's stable, namespaced backend identifier.
29    fn id(&self) -> BackendId;
30    /// Enumerates devices without opening them.
31    fn enumerate(&self) -> CameraResult<Vec<BackendDeviceInfo>>;
32    /// Opens the device identified by an earlier enumeration result.
33    fn open(&self, native_id: &str) -> CameraResult<Box<dyn BackendDevice>>;
34}
35
36/// A device handle may keep native thread-affine objects inside its own worker.
37/// Calls are serialized by the framework and never occur on the per-frame path.
38pub trait BackendDevice: Send + 'static {
39    /// Returns capture modes and controls supported by this device.
40    fn capabilities(&self) -> CameraResult<DeviceCapabilities>;
41    /// Starts native capture and publishes frames into the supplied bounded sink.
42    fn start(&mut self, sink: FrameSink, plan: &CapturePlan) -> CameraResult<()>;
43    /// Stops native capture and releases streaming resources.
44    fn stop(&mut self) -> CameraResult<()>;
45}
46
47#[derive(Clone)]
48/// Bounded frame destination supplied to an application-provided backend.
49pub struct FrameSink {
50    hub: FrameHub,
51    session: u64,
52}
53
54impl fmt::Debug for FrameSink {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.debug_struct("FrameSink")
57            .field("session", &self.session)
58            .finish_non_exhaustive()
59    }
60}
61
62impl FrameSink {
63    pub(crate) fn begin(hub: FrameHub) -> Self {
64        let session = hub.start();
65        Self { hub, session }
66    }
67
68    /// Copies one frame into the pool and publishes it to current subscribers.
69    ///
70    /// Returns `false` when policy or pool pressure intentionally drops the frame.
71    pub fn publish_bytes(
72        &self,
73        layout: FrameLayout,
74        timestamp: Option<SourceTimestamp>,
75        bytes: &[u8],
76    ) -> CameraResult<bool> {
77        self.hub
78            .publish_native(self.session, layout, timestamp, None, &[bytes])
79    }
80
81    /// Borrows writable storage directly from the bounded frame pool.
82    pub fn writable(&self, layout: FrameLayout) -> CameraResult<WritableFrameLease> {
83        Ok(WritableFrameLease {
84            inner: Some(self.hub.writable_native(self.session, layout)?),
85        })
86    }
87
88    /// Signal that the physical stream ended unexpectedly. This wakes automatic
89    /// recovery immediately instead of waiting for the no-frame timeout.
90    pub fn disconnect(&self) {
91        self.hub.stop();
92    }
93}
94
95/// Writable storage borrowed directly from the framework's bounded frame pool.
96/// `commit` makes it immutable and visible to subscribers; dropping it returns
97/// the slot to the pool without publishing.
98pub struct WritableFrameLease {
99    inner: Option<NativeWriteLease>,
100}
101
102impl WritableFrameLease {
103    /// Returns the exact frame payload slice described by the requested layout.
104    pub fn bytes_mut(&mut self) -> &mut [u8] {
105        self.inner
106            .as_mut()
107            .expect("lease is present until commit")
108            .bytes_mut()
109    }
110
111    /// Attaches the backend's source timestamp to this frame.
112    pub fn timestamp(mut self, timestamp: SourceTimestamp) -> Self {
113        self.inner
114            .as_mut()
115            .expect("lease is present until commit")
116            .set_timestamp(timestamp);
117        self
118    }
119
120    /// Makes the completed frame immutable and visible to subscribers.
121    pub fn commit(mut self) -> CameraResult<bool> {
122        self.inner
123            .take()
124            .expect("lease is present until commit")
125            .commit()
126    }
127}
128
129pub(crate) struct RegisteredBackend {
130    pub id: BackendId,
131    pub provider: Arc<dyn BackendProvider>,
132}
133
134impl Clone for RegisteredBackend {
135    fn clone(&self) -> Self {
136        Self {
137            id: self.id.clone(),
138            provider: self.provider.clone(),
139        }
140    }
141}
142
143impl fmt::Debug for RegisteredBackend {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        f.debug_struct("RegisteredBackend")
146            .field("id", &self.id)
147            .finish_non_exhaustive()
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::{PixelFormat, PlaneLayout, SessionEvent};
155
156    fn rgb_layout() -> FrameLayout {
157        FrameLayout {
158            width: 2,
159            height: 1,
160            format: PixelFormat::Rgb8,
161            planes: vec![PlaneLayout {
162                offset: 0,
163                length: 6,
164                row_stride: 6,
165                pixel_stride: 3,
166            }],
167            color: Default::default(),
168            orientation: Default::default(),
169            bottom_up: false,
170        }
171    }
172
173    #[test]
174    fn writable_lease_uses_the_bounded_pool_and_never_overwrites_retained_frames() {
175        let hub = FrameHub::new(2);
176        let sink = FrameSink::begin(hub.clone());
177        let (events, mut receiver) = tokio::sync::broadcast::channel(4);
178        hub.set_event_sender(events);
179
180        let mut first_lease = sink.writable(rgb_layout()).unwrap();
181        first_lease.bytes_mut().fill(1);
182        assert!(first_lease.commit().unwrap());
183        let first = hub.latest().unwrap();
184
185        let mut second_lease = sink.writable(rgb_layout()).unwrap();
186        second_lease.bytes_mut().fill(2);
187        assert!(second_lease.commit().unwrap());
188        let second = hub.latest().unwrap();
189
190        assert!(matches!(
191            sink.writable(rgb_layout()),
192            Err(ref error) if error.kind() == crate::CameraErrorKind::BufferExhausted
193        ));
194        assert!(matches!(
195            receiver.try_recv().unwrap(),
196            SessionEvent::ResourcePressure { dropped_frames: 1 }
197        ));
198
199        drop(first);
200        let mut third_lease = sink.writable(rgb_layout()).unwrap();
201        third_lease.bytes_mut().fill(3);
202        assert!(third_lease.commit().unwrap());
203        assert_eq!(second.bytes(), &[2; 6]);
204        assert_eq!(hub.latest().unwrap().bytes(), &[3; 6]);
205    }
206
207    #[test]
208    fn custom_backend_can_signal_a_physical_disconnect_immediately() {
209        let hub = FrameHub::new(2);
210        let sink = FrameSink::begin(hub.clone());
211        assert!(hub.is_streaming());
212
213        sink.disconnect();
214
215        assert!(!hub.is_streaming());
216    }
217}