Skip to main content

camera/
error.rs

1//! Stable, backend-neutral error contract.
2
3use crate::{BackendAttempt, BackendId, DeviceId, OperationStage};
4use std::{error::Error as StdError, fmt, str::FromStr};
5use thiserror::Error;
6
7/// Stable semantic category intended for caller-side branching.
8#[non_exhaustive]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum CameraErrorKind {
13    /// The `InvalidArgument` variant.
14    InvalidArgument,
15    /// The `BackendNotCompiled` variant.
16    BackendNotCompiled,
17    /// The `UnsupportedTarget` variant.
18    UnsupportedTarget,
19    /// The `BackendOptionMismatch` variant.
20    BackendOptionMismatch,
21    /// The `BackendFailure` variant.
22    BackendFailure,
23    /// The `MultipleBackendsFailed` variant.
24    MultipleBackendsFailed,
25    /// The `DeviceNotFound` variant.
26    DeviceNotFound,
27    /// The `DeviceBusy` variant.
28    DeviceBusy,
29    /// The `DeviceOpenFailed` variant.
30    DeviceOpenFailed,
31    /// The `DeviceDisconnected` variant.
32    DeviceDisconnected,
33    /// The `AmbiguousDevice` variant.
34    AmbiguousDevice,
35    /// The `PermissionRequired` variant.
36    PermissionRequired,
37    /// The `PermissionDenied` variant.
38    PermissionDenied,
39    /// The `PermissionManagedExternally` variant.
40    PermissionManagedExternally,
41    /// The `InvalidState` variant.
42    InvalidState,
43    /// The `StreamStopped` variant.
44    StreamStopped,
45    /// The `StreamFailure` variant.
46    StreamFailure,
47    /// The `Timeout` variant.
48    Timeout,
49    /// The `BufferExhausted` variant.
50    BufferExhausted,
51    /// The `InvalidFrame` variant.
52    InvalidFrame,
53    /// The `UnsupportedFormat` variant.
54    UnsupportedFormat,
55    /// The `ControlNotSupported` variant.
56    ControlNotSupported,
57    /// The `ControlNotReadable` variant.
58    ControlNotReadable,
59    /// The `ControlFailure` variant.
60    ControlFailure,
61    /// The `Io` variant.
62    Io,
63    /// The `WorkerFailure` variant.
64    WorkerFailure,
65    /// The `Internal` variant.
66    Internal,
67}
68
69impl CameraErrorKind {
70    /// Stable machine-readable code for logs, FFI boundaries, and API responses.
71    pub const fn as_str(self) -> &'static str {
72        match self {
73            Self::InvalidArgument => "invalid_argument",
74            Self::BackendNotCompiled => "backend_not_compiled",
75            Self::UnsupportedTarget => "unsupported_target",
76            Self::BackendOptionMismatch => "backend_option_mismatch",
77            Self::BackendFailure => "backend_failure",
78            Self::MultipleBackendsFailed => "multiple_backends_failed",
79            Self::DeviceNotFound => "device_not_found",
80            Self::DeviceBusy => "device_busy",
81            Self::DeviceOpenFailed => "device_open_failed",
82            Self::DeviceDisconnected => "device_disconnected",
83            Self::AmbiguousDevice => "ambiguous_device",
84            Self::PermissionRequired => "permission_required",
85            Self::PermissionDenied => "permission_denied",
86            Self::PermissionManagedExternally => "permission_managed_externally",
87            Self::InvalidState => "invalid_state",
88            Self::StreamStopped => "stream_stopped",
89            Self::StreamFailure => "stream_failure",
90            Self::Timeout => "timeout",
91            Self::BufferExhausted => "buffer_exhausted",
92            Self::InvalidFrame => "invalid_frame",
93            Self::UnsupportedFormat => "unsupported_format",
94            Self::ControlNotSupported => "control_not_supported",
95            Self::ControlNotReadable => "control_not_readable",
96            Self::ControlFailure => "control_failure",
97            Self::Io => "io",
98            Self::WorkerFailure => "worker_failure",
99            Self::Internal => "internal",
100        }
101    }
102}
103
104impl FromStr for CameraErrorKind {
105    type Err = CameraError;
106
107    fn from_str(code: &str) -> Result<Self> {
108        match code {
109            "invalid_argument" => Ok(Self::InvalidArgument),
110            "backend_not_compiled" => Ok(Self::BackendNotCompiled),
111            "unsupported_target" => Ok(Self::UnsupportedTarget),
112            "backend_option_mismatch" => Ok(Self::BackendOptionMismatch),
113            "backend_failure" => Ok(Self::BackendFailure),
114            "multiple_backends_failed" => Ok(Self::MultipleBackendsFailed),
115            "device_not_found" => Ok(Self::DeviceNotFound),
116            "device_busy" => Ok(Self::DeviceBusy),
117            "device_open_failed" => Ok(Self::DeviceOpenFailed),
118            "device_disconnected" => Ok(Self::DeviceDisconnected),
119            "ambiguous_device" => Ok(Self::AmbiguousDevice),
120            "permission_required" => Ok(Self::PermissionRequired),
121            "permission_denied" => Ok(Self::PermissionDenied),
122            "permission_managed_externally" => Ok(Self::PermissionManagedExternally),
123            "invalid_state" => Ok(Self::InvalidState),
124            "stream_stopped" => Ok(Self::StreamStopped),
125            "stream_failure" => Ok(Self::StreamFailure),
126            "timeout" => Ok(Self::Timeout),
127            "buffer_exhausted" => Ok(Self::BufferExhausted),
128            "invalid_frame" => Ok(Self::InvalidFrame),
129            "unsupported_format" => Ok(Self::UnsupportedFormat),
130            "control_not_supported" => Ok(Self::ControlNotSupported),
131            "control_not_readable" => Ok(Self::ControlNotReadable),
132            "control_failure" => Ok(Self::ControlFailure),
133            "io" => Ok(Self::Io),
134            "worker_failure" => Ok(Self::WorkerFailure),
135            "internal" => Ok(Self::Internal),
136            _ => Err(CameraError::invalid_argument(
137                "camera error code",
138                code.to_owned(),
139            )),
140        }
141    }
142}
143
144/// Conservative action a caller can take without inspecting backend text.
145#[non_exhaustive]
146#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
147#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
149pub enum RecoveryHint {
150    /// The `None` variant.
151    None,
152    /// The `Retry` variant.
153    Retry,
154    /// The `RequestPermission` variant.
155    RequestPermission,
156    /// The `ReenumerateDevice` variant.
157    ReenumerateDevice,
158    /// The `ChangeConfiguration` variant.
159    ChangeConfiguration,
160    /// The `EnableBackend` variant.
161    EnableBackend,
162    /// The `DropFrame` variant.
163    DropFrame,
164    /// The `ReduceResourceUsage` variant.
165    ReduceResourceUsage,
166}
167
168impl RecoveryHint {
169    /// Stable machine-readable recovery action.
170    pub const fn as_str(self) -> &'static str {
171        match self {
172            Self::None => "none",
173            Self::Retry => "retry",
174            Self::RequestPermission => "request_permission",
175            Self::ReenumerateDevice => "reenumerate_device",
176            Self::ChangeConfiguration => "change_configuration",
177            Self::EnableBackend => "enable_backend",
178            Self::DropFrame => "drop_frame",
179            Self::ReduceResourceUsage => "reduce_resource_usage",
180        }
181    }
182
183    /// The `fn` constant.
184    pub const fn is_retryable(self) -> bool {
185        matches!(self, Self::Retry | Self::ReenumerateDevice)
186    }
187}
188
189impl FromStr for RecoveryHint {
190    type Err = CameraError;
191
192    fn from_str(code: &str) -> Result<Self> {
193        match code {
194            "none" => Ok(Self::None),
195            "retry" => Ok(Self::Retry),
196            "request_permission" => Ok(Self::RequestPermission),
197            "reenumerate_device" => Ok(Self::ReenumerateDevice),
198            "change_configuration" => Ok(Self::ChangeConfiguration),
199            "enable_backend" => Ok(Self::EnableBackend),
200            "drop_frame" => Ok(Self::DropFrame),
201            "reduce_resource_usage" => Ok(Self::ReduceResourceUsage),
202            _ => Err(CameraError::invalid_argument(
203                "camera recovery code",
204                code.to_owned(),
205            )),
206        }
207    }
208}
209
210/// One public error type returned by every camera operation.
211///
212/// The representation is a struct so new diagnostics do not force downstream
213/// users to update exhaustive enum matches. Branch on [`Self::kind`] instead.
214#[derive(Clone, Debug, Error)]
215#[error("{message}")]
216pub struct CameraError {
217    kind: CameraErrorKind,
218    recovery_hint: RecoveryHint,
219    message: String,
220    #[source]
221    source: Option<SharedSource>,
222    details: Box<CameraErrorDetails>,
223}
224
225#[derive(Clone, Debug)]
226struct CameraErrorDetails {
227    backend: Option<BackendId>,
228    device: Option<DeviceId>,
229    stage: Option<OperationStage>,
230    operation: Option<String>,
231    native_code: Option<i64>,
232    backend_attempts: Vec<BackendAttempt>,
233    causes: Vec<std::sync::Arc<CameraError>>,
234}
235
236impl PartialEq for CameraError {
237    fn eq(&self, other: &Self) -> bool {
238        self.kind == other.kind
239            && self.recovery_hint == other.recovery_hint
240            && self.message == other.message
241            && self.details.backend == other.details.backend
242            && self.details.device == other.details.device
243            && self.details.stage == other.details.stage
244            && self.details.operation == other.details.operation
245            && self.details.native_code == other.details.native_code
246            && self.details.backend_attempts == other.details.backend_attempts
247            && self.details.causes == other.details.causes
248    }
249}
250impl Eq for CameraError {}
251
252impl CameraError {
253    /// Performs the `new` operation.
254    pub fn new(kind: CameraErrorKind, message: impl Into<String>) -> Self {
255        Self {
256            kind,
257            recovery_hint: default_recovery_hint(kind),
258            message: message.into(),
259            source: None,
260            details: Box::new(CameraErrorDetails {
261                backend: None,
262                device: None,
263                stage: None,
264                operation: None,
265                native_code: None,
266                backend_attempts: Vec::new(),
267                causes: Vec::new(),
268            }),
269        }
270    }
271
272    /// Performs the `kind` operation.
273    pub fn kind(&self) -> CameraErrorKind {
274        self.kind
275    }
276    /// Performs the `code` operation.
277    pub fn code(&self) -> &'static str {
278        self.kind.as_str()
279    }
280    /// Performs the `recovery_hint` operation.
281    pub fn recovery_hint(&self) -> RecoveryHint {
282        self.recovery_hint
283    }
284    /// Performs the `is_retryable` operation.
285    pub fn is_retryable(&self) -> bool {
286        self.recovery_hint.is_retryable()
287    }
288    /// Performs the `backend` operation.
289    pub fn backend(&self) -> Option<&BackendId> {
290        self.details.backend.as_ref()
291    }
292    /// Performs the `device` operation.
293    pub fn device(&self) -> Option<&DeviceId> {
294        self.details.device.as_ref()
295    }
296    /// Performs the `stage` operation.
297    pub fn stage(&self) -> Option<OperationStage> {
298        self.details.stage
299    }
300    /// Performs the `operation` operation.
301    pub fn operation(&self) -> Option<&str> {
302        self.details.operation.as_deref()
303    }
304    /// Performs the `native_code` operation.
305    pub fn native_code(&self) -> Option<i64> {
306        self.details.native_code
307    }
308    /// Performs the `io_error` operation.
309    pub fn io_error(&self) -> Option<&std::io::Error> {
310        self.source_error()?.downcast_ref::<std::io::Error>()
311    }
312    /// Performs the `source_error` operation.
313    pub fn source_error(&self) -> Option<&(dyn StdError + Send + Sync + 'static)> {
314        self.source.as_ref().map(SharedSource::get)
315    }
316    /// Performs the `backend_attempts` operation.
317    pub fn backend_attempts(&self) -> Option<&[BackendAttempt]> {
318        (!self.details.backend_attempts.is_empty())
319            .then_some(self.details.backend_attempts.as_slice())
320    }
321    /// Performs the `causes` operation.
322    pub fn causes(&self) -> &[std::sync::Arc<CameraError>] {
323        &self.details.causes
324    }
325
326    /// Performs the `with_backend` operation.
327    pub fn with_backend(mut self, backend: BackendId) -> Self {
328        self.details.backend = Some(backend);
329        self
330    }
331    /// Performs the `with_device` operation.
332    pub fn with_device(mut self, device: DeviceId) -> Self {
333        self.details.device = Some(device);
334        self
335    }
336    /// Performs the `with_stage` operation.
337    pub fn with_stage(mut self, stage: OperationStage) -> Self {
338        self.details.stage = Some(stage);
339        self
340    }
341    /// Performs the `with_operation` operation.
342    pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
343        self.details.operation = Some(operation.into());
344        self
345    }
346    /// Performs the `with_native_code` operation.
347    pub fn with_native_code(mut self, code: i64) -> Self {
348        self.details.native_code = Some(code);
349        self
350    }
351    /// Performs the `with_recovery_hint` operation.
352    pub fn with_recovery_hint(mut self, hint: RecoveryHint) -> Self {
353        self.recovery_hint = hint;
354        self
355    }
356    /// Performs the `with_source` operation.
357    pub fn with_source<E>(mut self, source: E) -> Self
358    where
359        E: StdError + Send + Sync + 'static,
360    {
361        self.source = Some(SharedSource(std::sync::Arc::new(source)));
362        self
363    }
364
365    /// Performs the `invalid_argument` operation.
366    pub fn invalid_argument(field: &'static str, message: String) -> Self {
367        Self::new(
368            CameraErrorKind::InvalidArgument,
369            format!("Invalid {field}: {message}"),
370        )
371        .with_operation(field)
372    }
373    /// Performs the `invalid_config` operation.
374    pub fn invalid_config(message: String) -> Self {
375        Self::invalid_argument("configuration", message)
376    }
377    /// Performs the `backend_not_compiled` operation.
378    pub fn backend_not_compiled(backend: BackendId) -> Self {
379        Self::new(
380            CameraErrorKind::BackendNotCompiled,
381            format!("Backend {backend} was not compiled into this build"),
382        )
383        .with_backend(backend)
384    }
385    /// Performs the `unsupported_target` operation.
386    pub fn unsupported_target(backend: BackendId, target: &'static str) -> Self {
387        Self::new(
388            CameraErrorKind::UnsupportedTarget,
389            format!("Backend {backend} is unsupported on target {target}"),
390        )
391        .with_backend(backend)
392    }
393    /// Performs the `backend_option_mismatch` operation.
394    pub fn backend_option_mismatch(option_backend: BackendId, selected_backend: BackendId) -> Self {
395        Self::new(
396            CameraErrorKind::BackendOptionMismatch,
397            format!("Backend option for {option_backend} cannot be used with {selected_backend}"),
398        )
399        .with_backend(selected_backend)
400    }
401    /// Performs the `backend_failure` operation.
402    pub fn backend_failure(backend: BackendId, stage: OperationStage, message: String) -> Self {
403        Self::new(CameraErrorKind::BackendFailure, message)
404            .with_backend(backend)
405            .with_stage(stage)
406    }
407    /// Performs the `native` operation.
408    pub fn native(
409        kind: CameraErrorKind,
410        backend: BackendId,
411        stage: OperationStage,
412        operation: String,
413        code: i64,
414        message: String,
415    ) -> Self {
416        Self::new(
417            kind,
418            format!("{backend} {operation} failed (code {code}): {message}"),
419        )
420        .with_backend(backend)
421        .with_stage(stage)
422        .with_operation(operation)
423        .with_native_code(code)
424    }
425    /// Performs the `all_backends_failed` operation.
426    pub fn all_backends_failed(attempts: Vec<BackendAttempt>) -> Self {
427        let details = attempts
428            .iter()
429            .map(|attempt| format!("{}: {}", attempt.backend(), attempt.error()))
430            .collect::<Vec<_>>()
431            .join("; ");
432        let recovery_hint = aggregate_recovery_hint(
433            attempts
434                .iter()
435                .map(|attempt| attempt.error().recovery_hint()),
436        );
437        let source = attempts
438            .first()
439            .map(|attempt| attempt.shared_error().clone());
440        let mut error = Self::new(
441            CameraErrorKind::MultipleBackendsFailed,
442            format!("All preferred backends failed: {details}"),
443        )
444        .with_recovery_hint(recovery_hint);
445        error.source = source.map(|source| SharedSource(source));
446        error.details.backend_attempts = attempts;
447        error
448    }
449    /// Performs the `device_busy` operation.
450    pub fn device_busy(message: String) -> Self {
451        Self::new(
452            CameraErrorKind::DeviceBusy,
453            format!("Device is busy: {message}"),
454        )
455    }
456    /// Performs the `permission_required` operation.
457    pub fn permission_required(message: String) -> Self {
458        Self::new(
459            CameraErrorKind::PermissionRequired,
460            format!("Permission is required before opening {message}"),
461        )
462    }
463    /// Performs the `permission_denied` operation.
464    pub fn permission_denied(message: String) -> Self {
465        Self::new(
466            CameraErrorKind::PermissionDenied,
467            format!("Permission denied: {message}"),
468        )
469    }
470    /// Performs the `permission_managed_externally` operation.
471    pub fn permission_managed_externally(backend: BackendId) -> Self {
472        Self::new(CameraErrorKind::PermissionManagedExternally,
473            format!("Permission for backend {backend} is managed by the application or platform adapter"))
474            .with_backend(backend)
475    }
476    /// Performs the `stream_stopped` operation.
477    pub fn stream_stopped() -> Self {
478        Self::new(CameraErrorKind::StreamStopped, "Stream stopped")
479    }
480    /// Performs the `invalid_state` operation.
481    pub fn invalid_state(message: String) -> Self {
482        Self::new(
483            CameraErrorKind::InvalidState,
484            format!("Invalid state: {message}"),
485        )
486    }
487    /// Performs the `ambiguous_device` operation.
488    pub fn ambiguous_device(message: String) -> Self {
489        Self::new(
490            CameraErrorKind::AmbiguousDevice,
491            format!("Device identity is ambiguous: {message}"),
492        )
493    }
494    /// Performs the `disconnected` operation.
495    pub fn disconnected(message: String) -> Self {
496        Self::new(
497            CameraErrorKind::DeviceDisconnected,
498            format!("Device disconnected: {message}"),
499        )
500    }
501    /// Performs the `control_not_readable` operation.
502    pub fn control_not_readable(message: String) -> Self {
503        Self::new(
504            CameraErrorKind::ControlNotReadable,
505            format!("Control is not readable: {message}"),
506        )
507    }
508    /// Performs the `device_not_found` operation.
509    pub fn device_not_found(message: String) -> Self {
510        Self::new(
511            CameraErrorKind::DeviceNotFound,
512            format!("Device not found: {message}"),
513        )
514    }
515    /// Performs the `device_open_failed` operation.
516    pub fn device_open_failed(message: String) -> Self {
517        Self::new(
518            CameraErrorKind::DeviceOpenFailed,
519            format!("Failed to open device: {message}"),
520        )
521    }
522    /// Performs the `invalid_frame` operation.
523    pub fn invalid_frame(message: String) -> Self {
524        Self::new(
525            CameraErrorKind::InvalidFrame,
526            format!("Invalid frame: {message}"),
527        )
528    }
529    /// Performs the `unsupported_format` operation.
530    pub fn unsupported_format(message: String) -> Self {
531        Self::new(
532            CameraErrorKind::UnsupportedFormat,
533            format!("Unsupported format: {message}"),
534        )
535    }
536    /// Performs the `stream_error` operation.
537    pub fn stream_error(message: String) -> Self {
538        Self::new(
539            CameraErrorKind::StreamFailure,
540            format!("Stream error: {message}"),
541        )
542    }
543    /// Performs the `timeout` operation.
544    pub fn timeout(stage: OperationStage) -> Self {
545        Self::new(
546            CameraErrorKind::Timeout,
547            format!("Operation timed out during {stage:?}"),
548        )
549        .with_stage(stage)
550    }
551    /// Performs the `buffer_exhausted` operation.
552    pub fn buffer_exhausted() -> Self {
553        Self::new(CameraErrorKind::BufferExhausted, "Frame buffer exhausted")
554    }
555    /// Performs the `control_not_supported` operation.
556    pub fn control_not_supported(message: String) -> Self {
557        Self::new(
558            CameraErrorKind::ControlNotSupported,
559            format!("Control not supported: {message}"),
560        )
561    }
562    /// Performs the `control_batch` operation.
563    pub fn control_batch(causes: Vec<std::sync::Arc<CameraError>>) -> Self {
564        let details = causes
565            .iter()
566            .map(ToString::to_string)
567            .collect::<Vec<_>>()
568            .join("; ");
569        let recovery_hint =
570            aggregate_recovery_hint(causes.iter().map(|cause| cause.recovery_hint()));
571        let source = causes.first().cloned();
572        let mut error = Self::new(
573            CameraErrorKind::ControlFailure,
574            format!("Control operations failed: {details}"),
575        )
576        .with_recovery_hint(recovery_hint);
577        error.source = source.map(|source| SharedSource(source));
578        error.details.causes = causes;
579        error
580    }
581    /// Performs the `io` operation.
582    pub fn io(stage: OperationStage, source: std::io::Error) -> Self {
583        let message = format!("I/O error during {stage:?}: {source}");
584        Self::new(CameraErrorKind::Io, message)
585            .with_stage(stage)
586            .with_source(source)
587    }
588    /// Performs the `worker_failure` operation.
589    pub fn worker_failure(message: String) -> Self {
590        Self::new(CameraErrorKind::WorkerFailure, message).with_stage(OperationStage::Worker)
591    }
592    /// Performs the `internal` operation.
593    pub fn internal(message: String) -> Self {
594        Self::new(
595            CameraErrorKind::Internal,
596            format!("Internal error: {message}"),
597        )
598    }
599    pub(crate) fn uvc_backend(code: i32, operation: String) -> Self {
600        let kind = match UvcErrorCode::from_code(code) {
601            UvcErrorCode::Access => CameraErrorKind::PermissionDenied,
602            UvcErrorCode::NoDevice | UvcErrorCode::NotFound | UvcErrorCode::InvalidDevice => {
603                CameraErrorKind::DeviceNotFound
604            }
605            UvcErrorCode::Busy => CameraErrorKind::DeviceBusy,
606            UvcErrorCode::Timeout => CameraErrorKind::Timeout,
607            UvcErrorCode::NotSupported => CameraErrorKind::UnsupportedFormat,
608            UvcErrorCode::InvalidParam | UvcErrorCode::InvalidMode => {
609                CameraErrorKind::InvalidArgument
610            }
611            _ => CameraErrorKind::BackendFailure,
612        };
613        Self::native(
614            kind,
615            BackendId::UVC,
616            OperationStage::BackendCommand,
617            operation,
618            i64::from(code),
619            UvcErrorCode::from_code(code).message().into(),
620        )
621    }
622    #[cfg(any(feature = "backend-uvc", test))]
623    pub(crate) fn uvc(code: i32, operation: String) -> Self {
624        let mut error = Self::uvc_backend(code, operation);
625        error.kind = match error.kind {
626            CameraErrorKind::UnsupportedFormat => CameraErrorKind::ControlNotSupported,
627            CameraErrorKind::BackendFailure => CameraErrorKind::ControlFailure,
628            kind => kind,
629        };
630        error.recovery_hint = default_recovery_hint(error.kind);
631        error
632    }
633}
634
635#[derive(Clone, Debug)]
636struct SharedSource(std::sync::Arc<dyn StdError + Send + Sync + 'static>);
637
638impl SharedSource {
639    fn get(&self) -> &(dyn StdError + Send + Sync + 'static) {
640        self.0.as_ref()
641    }
642}
643
644impl fmt::Display for SharedSource {
645    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
646        fmt::Display::fmt(self.0.as_ref(), formatter)
647    }
648}
649
650impl StdError for SharedSource {
651    fn source(&self) -> Option<&(dyn StdError + 'static)> {
652        Some(self.0.as_ref())
653    }
654}
655
656impl From<std::io::Error> for CameraError {
657    fn from(source: std::io::Error) -> Self {
658        Self::io(OperationStage::BackendCommand, source)
659    }
660}
661
662fn default_recovery_hint(kind: CameraErrorKind) -> RecoveryHint {
663    match kind {
664        CameraErrorKind::PermissionRequired
665        | CameraErrorKind::PermissionDenied
666        | CameraErrorKind::PermissionManagedExternally => RecoveryHint::RequestPermission,
667        CameraErrorKind::DeviceNotFound | CameraErrorKind::DeviceDisconnected => {
668            RecoveryHint::ReenumerateDevice
669        }
670        CameraErrorKind::DeviceBusy
671        | CameraErrorKind::DeviceOpenFailed
672        | CameraErrorKind::BackendFailure
673        | CameraErrorKind::StreamFailure
674        | CameraErrorKind::Timeout
675        | CameraErrorKind::Io
676        | CameraErrorKind::WorkerFailure => RecoveryHint::Retry,
677        CameraErrorKind::InvalidArgument
678        | CameraErrorKind::UnsupportedFormat
679        | CameraErrorKind::ControlNotSupported
680        | CameraErrorKind::ControlNotReadable => RecoveryHint::ChangeConfiguration,
681        CameraErrorKind::BackendNotCompiled | CameraErrorKind::UnsupportedTarget => {
682            RecoveryHint::EnableBackend
683        }
684        CameraErrorKind::InvalidFrame => RecoveryHint::DropFrame,
685        CameraErrorKind::BufferExhausted => RecoveryHint::ReduceResourceUsage,
686        CameraErrorKind::BackendOptionMismatch
687        | CameraErrorKind::MultipleBackendsFailed
688        | CameraErrorKind::AmbiguousDevice
689        | CameraErrorKind::InvalidState
690        | CameraErrorKind::StreamStopped
691        | CameraErrorKind::ControlFailure
692        | CameraErrorKind::Internal => RecoveryHint::None,
693    }
694}
695
696fn aggregate_recovery_hint(hints: impl IntoIterator<Item = RecoveryHint>) -> RecoveryHint {
697    hints
698        .into_iter()
699        .max_by_key(|hint| match hint {
700            RecoveryHint::None => 0,
701            RecoveryHint::DropFrame => 1,
702            RecoveryHint::EnableBackend => 2,
703            RecoveryHint::ChangeConfiguration => 3,
704            RecoveryHint::ReduceResourceUsage => 4,
705            RecoveryHint::Retry => 5,
706            RecoveryHint::ReenumerateDevice => 6,
707            RecoveryHint::RequestPermission => 7,
708        })
709        .unwrap_or(RecoveryHint::None)
710}
711
712#[allow(dead_code)]
713#[repr(i32)]
714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
715pub(crate) enum UvcErrorCode {
716    Success = 0,
717    Io = -1,
718    InvalidParam = -2,
719    Access = -3,
720    NoDevice = -4,
721    NotFound = -5,
722    Busy = -6,
723    Timeout = -7,
724    Overflow = -8,
725    Pipe = -9,
726    Interrupted = -10,
727    NoMem = -11,
728    NotSupported = -12,
729    InvalidDevice = -50,
730    InvalidMode = -51,
731    CallbackExists = -52,
732    Other = -99,
733}
734
735#[allow(dead_code)]
736impl UvcErrorCode {
737    pub fn from_code(code: i32) -> Self {
738        match code {
739            0 => Self::Success,
740            -1 => Self::Io,
741            -2 => Self::InvalidParam,
742            -3 => Self::Access,
743            -4 => Self::NoDevice,
744            -5 => Self::NotFound,
745            -6 => Self::Busy,
746            -7 => Self::Timeout,
747            -8 => Self::Overflow,
748            -9 => Self::Pipe,
749            -10 => Self::Interrupted,
750            -11 => Self::NoMem,
751            -12 => Self::NotSupported,
752            -50 => Self::InvalidDevice,
753            -51 => Self::InvalidMode,
754            -52 => Self::CallbackExists,
755            _ => Self::Other,
756        }
757    }
758    pub fn message(self) -> &'static str {
759        match self {
760            Self::Success => "Success",
761            Self::Io => "I/O error",
762            Self::InvalidParam => "Invalid parameter",
763            Self::Access => "Access denied",
764            Self::NoDevice => "Device does not exist",
765            Self::NotFound => "Not found",
766            Self::Busy => "Device busy",
767            Self::Timeout => "Timeout",
768            Self::Overflow => "Buffer overflow",
769            Self::Pipe => "Pipe error",
770            Self::Interrupted => "Operation interrupted",
771            Self::NoMem => "Out of memory",
772            Self::NotSupported => "Not supported",
773            Self::InvalidDevice => "Invalid device",
774            Self::InvalidMode => "Invalid mode",
775            Self::CallbackExists => "Callback already exists",
776            Self::Other => "Other error",
777        }
778    }
779    pub fn check(
780        code: i32,
781        stage: OperationStage,
782        operation: &'static str,
783    ) -> std::result::Result<(), CameraError> {
784        if code == 0 {
785            Ok(())
786        } else {
787            Err(CameraError::uvc_backend(code, operation.into()).with_stage(stage))
788        }
789    }
790}
791
792impl fmt::Display for CameraErrorKind {
793    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794        f.write_str(self.as_str())
795    }
796}
797
798impl fmt::Display for RecoveryHint {
799    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800        f.write_str(self.as_str())
801    }
802}
803
804pub(crate) type Result<T> = std::result::Result<T, CameraError>;
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809    #[test]
810    fn uvc_statuses_are_semantically_normalized() {
811        assert_eq!(
812            CameraError::uvc_backend(-3, "open".into()).kind(),
813            CameraErrorKind::PermissionDenied
814        );
815        assert_eq!(
816            CameraError::uvc_backend(-6, "open".into()).kind(),
817            CameraErrorKind::DeviceBusy
818        );
819        assert_eq!(
820            CameraError::uvc_backend(-7, "read".into()).kind(),
821            CameraErrorKind::Timeout
822        );
823        assert_eq!(
824            CameraError::uvc(-12, "query exposure".into()).kind(),
825            CameraErrorKind::ControlNotSupported
826        );
827    }
828}