1use crate::{BackendAttempt, BackendId, DeviceId, OperationStage};
4use std::{error::Error as StdError, fmt, str::FromStr};
5use thiserror::Error;
6
7#[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 InvalidArgument,
15 BackendNotCompiled,
17 UnsupportedTarget,
19 BackendOptionMismatch,
21 BackendFailure,
23 MultipleBackendsFailed,
25 DeviceNotFound,
27 DeviceBusy,
29 DeviceOpenFailed,
31 DeviceDisconnected,
33 AmbiguousDevice,
35 PermissionRequired,
37 PermissionDenied,
39 PermissionManagedExternally,
41 InvalidState,
43 StreamStopped,
45 StreamFailure,
47 Timeout,
49 BufferExhausted,
51 InvalidFrame,
53 UnsupportedFormat,
55 ControlNotSupported,
57 ControlNotReadable,
59 ControlFailure,
61 Io,
63 WorkerFailure,
65 Internal,
67}
68
69impl CameraErrorKind {
70 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#[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 None,
152 Retry,
154 RequestPermission,
156 ReenumerateDevice,
158 ChangeConfiguration,
160 EnableBackend,
162 DropFrame,
164 ReduceResourceUsage,
166}
167
168impl RecoveryHint {
169 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 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#[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 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 pub fn kind(&self) -> CameraErrorKind {
274 self.kind
275 }
276 pub fn code(&self) -> &'static str {
278 self.kind.as_str()
279 }
280 pub fn recovery_hint(&self) -> RecoveryHint {
282 self.recovery_hint
283 }
284 pub fn is_retryable(&self) -> bool {
286 self.recovery_hint.is_retryable()
287 }
288 pub fn backend(&self) -> Option<&BackendId> {
290 self.details.backend.as_ref()
291 }
292 pub fn device(&self) -> Option<&DeviceId> {
294 self.details.device.as_ref()
295 }
296 pub fn stage(&self) -> Option<OperationStage> {
298 self.details.stage
299 }
300 pub fn operation(&self) -> Option<&str> {
302 self.details.operation.as_deref()
303 }
304 pub fn native_code(&self) -> Option<i64> {
306 self.details.native_code
307 }
308 pub fn io_error(&self) -> Option<&std::io::Error> {
310 self.source_error()?.downcast_ref::<std::io::Error>()
311 }
312 pub fn source_error(&self) -> Option<&(dyn StdError + Send + Sync + 'static)> {
314 self.source.as_ref().map(SharedSource::get)
315 }
316 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 pub fn causes(&self) -> &[std::sync::Arc<CameraError>] {
323 &self.details.causes
324 }
325
326 pub fn with_backend(mut self, backend: BackendId) -> Self {
328 self.details.backend = Some(backend);
329 self
330 }
331 pub fn with_device(mut self, device: DeviceId) -> Self {
333 self.details.device = Some(device);
334 self
335 }
336 pub fn with_stage(mut self, stage: OperationStage) -> Self {
338 self.details.stage = Some(stage);
339 self
340 }
341 pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
343 self.details.operation = Some(operation.into());
344 self
345 }
346 pub fn with_native_code(mut self, code: i64) -> Self {
348 self.details.native_code = Some(code);
349 self
350 }
351 pub fn with_recovery_hint(mut self, hint: RecoveryHint) -> Self {
353 self.recovery_hint = hint;
354 self
355 }
356 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 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 pub fn invalid_config(message: String) -> Self {
375 Self::invalid_argument("configuration", message)
376 }
377 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 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 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 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 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 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 pub fn device_busy(message: String) -> Self {
451 Self::new(
452 CameraErrorKind::DeviceBusy,
453 format!("Device is busy: {message}"),
454 )
455 }
456 pub fn permission_required(message: String) -> Self {
458 Self::new(
459 CameraErrorKind::PermissionRequired,
460 format!("Permission is required before opening {message}"),
461 )
462 }
463 pub fn permission_denied(message: String) -> Self {
465 Self::new(
466 CameraErrorKind::PermissionDenied,
467 format!("Permission denied: {message}"),
468 )
469 }
470 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 pub fn stream_stopped() -> Self {
478 Self::new(CameraErrorKind::StreamStopped, "Stream stopped")
479 }
480 pub fn invalid_state(message: String) -> Self {
482 Self::new(
483 CameraErrorKind::InvalidState,
484 format!("Invalid state: {message}"),
485 )
486 }
487 pub fn ambiguous_device(message: String) -> Self {
489 Self::new(
490 CameraErrorKind::AmbiguousDevice,
491 format!("Device identity is ambiguous: {message}"),
492 )
493 }
494 pub fn disconnected(message: String) -> Self {
496 Self::new(
497 CameraErrorKind::DeviceDisconnected,
498 format!("Device disconnected: {message}"),
499 )
500 }
501 pub fn control_not_readable(message: String) -> Self {
503 Self::new(
504 CameraErrorKind::ControlNotReadable,
505 format!("Control is not readable: {message}"),
506 )
507 }
508 pub fn device_not_found(message: String) -> Self {
510 Self::new(
511 CameraErrorKind::DeviceNotFound,
512 format!("Device not found: {message}"),
513 )
514 }
515 pub fn device_open_failed(message: String) -> Self {
517 Self::new(
518 CameraErrorKind::DeviceOpenFailed,
519 format!("Failed to open device: {message}"),
520 )
521 }
522 pub fn invalid_frame(message: String) -> Self {
524 Self::new(
525 CameraErrorKind::InvalidFrame,
526 format!("Invalid frame: {message}"),
527 )
528 }
529 pub fn unsupported_format(message: String) -> Self {
531 Self::new(
532 CameraErrorKind::UnsupportedFormat,
533 format!("Unsupported format: {message}"),
534 )
535 }
536 pub fn stream_error(message: String) -> Self {
538 Self::new(
539 CameraErrorKind::StreamFailure,
540 format!("Stream error: {message}"),
541 )
542 }
543 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 pub fn buffer_exhausted() -> Self {
553 Self::new(CameraErrorKind::BufferExhausted, "Frame buffer exhausted")
554 }
555 pub fn control_not_supported(message: String) -> Self {
557 Self::new(
558 CameraErrorKind::ControlNotSupported,
559 format!("Control not supported: {message}"),
560 )
561 }
562 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 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 pub fn worker_failure(message: String) -> Self {
590 Self::new(CameraErrorKind::WorkerFailure, message).with_stage(OperationStage::Worker)
591 }
592 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(
623 test,
624 all(
625 feature = "backend-uvc",
626 any(target_os = "linux", target_os = "macos", target_os = "android")
627 )
628 ))]
629 pub(crate) fn uvc(code: i32, operation: String) -> Self {
630 let mut error = Self::uvc_backend(code, operation);
631 error.kind = match error.kind {
632 CameraErrorKind::UnsupportedFormat => CameraErrorKind::ControlNotSupported,
633 CameraErrorKind::BackendFailure => CameraErrorKind::ControlFailure,
634 kind => kind,
635 };
636 error.recovery_hint = default_recovery_hint(error.kind);
637 error
638 }
639}
640
641#[derive(Clone, Debug)]
642struct SharedSource(std::sync::Arc<dyn StdError + Send + Sync + 'static>);
643
644impl SharedSource {
645 fn get(&self) -> &(dyn StdError + Send + Sync + 'static) {
646 self.0.as_ref()
647 }
648}
649
650impl fmt::Display for SharedSource {
651 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
652 fmt::Display::fmt(self.0.as_ref(), formatter)
653 }
654}
655
656impl StdError for SharedSource {
657 fn source(&self) -> Option<&(dyn StdError + 'static)> {
658 Some(self.0.as_ref())
659 }
660}
661
662impl From<std::io::Error> for CameraError {
663 fn from(source: std::io::Error) -> Self {
664 Self::io(OperationStage::BackendCommand, source)
665 }
666}
667
668fn default_recovery_hint(kind: CameraErrorKind) -> RecoveryHint {
669 match kind {
670 CameraErrorKind::PermissionRequired
671 | CameraErrorKind::PermissionDenied
672 | CameraErrorKind::PermissionManagedExternally => RecoveryHint::RequestPermission,
673 CameraErrorKind::DeviceNotFound | CameraErrorKind::DeviceDisconnected => {
674 RecoveryHint::ReenumerateDevice
675 }
676 CameraErrorKind::DeviceBusy
677 | CameraErrorKind::DeviceOpenFailed
678 | CameraErrorKind::BackendFailure
679 | CameraErrorKind::StreamFailure
680 | CameraErrorKind::Timeout
681 | CameraErrorKind::Io
682 | CameraErrorKind::WorkerFailure => RecoveryHint::Retry,
683 CameraErrorKind::InvalidArgument
684 | CameraErrorKind::UnsupportedFormat
685 | CameraErrorKind::ControlNotSupported
686 | CameraErrorKind::ControlNotReadable => RecoveryHint::ChangeConfiguration,
687 CameraErrorKind::BackendNotCompiled | CameraErrorKind::UnsupportedTarget => {
688 RecoveryHint::EnableBackend
689 }
690 CameraErrorKind::InvalidFrame => RecoveryHint::DropFrame,
691 CameraErrorKind::BufferExhausted => RecoveryHint::ReduceResourceUsage,
692 CameraErrorKind::BackendOptionMismatch
693 | CameraErrorKind::MultipleBackendsFailed
694 | CameraErrorKind::AmbiguousDevice
695 | CameraErrorKind::InvalidState
696 | CameraErrorKind::StreamStopped
697 | CameraErrorKind::ControlFailure
698 | CameraErrorKind::Internal => RecoveryHint::None,
699 }
700}
701
702fn aggregate_recovery_hint(hints: impl IntoIterator<Item = RecoveryHint>) -> RecoveryHint {
703 hints
704 .into_iter()
705 .max_by_key(|hint| match hint {
706 RecoveryHint::None => 0,
707 RecoveryHint::DropFrame => 1,
708 RecoveryHint::EnableBackend => 2,
709 RecoveryHint::ChangeConfiguration => 3,
710 RecoveryHint::ReduceResourceUsage => 4,
711 RecoveryHint::Retry => 5,
712 RecoveryHint::ReenumerateDevice => 6,
713 RecoveryHint::RequestPermission => 7,
714 })
715 .unwrap_or(RecoveryHint::None)
716}
717
718#[allow(dead_code)]
719#[repr(i32)]
720#[derive(Debug, Clone, Copy, PartialEq, Eq)]
721pub(crate) enum UvcErrorCode {
722 Success = 0,
723 Io = -1,
724 InvalidParam = -2,
725 Access = -3,
726 NoDevice = -4,
727 NotFound = -5,
728 Busy = -6,
729 Timeout = -7,
730 Overflow = -8,
731 Pipe = -9,
732 Interrupted = -10,
733 NoMem = -11,
734 NotSupported = -12,
735 InvalidDevice = -50,
736 InvalidMode = -51,
737 CallbackExists = -52,
738 Other = -99,
739}
740
741#[allow(dead_code)]
742impl UvcErrorCode {
743 pub fn from_code(code: i32) -> Self {
744 match code {
745 0 => Self::Success,
746 -1 => Self::Io,
747 -2 => Self::InvalidParam,
748 -3 => Self::Access,
749 -4 => Self::NoDevice,
750 -5 => Self::NotFound,
751 -6 => Self::Busy,
752 -7 => Self::Timeout,
753 -8 => Self::Overflow,
754 -9 => Self::Pipe,
755 -10 => Self::Interrupted,
756 -11 => Self::NoMem,
757 -12 => Self::NotSupported,
758 -50 => Self::InvalidDevice,
759 -51 => Self::InvalidMode,
760 -52 => Self::CallbackExists,
761 _ => Self::Other,
762 }
763 }
764 pub fn message(self) -> &'static str {
765 match self {
766 Self::Success => "Success",
767 Self::Io => "I/O error",
768 Self::InvalidParam => "Invalid parameter",
769 Self::Access => "Access denied",
770 Self::NoDevice => "Device does not exist",
771 Self::NotFound => "Not found",
772 Self::Busy => "Device busy",
773 Self::Timeout => "Timeout",
774 Self::Overflow => "Buffer overflow",
775 Self::Pipe => "Pipe error",
776 Self::Interrupted => "Operation interrupted",
777 Self::NoMem => "Out of memory",
778 Self::NotSupported => "Not supported",
779 Self::InvalidDevice => "Invalid device",
780 Self::InvalidMode => "Invalid mode",
781 Self::CallbackExists => "Callback already exists",
782 Self::Other => "Other error",
783 }
784 }
785 pub fn check(
786 code: i32,
787 stage: OperationStage,
788 operation: &'static str,
789 ) -> std::result::Result<(), CameraError> {
790 if code == 0 {
791 Ok(())
792 } else {
793 Err(CameraError::uvc_backend(code, operation.into()).with_stage(stage))
794 }
795 }
796}
797
798impl fmt::Display for CameraErrorKind {
799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800 f.write_str(self.as_str())
801 }
802}
803
804impl fmt::Display for RecoveryHint {
805 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806 f.write_str(self.as_str())
807 }
808}
809
810pub(crate) type Result<T> = std::result::Result<T, CameraError>;
811
812#[cfg(test)]
813mod tests {
814 use super::*;
815 #[test]
816 fn uvc_statuses_are_semantically_normalized() {
817 assert_eq!(
818 CameraError::uvc_backend(-3, "open".into()).kind(),
819 CameraErrorKind::PermissionDenied
820 );
821 assert_eq!(
822 CameraError::uvc_backend(-6, "open".into()).kind(),
823 CameraErrorKind::DeviceBusy
824 );
825 assert_eq!(
826 CameraError::uvc_backend(-7, "read".into()).kind(),
827 CameraErrorKind::Timeout
828 );
829 assert_eq!(
830 CameraError::uvc(-12, "query exposure".into()).kind(),
831 CameraErrorKind::ControlNotSupported
832 );
833 }
834}