1use 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)]
10pub struct BackendDeviceInfo {
12 pub native_id: String,
14 pub name: String,
16 pub description: String,
18 pub stability: IdentityStability,
20 pub facing: CameraFacing,
22 pub usb: Option<UsbIdentity>,
24}
25
26pub trait BackendProvider: fmt::Debug + Send + Sync + 'static {
28 fn id(&self) -> BackendId;
30 fn enumerate(&self) -> CameraResult<Vec<BackendDeviceInfo>>;
32 fn open(&self, native_id: &str) -> CameraResult<Box<dyn BackendDevice>>;
34}
35
36pub trait BackendDevice: Send + 'static {
39 fn capabilities(&self) -> CameraResult<DeviceCapabilities>;
41 fn start(&mut self, sink: FrameSink, plan: &CapturePlan) -> CameraResult<()>;
43 fn stop(&mut self) -> CameraResult<()>;
45}
46
47#[derive(Clone)]
48pub 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 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 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 pub fn disconnect(&self) {
91 self.hub.stop();
92 }
93}
94
95pub struct WritableFrameLease {
99 inner: Option<NativeWriteLease>,
100}
101
102impl WritableFrameLease {
103 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 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 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}