1use crate::{
3 CameraConfig, CameraError, CameraResult, DeliveryPolicy, FrameRate, MemoryBudget,
4 OverflowPolicy, PixelFormat, VideoFormat,
5};
6use std::{borrow::Cow, fmt, str::FromStr, time::Duration};
7
8#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub struct BackendId(Cow<'static, str>);
11
12impl BackendId {
13 pub const UVC: Self = Self::builtin("uvc");
15 pub const V4L2: Self = Self::builtin("v4l2");
17 pub const AV_FOUNDATION: Self = Self::builtin("avfoundation");
19 pub const CAMERA2: Self = Self::builtin("camera2");
21 pub const MEDIA_FOUNDATION: Self = Self::builtin("media-foundation");
23 pub const SYNTHETIC: Self = Self::builtin("synthetic");
25
26 const fn builtin(value: &'static str) -> Self {
27 Self(Cow::Borrowed(value))
29 }
30
31 pub fn custom(namespace: &str, name: &str) -> CameraResult<Self> {
35 fn valid(part: &str) -> bool {
36 !part.is_empty()
37 && part.len() <= 96
38 && part
39 .bytes()
40 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
41 }
42 if !valid(namespace) || !valid(name) {
43 return Err(CameraError::invalid_config(
44 "Backend namespace and name must be non-empty ASCII identifiers".into(),
45 ));
46 }
47 Ok(Self(Cow::Owned(format!("{namespace}/{name}"))))
48 }
49
50 pub fn as_str(&self) -> &str {
52 &self.0
53 }
54
55 #[allow(dead_code)]
56 pub(crate) fn from_builtin(value: &'static str) -> Self {
57 Self(Cow::Borrowed(value))
58 }
59}
60
61impl fmt::Display for BackendId {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 f.write_str(self.as_str())
64 }
65}
66
67impl FromStr for BackendId {
68 type Err = CameraError;
69
70 fn from_str(value: &str) -> Result<Self, Self::Err> {
71 match value {
72 "uvc" => Ok(Self::UVC),
73 "v4l2" => Ok(Self::V4L2),
74 "avfoundation" => Ok(Self::AV_FOUNDATION),
75 "camera2" => Ok(Self::CAMERA2),
76 "media-foundation" => Ok(Self::MEDIA_FOUNDATION),
77 "synthetic" => Ok(Self::SYNTHETIC),
78 _ => {
79 let (namespace, name) = value.split_once('/').ok_or_else(|| {
80 CameraError::invalid_config("Invalid backend identifier".into())
81 })?;
82 Self::custom(namespace, name)
83 }
84 }
85 }
86}
87
88#[cfg(feature = "serde")]
89impl serde::Serialize for BackendId {
90 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
91 where
92 S: serde::Serializer,
93 {
94 serializer.serialize_str(self.as_str())
95 }
96}
97
98#[cfg(feature = "serde")]
99impl<'de> serde::Deserialize<'de> for BackendId {
100 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
101 where
102 D: serde::Deserializer<'de>,
103 {
104 let value = <String as serde::Deserialize>::deserialize(deserializer)?;
105 value.parse().map_err(serde::de::Error::custom)
106 }
107}
108
109#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
110#[derive(Clone, Debug, Default, PartialEq, Eq)]
111pub enum BackendPolicy {
113 #[default]
114 PlatformDefault,
116 Require(BackendId),
118 Prefer(Vec<BackendId>),
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum BackendAvailability {
125 Available,
127 NotCompiled,
129 UnsupportedTarget,
131}
132
133#[non_exhaustive]
134#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
135#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub enum OperationStage {
139 Enumeration,
141 Open,
143 Capabilities,
145 Startup,
147 FirstFrame,
149 FrameWait,
151 BackendCommand,
153 Worker,
155 Close,
157}
158
159impl OperationStage {
160 pub const fn as_str(self) -> &'static str {
162 match self {
163 Self::Enumeration => "enumeration",
164 Self::Open => "open",
165 Self::Capabilities => "capabilities",
166 Self::Startup => "startup",
167 Self::FirstFrame => "first_frame",
168 Self::FrameWait => "frame_wait",
169 Self::BackendCommand => "backend_command",
170 Self::Worker => "worker",
171 Self::Close => "close",
172 }
173 }
174}
175
176impl fmt::Display for OperationStage {
177 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
178 formatter.write_str(self.as_str())
179 }
180}
181
182impl FromStr for OperationStage {
183 type Err = CameraError;
184
185 fn from_str(code: &str) -> Result<Self, Self::Err> {
186 match code {
187 "enumeration" => Ok(Self::Enumeration),
188 "open" => Ok(Self::Open),
189 "capabilities" => Ok(Self::Capabilities),
190 "startup" => Ok(Self::Startup),
191 "first_frame" => Ok(Self::FirstFrame),
192 "frame_wait" => Ok(Self::FrameWait),
193 "backend_command" => Ok(Self::BackendCommand),
194 "worker" => Ok(Self::Worker),
195 "close" => Ok(Self::Close),
196 _ => Err(CameraError::invalid_argument(
197 "camera operation stage",
198 code.to_owned(),
199 )),
200 }
201 }
202}
203
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
205pub enum PermissionStatus {
207 NotDetermined,
209 Restricted,
211 Denied,
213 Authorized,
215 ManagedExternally,
217 NotRequired,
219}
220
221#[derive(Clone, Debug, PartialEq, Eq)]
222pub struct BackendAttempt {
224 backend: BackendId,
225 error: std::sync::Arc<CameraError>,
226}
227
228impl BackendAttempt {
229 pub fn new(backend: BackendId, error: std::sync::Arc<CameraError>) -> Self {
231 Self { backend, error }
232 }
233
234 pub fn backend(&self) -> &BackendId {
236 &self.backend
237 }
238
239 pub fn error(&self) -> &CameraError {
241 &self.error
242 }
243
244 pub(crate) fn shared_error(&self) -> &std::sync::Arc<CameraError> {
245 &self.error
246 }
247}
248
249#[derive(Clone, Debug, PartialEq, Eq, Hash)]
253pub struct DeviceId {
254 pub(crate) backend: BackendId,
255 pub(crate) native: String,
256}
257
258impl DeviceId {
259 pub fn new(backend: BackendId, native_id: impl Into<String>) -> CameraResult<Self> {
261 let native = native_id.into();
262 if native.is_empty() || native.len() > 4096 || native.contains('\0') {
263 return Err(CameraError::invalid_config(
264 "Device native identifier is empty or invalid".into(),
265 ));
266 }
267 Ok(Self { backend, native })
268 }
269
270 pub fn backend(&self) -> &BackendId {
272 &self.backend
273 }
274
275 pub fn native_id(&self) -> &str {
277 &self.native
278 }
279
280 pub fn to_persistent_string(&self) -> String {
282 let encoded = self
283 .native
284 .as_bytes()
285 .iter()
286 .map(|byte| format!("{byte:02x}"))
287 .collect::<String>();
288 format!("{}|{encoded}", self.backend)
289 }
290
291 pub fn parse(value: &str) -> CameraResult<Self> {
293 let (backend, encoded) = value
294 .split_once('|')
295 .ok_or_else(|| CameraError::invalid_config("Invalid persisted device ID".into()))?;
296 if encoded.len() > 4096 * 2
297 || encoded.len() % 2 != 0
298 || !encoded.as_bytes().iter().all(u8::is_ascii_hexdigit)
299 {
300 return Err(CameraError::invalid_config(
301 "Invalid persisted device ID payload".into(),
302 ));
303 }
304 #[allow(clippy::chunks_exact_to_as_chunks)]
305 let bytes = encoded
306 .as_bytes()
307 .chunks_exact(2)
308 .map(|pair| {
309 let digit = |byte: u8| match byte {
310 b'0'..=b'9' => byte - b'0',
311 b'a'..=b'f' => byte - b'a' + 10,
312 b'A'..=b'F' => byte - b'A' + 10,
313 _ => unreachable!("ASCII hexadecimal was validated above"),
314 };
315 Ok((digit(pair[0]) << 4) | digit(pair[1]))
316 })
317 .collect::<std::result::Result<Vec<_>, _>>()
318 .map_err(|_: std::convert::Infallible| {
319 CameraError::invalid_config("Invalid persisted device ID payload".into())
320 })?;
321 let native = String::from_utf8(bytes)
322 .map_err(|_| CameraError::invalid_config("Device ID payload is not UTF-8".into()))?;
323 Self::new(backend.parse()?, native)
324 }
325}
326
327impl fmt::Display for DeviceId {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 write!(f, "{}:{}", self.backend, self.native)
330 }
331}
332
333#[cfg(feature = "serde")]
334impl serde::Serialize for DeviceId {
335 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336 where
337 S: serde::Serializer,
338 {
339 serializer.serialize_str(&self.to_persistent_string())
340 }
341}
342
343#[cfg(feature = "serde")]
344impl<'de> serde::Deserialize<'de> for DeviceId {
345 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
346 where
347 D: serde::Deserializer<'de>,
348 {
349 let value = <String as serde::Deserialize>::deserialize(deserializer)?;
350 Self::parse(&value).map_err(serde::de::Error::custom)
351 }
352}
353
354#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub enum IdentityStability {
358 Native,
360 EnumerationOnly,
362}
363
364#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
365#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
366pub enum CameraFacing {
368 Front,
370 Back,
372 External,
374 #[default]
375 Unknown,
377}
378
379#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub struct UsbIdentity {
383 pub vendor_id: u16,
385 pub product_id: u16,
387 pub serial_number: Option<String>,
389}
390
391#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
392#[derive(Clone, Debug)]
393pub struct DeviceInfo {
395 pub id: DeviceId,
397 pub name: String,
399 pub description: String,
401 pub stability: IdentityStability,
403 pub index: u32,
405 pub facing: CameraFacing,
407 pub usb: Option<UsbIdentity>,
409}
410
411#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
412#[derive(Clone, Debug)]
413pub enum DeviceSelector {
415 Default,
417 Id(DeviceId),
419 Facing(CameraFacing),
421 Usb {
423 vendor_id: u16,
425 product_id: u16,
427 serial_number: Option<String>,
429 },
430 Name(String),
432}
433
434#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
435#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
436pub enum CaptureFormat {
438 Mjpeg,
440 Yuyv,
442 Uyvy,
444 Nv12,
446 Rgb8,
448 H264,
450 Gray8,
452}
453
454impl From<CaptureFormat> for VideoFormat {
455 fn from(value: CaptureFormat) -> Self {
456 match value {
457 CaptureFormat::Mjpeg => Self::MJPEG,
458 CaptureFormat::Yuyv => Self::YUYV,
459 CaptureFormat::Uyvy => Self::UYVY,
460 CaptureFormat::Nv12 => Self::NV12,
461 CaptureFormat::Rgb8 => Self::RGB,
462 CaptureFormat::H264 => Self::H264,
463 CaptureFormat::Gray8 => Self::Gray,
464 }
465 }
466}
467
468impl From<VideoFormat> for CaptureFormat {
469 fn from(value: VideoFormat) -> Self {
470 match value {
471 VideoFormat::MJPEG => Self::Mjpeg,
472 VideoFormat::YUYV => Self::Yuyv,
473 VideoFormat::UYVY => Self::Uyvy,
474 VideoFormat::NV12 => Self::Nv12,
475 VideoFormat::RGB => Self::Rgb8,
476 VideoFormat::H264 => Self::H264,
477 VideoFormat::Gray => Self::Gray8,
478 }
479 }
480}
481
482impl TryFrom<PixelFormat> for CaptureFormat {
483 type Error = CameraError;
484
485 fn try_from(value: PixelFormat) -> Result<Self, Self::Error> {
486 Ok(match value {
487 PixelFormat::Mjpeg => Self::Mjpeg,
488 PixelFormat::Yuyv => Self::Yuyv,
489 PixelFormat::Uyvy => Self::Uyvy,
490 PixelFormat::Nv12 => Self::Nv12,
491 PixelFormat::Rgb8 => Self::Rgb8,
492 PixelFormat::H264 => Self::H264,
493 PixelFormat::Gray8 => Self::Gray8,
494 _ => {
495 return Err(CameraError::unsupported_format(format!(
496 "{value:?} has no capture-format equivalent"
497 )))
498 }
499 })
500 }
501}
502
503#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
504#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
505pub enum NegotiationPriority {
507 LowLatency,
509 #[default]
510 LowCpu,
512 LowBandwidth,
514 Fidelity,
516}
517
518#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
519#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
520pub enum CaptureProfile {
522 #[default]
523 Preview,
525 Recognition,
527 Recording,
529 NativeRelay,
531}
532
533#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
534#[derive(Clone, Debug)]
535pub struct CaptureRequest {
537 pub(crate) width: u32,
538 pub(crate) height: u32,
539 pub(crate) preferred_fps: FrameRate,
540 pub(crate) minimum_fps: Option<FrameRate>,
541 pub(crate) preferred_formats: Vec<CaptureFormat>,
542 pub(crate) priority: NegotiationPriority,
543 pub(crate) exact_resolution: bool,
544 pub(crate) required_aspect_ratio: Option<(u32, u32)>,
545 pub(crate) memory: MemoryBudget,
546 pub(crate) startup_timeout: Duration,
547 pub(crate) reconnect: Option<crate::ReconnectPolicy>,
548}
549
550impl CaptureRequest {
551 pub fn builder() -> CaptureRequestBuilder {
553 CaptureRequestBuilder(Self {
554 width: 640,
555 height: 480,
556 preferred_fps: FrameRate::default(),
557 minimum_fps: None,
558 preferred_formats: Vec::new(),
559 priority: NegotiationPriority::default(),
560 exact_resolution: false,
561 required_aspect_ratio: None,
562 memory: MemoryBudget::default(),
563 startup_timeout: Duration::from_secs(3),
564 reconnect: None,
565 })
566 }
567
568 pub fn preferred_resolution(&self) -> (u32, u32) {
570 (self.width, self.height)
571 }
572
573 pub fn preferred_frame_rate(&self) -> FrameRate {
575 self.preferred_fps
576 }
577
578 pub fn minimum_frame_rate(&self) -> Option<FrameRate> {
580 self.minimum_fps
581 }
582
583 pub fn preferred_formats(&self) -> &[CaptureFormat] {
585 &self.preferred_formats
586 }
587
588 pub fn priority(&self) -> NegotiationPriority {
590 self.priority
591 }
592
593 pub fn required_aspect_ratio(&self) -> Option<(u32, u32)> {
595 self.required_aspect_ratio
596 }
597
598 pub const fn delivers_native_frames(&self) -> bool {
600 true
601 }
602
603 pub(crate) fn to_stream_request(&self) -> CameraResult<crate::StreamRequest> {
604 let mut builder = crate::StreamRequest::builder()
605 .resolution(self.width, self.height)
606 .frame_rate(self.preferred_fps)
607 .output(crate::OutputFormat::Native)
608 .selection(crate::SelectionPolicy::Closest)
609 .memory_budget(self.memory)
610 .startup_timeout(self.startup_timeout);
611 if let Some(format) = self.preferred_formats.first().copied() {
612 builder = builder.capture_format(format.into());
613 }
614 if let Some(policy) = self.reconnect.clone() {
615 builder = builder.reconnect(policy);
616 }
617 builder.build()
618 }
619}
620
621#[derive(Clone, Debug)]
622pub struct CaptureRequestBuilder(CaptureRequest);
624
625impl CaptureRequestBuilder {
626 pub fn preferred_resolution(mut self, width: u32, height: u32) -> Self {
628 self.0.width = width;
629 self.0.height = height;
630 self
631 }
632
633 pub fn exact_resolution(mut self, width: u32, height: u32) -> Self {
635 self.0.width = width;
636 self.0.height = height;
637 self.0.exact_resolution = true;
638 self
639 }
640
641 pub fn require_aspect_ratio(mut self, width: u32, height: u32) -> Self {
644 self.0.required_aspect_ratio = Some((width, height));
645 self
646 }
647
648 pub fn preferred_frame_rate(mut self, rate: FrameRate) -> Self {
650 self.0.preferred_fps = rate;
651 self
652 }
653
654 pub fn minimum_frame_rate(mut self, rate: FrameRate) -> Self {
656 self.0.minimum_fps = Some(rate);
657 self
658 }
659
660 pub fn preferred_formats(mut self, formats: impl IntoIterator<Item = CaptureFormat>) -> Self {
662 self.0.preferred_formats = formats.into_iter().collect();
663 self
664 }
665
666 pub fn priority(mut self, priority: NegotiationPriority) -> Self {
668 self.0.priority = priority;
669 self
670 }
671
672 pub fn memory_budget(mut self, budget: MemoryBudget) -> Self {
674 self.0.memory = budget;
675 self
676 }
677
678 pub fn startup_timeout(mut self, timeout: Duration) -> Self {
680 self.0.startup_timeout = timeout;
681 self
682 }
683
684 pub fn reconnect(mut self, policy: crate::ReconnectPolicy) -> Self {
686 self.0.reconnect = Some(policy);
687 self
688 }
689
690 pub fn build(self) -> CameraResult<CaptureRequest> {
692 let request = self.0;
693 request.to_stream_request()?;
694 if request
695 .minimum_fps
696 .is_some_and(|minimum| minimum > request.preferred_fps)
697 {
698 return Err(CameraError::invalid_config(
699 "Minimum frame rate exceeds preferred frame rate".into(),
700 ));
701 }
702 if request
703 .required_aspect_ratio
704 .is_some_and(|(width, height)| width == 0 || height == 0)
705 {
706 return Err(CameraError::invalid_config(
707 "Required aspect ratio must be positive".into(),
708 ));
709 }
710 if request.preferred_formats.len() > 1 {
711 let mut dedup = request.preferred_formats.clone();
712 dedup.sort_by_key(|format| *format as u8);
713 dedup.dedup();
714 if dedup.len() != request.preferred_formats.len() {
715 return Err(CameraError::invalid_config(
716 "Preferred capture formats contain duplicates".into(),
717 ));
718 }
719 }
720 Ok(request)
721 }
722}
723
724#[derive(Clone, Debug, PartialEq, Eq)]
725pub struct CaptureMode {
727 pub format: CaptureFormat,
729 pub width: u32,
731 pub height: u32,
733 pub frame_rate: FrameRate,
735}
736
737impl CaptureMode {
738 #[allow(dead_code)]
739 pub(crate) fn from_config(config: &CameraConfig) -> CameraResult<Self> {
740 Ok(Self {
741 format: config.format.into(),
742 width: config.width,
743 height: config.height,
744 frame_rate: config.frame_rate()?,
745 })
746 }
747
748 pub(crate) fn to_config(&self) -> CameraResult<CameraConfig> {
749 let config = CameraConfig::new(
750 self.format.into(),
751 self.width,
752 self.height,
753 self.frame_rate.numerator(),
754 )
755 .with_frame_rate(self.frame_rate);
756 config.validate()?;
757 Ok(config)
758 }
759}
760
761#[derive(Clone, Debug, PartialEq, Eq)]
762pub enum CapabilityKnowledge<T> {
764 Known(T),
766 Representative {
769 values: T,
771 reason: String,
773 },
774 Unknown {
776 reason: String,
778 },
779}
780
781#[derive(Clone, Copy, Debug, PartialEq, Eq)]
782pub enum CapabilityRangeKind {
784 Discrete,
786 Continuous,
788 Stepwise,
790}
791
792#[derive(Clone, Copy, Debug, PartialEq, Eq)]
793pub struct DimensionRange {
795 pub minimum: u32,
797 pub maximum: u32,
799 pub step: u32,
801}
802
803#[derive(Clone, Copy, Debug, PartialEq, Eq)]
804pub struct FrameInterval {
806 pub numerator: u32,
808 pub denominator: u32,
810}
811
812#[derive(Clone, Debug, PartialEq, Eq)]
813pub struct FrameIntervalRange {
815 pub kind: CapabilityRangeKind,
817 pub minimum: FrameInterval,
819 pub maximum: FrameInterval,
821 pub step: Option<FrameInterval>,
823 pub at_resolution: (u32, u32),
825}
826
827#[derive(Clone, Debug, PartialEq, Eq)]
828pub struct CaptureModeRange {
830 pub format: CaptureFormat,
832 pub kind: CapabilityRangeKind,
834 pub width: DimensionRange,
836 pub height: DimensionRange,
838 pub frame_intervals: Vec<FrameIntervalRange>,
840}
841
842#[derive(Clone, Debug, PartialEq, Eq)]
843pub struct ConversionCapability {
845 pub input: CaptureFormat,
847 pub output: PixelFormat,
849 pub available: bool,
851 pub requirement: Option<&'static str>,
853}
854
855#[derive(Clone, Debug)]
856pub struct DeviceCapabilities {
858 pub capture_modes: CapabilityKnowledge<Vec<CaptureMode>>,
860 pub capture_mode_ranges: Vec<CaptureModeRange>,
863 pub native_formats: Vec<CaptureFormat>,
865 pub conversions: Vec<ConversionCapability>,
867 pub limitations: Vec<String>,
869}
870
871impl DeviceCapabilities {
872 pub fn single_native(
874 format: CaptureFormat,
875 width: u32,
876 height: u32,
877 frame_rate: FrameRate,
878 ) -> Self {
879 Self::from_modes_unchecked(vec![CaptureMode {
880 format,
881 width,
882 height,
883 frame_rate,
884 }])
885 }
886
887 pub fn from_modes(modes: impl IntoIterator<Item = CaptureMode>) -> CameraResult<Self> {
890 let modes = modes.into_iter().collect::<Vec<_>>();
891 if modes.is_empty() {
892 return Err(CameraError::invalid_config(
893 "Device capabilities require at least one capture mode".into(),
894 ));
895 }
896 let mut configurations = modes
897 .iter()
898 .map(CaptureMode::to_config)
899 .collect::<CameraResult<Vec<_>>>()?;
900 configurations.sort_by_key(|config| {
901 (
902 config.format as u8,
903 config.width,
904 config.height,
905 config.fps,
906 config.fps_denominator,
907 )
908 });
909 configurations.dedup();
910 if configurations.len() != modes.len() {
911 return Err(CameraError::invalid_config(
912 "Device capabilities contain duplicate capture modes".into(),
913 ));
914 }
915 Ok(Self::from_modes_unchecked(modes))
916 }
917
918 #[allow(dead_code)]
919 pub(crate) fn from_configurations(configurations: Vec<CameraConfig>) -> Self {
920 let modes = configurations
921 .iter()
922 .filter_map(|config| {
923 Some(CaptureMode {
924 format: config.format.into(),
925 width: config.width,
926 height: config.height,
927 frame_rate: config.frame_rate().ok()?,
928 })
929 })
930 .collect::<Vec<_>>();
931 Self::from_modes_unchecked(modes)
932 }
933
934 fn from_modes_unchecked(modes: Vec<CaptureMode>) -> Self {
935 let mut native_formats = modes.iter().map(|mode| mode.format).collect::<Vec<_>>();
936 native_formats.sort_by_key(|format| *format as u8);
937 native_formats.dedup();
938 let conversions = native_formats
939 .iter()
940 .copied()
941 .map(|input| {
942 let jpeg = input == CaptureFormat::Mjpeg;
943 let h264 = input == CaptureFormat::H264;
944 let available = !h264
945 && cfg!(feature = "convert-rgb")
946 && (!jpeg || cfg!(feature = "decode-mjpeg"));
947 ConversionCapability {
948 input,
949 output: PixelFormat::Rgb8,
950 available,
951 requirement: if h264 {
952 Some("external-h264-decoder")
953 } else if jpeg && !cfg!(feature = "decode-mjpeg") {
954 Some("decode-mjpeg")
955 } else if !cfg!(feature = "convert-rgb") {
956 Some("convert-rgb")
957 } else {
958 None
959 },
960 }
961 })
962 .collect();
963 Self {
964 capture_modes: CapabilityKnowledge::Known(modes),
965 capture_mode_ranges: Vec::new(),
966 native_formats,
967 conversions,
968 limitations: Vec::new(),
969 }
970 }
971
972 #[allow(dead_code)]
973 pub(crate) fn configurations(&self) -> CameraResult<Vec<CameraConfig>> {
974 match &self.capture_modes {
975 CapabilityKnowledge::Known(modes)
976 | CapabilityKnowledge::Representative { values: modes, .. } => {
977 modes.iter().map(CaptureMode::to_config).collect()
978 }
979 CapabilityKnowledge::Unknown { reason } => Err(CameraError::unsupported_format(
980 format!("Capture modes are unknown: {reason}"),
981 )),
982 }
983 }
984
985 #[allow(dead_code)]
986 pub(crate) fn with_ranges(mut self, ranges: Vec<CaptureModeRange>) -> Self {
987 if !ranges.is_empty() {
988 if let CapabilityKnowledge::Known(modes) = self.capture_modes {
989 self.capture_modes = CapabilityKnowledge::Representative {
990 values: modes,
991 reason:
992 "backend advertises ranged modes; listed modes are representative samples"
993 .into(),
994 };
995 }
996 self.capture_mode_ranges = ranges;
997 }
998 self
999 }
1000}
1001
1002#[derive(Clone, Debug)]
1003pub struct NegotiatedCapture {
1005 pub capture: CaptureMode,
1007 pub adjustments: Vec<String>,
1009 pub first_frame_latency: Duration,
1011}
1012
1013#[derive(Clone, Debug)]
1014pub struct CapturePlan {
1016 pub selected: NegotiatedCapture,
1018 pub alternatives: Vec<CaptureMode>,
1020 pub ranking_reason: String,
1022 pub estimated_pool_bytes: usize,
1024 pub adjustments: Vec<String>,
1026}
1027
1028#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1029#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1030pub struct SubscriptionOptions {
1032 pub(crate) delivery: DeliveryPolicy,
1033 pub(crate) max_rate: Option<FrameRate>,
1034}
1035
1036impl SubscriptionOptions {
1037 pub fn latest() -> Self {
1039 Self {
1040 delivery: DeliveryPolicy::Latest,
1041 max_rate: None,
1042 }
1043 }
1044
1045 pub fn buffered(capacity: usize) -> Self {
1047 Self {
1048 delivery: DeliveryPolicy::Buffered {
1049 capacity,
1050 overflow: OverflowPolicy::DropOldest,
1051 },
1052 max_rate: None,
1053 }
1054 }
1055
1056 pub fn overflow(mut self, overflow: OverflowPolicy) -> Self {
1058 if let DeliveryPolicy::Buffered {
1059 overflow: current, ..
1060 } = &mut self.delivery
1061 {
1062 *current = overflow;
1063 }
1064 self
1065 }
1066
1067 pub fn max_rate(mut self, rate: FrameRate) -> Self {
1069 self.max_rate = Some(rate);
1070 self
1071 }
1072
1073 #[allow(dead_code)]
1074 pub(crate) fn validate(self, budget: MemoryBudget) -> CameraResult<()> {
1075 if let DeliveryPolicy::Buffered { capacity, .. } = self.delivery {
1076 if capacity == 0 || capacity >= budget.buffers {
1077 return Err(CameraError::invalid_config(
1078 "Subscription queue must be positive and smaller than the frame pool".into(),
1079 ));
1080 }
1081 }
1082 Ok(())
1083 }
1084}
1085
1086#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1087#[derive(Clone, Debug, Default, PartialEq, Eq)]
1088pub struct V4l2Options {
1090 pub mmap_buffers: Option<usize>,
1092}
1093
1094#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1095#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1096pub enum Camera2RequestTemplate {
1098 #[default]
1099 Preview,
1101 StillCapture,
1103 Record,
1105}
1106
1107impl Camera2RequestTemplate {
1108 #[cfg(target_os = "android")]
1109 pub(crate) const fn native_value(self) -> i32 {
1110 match self {
1111 Self::Preview => 1,
1112 Self::StillCapture => 2,
1113 Self::Record => 3,
1114 }
1115 }
1116}
1117
1118#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1119#[derive(Clone, Debug, Default, PartialEq, Eq)]
1120pub struct Camera2Options {
1122 pub max_images: Option<u32>,
1124 pub request_template: Option<Camera2RequestTemplate>,
1126}
1127
1128#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1130pub enum LateFramePolicy {
1132 #[default]
1133 Drop,
1135 Deliver,
1137}
1138
1139#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1140#[derive(Clone, Debug, Default, PartialEq, Eq)]
1141pub struct AvFoundationOptions {
1143 pub late_frames: LateFramePolicy,
1145}
1146
1147impl AvFoundationOptions {
1148 pub fn late_frames(mut self, policy: LateFramePolicy) -> Self {
1150 self.late_frames = policy;
1151 self
1152 }
1153}
1154
1155impl Camera2Options {
1156 pub fn max_images(mut self, count: u32) -> Self {
1158 self.max_images = Some(count);
1159 self
1160 }
1161
1162 pub fn request_template(mut self, template: Camera2RequestTemplate) -> Self {
1164 self.request_template = Some(template);
1165 self
1166 }
1167}
1168
1169impl V4l2Options {
1170 pub fn mmap_buffers(mut self, count: usize) -> Self {
1172 self.mmap_buffers = Some(count);
1173 self
1174 }
1175}
1176
1177#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1178#[derive(Clone, Debug, PartialEq, Eq)]
1179pub enum BackendOptions {
1181 V4l2(V4l2Options),
1183 Camera2(Camera2Options),
1185 AvFoundation(AvFoundationOptions),
1187}
1188
1189impl BackendOptions {
1190 pub fn backend(&self) -> BackendId {
1192 match self {
1193 Self::V4l2(_) => BackendId::V4L2,
1194 Self::Camera2(_) => BackendId::CAMERA2,
1195 Self::AvFoundation(_) => BackendId::AV_FOUNDATION,
1196 }
1197 }
1198
1199 #[allow(dead_code)]
1200 pub(crate) fn validate(&self) -> CameraResult<()> {
1201 match self {
1202 Self::V4l2(options) if options.mmap_buffers.is_some_and(|n| !(2..=32).contains(&n)) => {
1203 Err(CameraError::invalid_config(
1204 "V4L2 MMAP buffer count must be 2..=32".into(),
1205 ))
1206 }
1207 Self::Camera2(options)
1208 if options.max_images.is_some_and(|n| !(2..=16).contains(&n)) =>
1209 {
1210 Err(CameraError::invalid_config(
1211 "Camera2 max_images must be 2..=16".into(),
1212 ))
1213 }
1214 Self::AvFoundation(_) => Ok(()),
1215 _ => Ok(()),
1216 }
1217 }
1218}
1219
1220impl From<V4l2Options> for BackendOptions {
1221 fn from(value: V4l2Options) -> Self {
1222 Self::V4l2(value)
1223 }
1224}
1225
1226impl From<Camera2Options> for BackendOptions {
1227 fn from(value: Camera2Options) -> Self {
1228 Self::Camera2(value)
1229 }
1230}
1231
1232impl From<AvFoundationOptions> for BackendOptions {
1233 fn from(value: AvFoundationOptions) -> Self {
1234 Self::AvFoundation(value)
1235 }
1236}
1237
1238#[cfg(test)]
1239mod capability_tests {
1240 use super::*;
1241
1242 #[test]
1243 fn ranged_capabilities_mark_discrete_modes_as_representative() {
1244 let capabilities = DeviceCapabilities::single_native(
1245 CaptureFormat::Yuyv,
1246 640,
1247 480,
1248 FrameRate::new(30, 1).unwrap(),
1249 )
1250 .with_ranges(vec![CaptureModeRange {
1251 format: CaptureFormat::Yuyv,
1252 kind: CapabilityRangeKind::Stepwise,
1253 width: DimensionRange {
1254 minimum: 320,
1255 maximum: 1920,
1256 step: 16,
1257 },
1258 height: DimensionRange {
1259 minimum: 240,
1260 maximum: 1080,
1261 step: 16,
1262 },
1263 frame_intervals: vec![FrameIntervalRange {
1264 kind: CapabilityRangeKind::Continuous,
1265 minimum: FrameInterval {
1266 numerator: 1,
1267 denominator: 60,
1268 },
1269 maximum: FrameInterval {
1270 numerator: 1,
1271 denominator: 15,
1272 },
1273 step: None,
1274 at_resolution: (640, 480),
1275 }],
1276 }]);
1277
1278 assert!(matches!(
1279 capabilities.capture_modes,
1280 CapabilityKnowledge::Representative { .. }
1281 ));
1282 assert_eq!(capabilities.capture_mode_ranges.len(), 1);
1283 assert_eq!(capabilities.configurations().unwrap().len(), 1);
1284 }
1285}