Skip to main content

camera/
contract.rs

1//! Public, backend-neutral capture contracts.
2use 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)]
9/// Stable identifier for a built-in or application-provided camera backend.
10pub struct BackendId(Cow<'static, str>);
11
12impl BackendId {
13    /// USB Video Class backend backed by bundled libuvc/libusb.
14    pub const UVC: Self = Self::builtin("uvc");
15    /// Linux Video4Linux2 backend.
16    pub const V4L2: Self = Self::builtin("v4l2");
17    /// Apple AVFoundation backend.
18    pub const AV_FOUNDATION: Self = Self::builtin("avfoundation");
19    /// Android NDK Camera2 backend.
20    pub const CAMERA2: Self = Self::builtin("camera2");
21    /// Windows Media Foundation backend.
22    pub const MEDIA_FOUNDATION: Self = Self::builtin("media-foundation");
23    /// Deterministic in-process backend intended for examples and tests.
24    pub const SYNTHETIC: Self = Self::builtin("synthetic");
25
26    const fn builtin(value: &'static str) -> Self {
27        // All callers are associated constants backed by string literals.
28        Self(Cow::Borrowed(value))
29    }
30
31    /// Creates a namespaced identifier for an application-provided backend.
32    ///
33    /// Each component must be a non-empty ASCII identifier of at most 96 bytes.
34    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    /// Returns the stable serialized backend identifier.
51    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)]
111/// Policy used to select which compiled backend may satisfy an operation.
112pub enum BackendPolicy {
113    #[default]
114    /// Use the platform's preferred native backend without unrelated fallback.
115    PlatformDefault,
116    /// Require exactly the specified backend.
117    Require(BackendId),
118    /// Try the listed backends in order and retain each typed failure.
119    Prefer(Vec<BackendId>),
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123/// Compile-time and target support status for a backend.
124pub enum BackendAvailability {
125    /// The backend is compiled and supports the current target.
126    Available,
127    /// The corresponding Cargo feature was not enabled.
128    NotCompiled,
129    /// The backend feature is enabled but cannot run on this target.
130    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)]
137/// Possible values for `OperationStage`.
138pub enum OperationStage {
139    /// The `Enumeration` variant.
140    Enumeration,
141    /// The `Open` variant.
142    Open,
143    /// The `Capabilities` variant.
144    Capabilities,
145    /// The `Startup` variant.
146    Startup,
147    /// The `FirstFrame` variant.
148    FirstFrame,
149    /// The `FrameWait` variant.
150    FrameWait,
151    /// The `BackendCommand` variant.
152    BackendCommand,
153    /// The `Worker` variant.
154    Worker,
155    /// The `Close` variant.
156    Close,
157}
158
159impl OperationStage {
160    /// Stable machine-readable operation stage.
161    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)]
205/// Current camera authorization state as reported by the selected platform.
206pub enum PermissionStatus {
207    /// The `NotDetermined` variant.
208    NotDetermined,
209    /// The `Restricted` variant.
210    Restricted,
211    /// The `Denied` variant.
212    Denied,
213    /// The `Authorized` variant.
214    Authorized,
215    /// The `ManagedExternally` variant.
216    ManagedExternally,
217    /// The `NotRequired` variant.
218    NotRequired,
219}
220
221#[derive(Clone, Debug, PartialEq, Eq)]
222/// One typed failure captured while evaluating a fallback backend policy.
223pub struct BackendAttempt {
224    backend: BackendId,
225    error: std::sync::Arc<CameraError>,
226}
227
228impl BackendAttempt {
229    /// Creates an attempt record from its backend and original shared error.
230    pub fn new(backend: BackendId, error: std::sync::Arc<CameraError>) -> Self {
231        Self { backend, error }
232    }
233
234    /// Returns the backend that produced the failure.
235    pub fn backend(&self) -> &BackendId {
236        &self.backend
237    }
238
239    /// Returns the original structured camera error.
240    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/// Backend-scoped device identity. Persistence preserves the backend namespace;
250/// `IdentityStability` still tells callers whether the native part is stable
251/// across enumeration cycles or process restarts.
252#[derive(Clone, Debug, PartialEq, Eq, Hash)]
253pub struct DeviceId {
254    pub(crate) backend: BackendId,
255    pub(crate) native: String,
256}
257
258impl DeviceId {
259    /// Performs the `new` operation.
260    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    /// Performs the `backend` operation.
271    pub fn backend(&self) -> &BackendId {
272        &self.backend
273    }
274
275    /// Performs the `native_id` operation.
276    pub fn native_id(&self) -> &str {
277        &self.native
278    }
279
280    /// Performs the `to_persistent_string` operation.
281    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    /// Performs the `parse` operation.
292    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)]
356/// Possible values for `IdentityStability`.
357pub enum IdentityStability {
358    /// The `Native` variant.
359    Native,
360    /// The `EnumerationOnly` variant.
361    EnumerationOnly,
362}
363
364#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
365#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
366/// Possible values for `CameraFacing`.
367pub enum CameraFacing {
368    /// The `Front` variant.
369    Front,
370    /// The `Back` variant.
371    Back,
372    /// The `External` variant.
373    External,
374    #[default]
375    /// The `Unknown` variant.
376    Unknown,
377}
378
379#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
380#[derive(Clone, Debug, PartialEq, Eq)]
381/// Values for `UsbIdentity`.
382pub struct UsbIdentity {
383    /// USB vendor identifier.
384    pub vendor_id: u16,
385    /// USB product identifier.
386    pub product_id: u16,
387    /// USB serial number when available.
388    pub serial_number: Option<String>,
389}
390
391#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
392#[derive(Clone, Debug)]
393/// Values for `DeviceInfo`.
394pub struct DeviceInfo {
395    /// The id value.
396    pub id: DeviceId,
397    /// Human-readable name.
398    pub name: String,
399    /// Human-readable description.
400    pub description: String,
401    /// Persistence guarantee for the identifier.
402    pub stability: IdentityStability,
403    /// Enumeration index for the current snapshot.
404    pub index: u32,
405    /// Physical camera facing.
406    pub facing: CameraFacing,
407    /// USB identity when available.
408    pub usb: Option<UsbIdentity>,
409}
410
411#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
412#[derive(Clone, Debug)]
413/// Possible values for `DeviceSelector`.
414pub enum DeviceSelector {
415    /// The `Default` variant.
416    Default,
417    /// The `Id` variant.
418    Id(DeviceId),
419    /// The `Facing` variant.
420    Facing(CameraFacing),
421    /// The `Usb` variant.
422    Usb {
423        /// The `vendor_id` struct field.
424        vendor_id: u16,
425        /// The `product_id` struct field.
426        product_id: u16,
427        /// The `serial_number` struct field.
428        serial_number: Option<String>,
429    },
430    /// The `Name` variant.
431    Name(String),
432}
433
434#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
435#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
436/// Possible values for `CaptureFormat`.
437pub enum CaptureFormat {
438    /// The `Mjpeg` variant.
439    Mjpeg,
440    /// The `Yuyv` variant.
441    Yuyv,
442    /// The `Uyvy` variant.
443    Uyvy,
444    /// The `Nv12` variant.
445    Nv12,
446    /// The `Rgb8` variant.
447    Rgb8,
448    /// The `H264` variant.
449    H264,
450    /// The `Gray8` variant.
451    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)]
505/// Possible values for `NegotiationPriority`.
506pub enum NegotiationPriority {
507    /// The `LowLatency` variant.
508    LowLatency,
509    #[default]
510    /// The `LowCpu` variant.
511    LowCpu,
512    /// The `LowBandwidth` variant.
513    LowBandwidth,
514    /// The `Fidelity` variant.
515    Fidelity,
516}
517
518#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
519#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
520/// Possible values for `CaptureProfile`.
521pub enum CaptureProfile {
522    #[default]
523    /// The `Preview` variant.
524    Preview,
525    /// The `Recognition` variant.
526    Recognition,
527    /// The `Recording` variant.
528    Recording,
529    /// The `NativeRelay` variant.
530    NativeRelay,
531}
532
533#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
534#[derive(Clone, Debug)]
535/// Values for `CaptureRequest`.
536pub 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    /// Performs the `builder` operation.
552    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    /// Performs the `preferred_resolution` operation.
569    pub fn preferred_resolution(&self) -> (u32, u32) {
570        (self.width, self.height)
571    }
572
573    /// Performs the `preferred_frame_rate` operation.
574    pub fn preferred_frame_rate(&self) -> FrameRate {
575        self.preferred_fps
576    }
577
578    /// Performs the `minimum_frame_rate` operation.
579    pub fn minimum_frame_rate(&self) -> Option<FrameRate> {
580        self.minimum_fps
581    }
582
583    /// Performs the `preferred_formats` operation.
584    pub fn preferred_formats(&self) -> &[CaptureFormat] {
585        &self.preferred_formats
586    }
587
588    /// Performs the `priority` operation.
589    pub fn priority(&self) -> NegotiationPriority {
590        self.priority
591    }
592
593    /// Performs the `required_aspect_ratio` operation.
594    pub fn required_aspect_ratio(&self) -> Option<(u32, u32)> {
595        self.required_aspect_ratio
596    }
597
598    /// The `fn` constant.
599    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)]
622/// Values for `CaptureRequestBuilder`.
623pub struct CaptureRequestBuilder(CaptureRequest);
624
625impl CaptureRequestBuilder {
626    /// Performs the `preferred_resolution` operation.
627    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    /// Performs the `exact_resolution` operation.
634    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    /// Require an exact display aspect ratio while still allowing the device to
642    /// negotiate a different resolution with that ratio.
643    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    /// Performs the `preferred_frame_rate` operation.
649    pub fn preferred_frame_rate(mut self, rate: FrameRate) -> Self {
650        self.0.preferred_fps = rate;
651        self
652    }
653
654    /// Performs the `minimum_frame_rate` operation.
655    pub fn minimum_frame_rate(mut self, rate: FrameRate) -> Self {
656        self.0.minimum_fps = Some(rate);
657        self
658    }
659
660    /// Performs the `preferred_formats` operation.
661    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    /// Performs the `priority` operation.
667    pub fn priority(mut self, priority: NegotiationPriority) -> Self {
668        self.0.priority = priority;
669        self
670    }
671
672    /// Performs the `memory_budget` operation.
673    pub fn memory_budget(mut self, budget: MemoryBudget) -> Self {
674        self.0.memory = budget;
675        self
676    }
677
678    /// Performs the `startup_timeout` operation.
679    pub fn startup_timeout(mut self, timeout: Duration) -> Self {
680        self.0.startup_timeout = timeout;
681        self
682    }
683
684    /// Performs the `reconnect` operation.
685    pub fn reconnect(mut self, policy: crate::ReconnectPolicy) -> Self {
686        self.0.reconnect = Some(policy);
687        self
688    }
689
690    /// Performs the `build` operation.
691    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)]
725/// Values for `CaptureMode`.
726pub struct CaptureMode {
727    /// Pixel or capture format.
728    pub format: CaptureFormat,
729    /// Frame width in pixels.
730    pub width: u32,
731    /// Frame height in pixels.
732    pub height: u32,
733    /// Capture frame rate.
734    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)]
762/// Possible values for `CapabilityKnowledge`.
763pub enum CapabilityKnowledge<T> {
764    /// The `Known` variant.
765    Known(T),
766    /// A bounded sample of a backend capability space that also contains
767    /// continuous or stepwise ranges.
768    Representative {
769        /// The `values` struct field.
770        values: T,
771        /// The `reason` struct field.
772        reason: String,
773    },
774    /// The `Unknown` variant.
775    Unknown {
776        /// The `reason` struct field.
777        reason: String,
778    },
779}
780
781#[derive(Clone, Copy, Debug, PartialEq, Eq)]
782/// Possible values for `CapabilityRangeKind`.
783pub enum CapabilityRangeKind {
784    /// The `Discrete` variant.
785    Discrete,
786    /// The `Continuous` variant.
787    Continuous,
788    /// The `Stepwise` variant.
789    Stepwise,
790}
791
792#[derive(Clone, Copy, Debug, PartialEq, Eq)]
793/// Values for `DimensionRange`.
794pub struct DimensionRange {
795    /// The minimum value.
796    pub minimum: u32,
797    /// The maximum value.
798    pub maximum: u32,
799    /// The step value.
800    pub step: u32,
801}
802
803#[derive(Clone, Copy, Debug, PartialEq, Eq)]
804/// Values for `FrameInterval`.
805pub struct FrameInterval {
806    /// The numerator value.
807    pub numerator: u32,
808    /// The denominator value.
809    pub denominator: u32,
810}
811
812#[derive(Clone, Debug, PartialEq, Eq)]
813/// Values for `FrameIntervalRange`.
814pub struct FrameIntervalRange {
815    /// The kind value.
816    pub kind: CapabilityRangeKind,
817    /// The minimum value.
818    pub minimum: FrameInterval,
819    /// The maximum value.
820    pub maximum: FrameInterval,
821    /// The step value.
822    pub step: Option<FrameInterval>,
823    /// Resolution at which the backend reported this interval range.
824    pub at_resolution: (u32, u32),
825}
826
827#[derive(Clone, Debug, PartialEq, Eq)]
828/// Values for `CaptureModeRange`.
829pub struct CaptureModeRange {
830    /// Pixel or capture format.
831    pub format: CaptureFormat,
832    /// The kind value.
833    pub kind: CapabilityRangeKind,
834    /// Frame width in pixels.
835    pub width: DimensionRange,
836    /// Frame height in pixels.
837    pub height: DimensionRange,
838    /// The frame intervals value.
839    pub frame_intervals: Vec<FrameIntervalRange>,
840}
841
842#[derive(Clone, Debug, PartialEq, Eq)]
843/// Values for `ConversionCapability`.
844pub struct ConversionCapability {
845    /// The input value.
846    pub input: CaptureFormat,
847    /// The output value.
848    pub output: PixelFormat,
849    /// Whether this conversion is compiled and available.
850    pub available: bool,
851    /// The requirement value.
852    pub requirement: Option<&'static str>,
853}
854
855#[derive(Clone, Debug)]
856/// Values for `DeviceCapabilities`.
857pub struct DeviceCapabilities {
858    /// The capture modes value.
859    pub capture_modes: CapabilityKnowledge<Vec<CaptureMode>>,
860    /// Native size and/or frame-interval range descriptors. `capture_modes` is
861    /// representative when this list is non-empty.
862    pub capture_mode_ranges: Vec<CaptureModeRange>,
863    /// The native formats value.
864    pub native_formats: Vec<CaptureFormat>,
865    /// The conversions value.
866    pub conversions: Vec<ConversionCapability>,
867    /// The limitations value.
868    pub limitations: Vec<String>,
869}
870
871impl DeviceCapabilities {
872    /// Performs the `single_native` operation.
873    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    /// Build a capability description whose public capture modes are also the
888    /// single source used by planning and capture negotiation.
889    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)]
1003/// Values for `NegotiatedCapture`.
1004pub struct NegotiatedCapture {
1005    /// Negotiated native capture mode.
1006    pub capture: CaptureMode,
1007    /// Adjustments made during negotiation.
1008    pub adjustments: Vec<String>,
1009    /// The first frame latency value.
1010    pub first_frame_latency: Duration,
1011}
1012
1013#[derive(Clone, Debug)]
1014/// Values for `CapturePlan`.
1015pub struct CapturePlan {
1016    /// The selected value.
1017    pub selected: NegotiatedCapture,
1018    /// Other compatible capture modes.
1019    pub alternatives: Vec<CaptureMode>,
1020    /// Human-readable explanation of the selected mode.
1021    pub ranking_reason: String,
1022    /// Estimated bytes reserved by the frame pool.
1023    pub estimated_pool_bytes: usize,
1024    /// Adjustments made during negotiation.
1025    pub adjustments: Vec<String>,
1026}
1027
1028#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1029#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1030/// Values for `SubscriptionOptions`.
1031pub struct SubscriptionOptions {
1032    pub(crate) delivery: DeliveryPolicy,
1033    pub(crate) max_rate: Option<FrameRate>,
1034}
1035
1036impl SubscriptionOptions {
1037    /// Performs the `latest` operation.
1038    pub fn latest() -> Self {
1039        Self {
1040            delivery: DeliveryPolicy::Latest,
1041            max_rate: None,
1042        }
1043    }
1044
1045    /// Performs the `buffered` operation.
1046    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    /// Performs the `overflow` operation.
1057    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    /// Performs the `max_rate` operation.
1068    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)]
1088/// Values for `V4l2Options`.
1089pub struct V4l2Options {
1090    /// The mmap buffers value.
1091    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)]
1096/// Possible values for `Camera2RequestTemplate`.
1097pub enum Camera2RequestTemplate {
1098    #[default]
1099    /// The `Preview` variant.
1100    Preview,
1101    /// The `StillCapture` variant.
1102    StillCapture,
1103    /// The `Record` variant.
1104    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)]
1120/// Values for `Camera2Options`.
1121pub struct Camera2Options {
1122    /// The max images value.
1123    pub max_images: Option<u32>,
1124    /// The request template value.
1125    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)]
1130/// Possible values for `LateFramePolicy`.
1131pub enum LateFramePolicy {
1132    #[default]
1133    /// The `Drop` variant.
1134    Drop,
1135    /// The `Deliver` variant.
1136    Deliver,
1137}
1138
1139#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1140#[derive(Clone, Debug, Default, PartialEq, Eq)]
1141/// Values for `AvFoundationOptions`.
1142pub struct AvFoundationOptions {
1143    /// The late frames value.
1144    pub late_frames: LateFramePolicy,
1145}
1146
1147impl AvFoundationOptions {
1148    /// Performs the `late_frames` operation.
1149    pub fn late_frames(mut self, policy: LateFramePolicy) -> Self {
1150        self.late_frames = policy;
1151        self
1152    }
1153}
1154
1155impl Camera2Options {
1156    /// Performs the `max_images` operation.
1157    pub fn max_images(mut self, count: u32) -> Self {
1158        self.max_images = Some(count);
1159        self
1160    }
1161
1162    /// Performs the `request_template` operation.
1163    pub fn request_template(mut self, template: Camera2RequestTemplate) -> Self {
1164        self.request_template = Some(template);
1165        self
1166    }
1167}
1168
1169impl V4l2Options {
1170    /// Performs the `mmap_buffers` operation.
1171    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)]
1179/// Possible values for `BackendOptions`.
1180pub enum BackendOptions {
1181    /// The `V4l2` variant.
1182    V4l2(V4l2Options),
1183    /// The `Camera2` variant.
1184    Camera2(Camera2Options),
1185    /// The `AvFoundation` variant.
1186    AvFoundation(AvFoundationOptions),
1187}
1188
1189impl BackendOptions {
1190    /// Performs the `backend` operation.
1191    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}