Skip to main content

zenpixels_convert/
error.rs

1//! Structured conversion errors wrapped in [`whereat::At`] for source-site traces.
2
3use core::fmt;
4use whereat::At;
5use zenpixels::{BufferError, ColorError, LayoutError};
6
7/// Error returned when planning or executing a pixel conversion.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum ConvertError {
11    /// Underlying [`PixelFormat`](zenpixels::PixelFormat) validation error.
12    InvalidFormat(ColorError),
13    /// Underlying [`SampleLayout`](zenpixels::SampleLayout) validation error.
14    InvalidLayout(LayoutError),
15    /// Underlying pixel buffer geometry, alignment, or allocation error.
16    Buffer(BufferError),
17    /// Conversion crosses absolute PQ luminance ↔ relative linear light without a [`DiffuseWhite`](zenpixels::DiffuseWhite) anchor.
18    MissingHdrAnchor,
19    /// Conversion renders HLG into linear/SDR/PQ without explicit [`HlgRendering`](zenpixels::HlgRendering) conditions.
20    HlgRenderingRequired,
21    /// HDR tone mapping requested [`PeakSource::Declared`](zenpixels::PeakSource::Declared) but no MaxCLL or ST 2086 mastering peak was present.
22    MissingDeclaredPeak,
23    /// HDR transfer (`Pq` / `Hlg`) requires enabling the `hdr-transfers` Cargo feature.
24    HdrFeatureRequired,
25    /// Requested color space or operator requires an optional Cargo feature (`oklab`, `perceptual`, `bt2446a`, etc.).
26    FeatureRequired(&'static str),
27    /// Conversion involves an arbitrary ICC profile or CMYK ink space and requires a [`CmsBackend`](crate::cms::CmsBackend).
28    CmsRequired,
29    /// Destination has lower precision than source while `DepthPolicy::Forbid` is active.
30    DepthReductionForbidden,
31    /// Conversion drops non-opaque alpha while `AlphaPolicy::Forbid` or `DiscardIfOpaque` (unproven) is active.
32    AlphaLossForbidden,
33    /// Conversion changes `Full ↔ Narrow` signal range while `RangePolicy::Forbid` is active.
34    RangeConversionForbidden,
35    /// Conversion narrows gamut or clips extended values while `GamutPolicy::Forbid` is active.
36    GamutLossForbidden,
37    /// Conversion route is not supported (e.g., unknown primaries across a gamut change, or non-standard sample type).
38    UnsupportedRoute,
39    /// Source and destination dimensions or row byte lengths disagree.
40    DimensionMismatch,
41    /// Custom [`ToneMapper`](crate::tonemap::ToneMapper) declared `full_image = true`, which is not supported in streaming plans.
42    FullImageMapperNotSupported,
43    /// Custom [`ToneMapper`](crate::tonemap::ToneMapper) failed to prepare for this image context.
44    ToneMapperFailed,
45    /// CMS backend rejected or failed to execute the transform.
46    CmsBackendFailed,
47    /// Requested container color signaling (`CicpOnly` / `EmbedIcc`) is not available for the destination color space.
48    OutputSignalingUnavailable,
49    /// Requested container color signaling (`SameAsOrigin` / `CustomIcc`) contradicts the destination pixels.
50    OutputSignalingMismatch,
51    /// Heap allocation failed.
52    AllocationFailed,
53    /// Cooperative cancellation was triggered via [`enough::Stop`] or [`how_far::Pulse`].
54    Cancelled(enough::StopReason),
55}
56
57impl From<enough::StopReason> for ConvertError {
58    fn from(r: enough::StopReason) -> Self {
59        Self::Cancelled(r)
60    }
61}
62
63impl enough::AsStopReason for ConvertError {
64    fn as_stop_reason(&self) -> Option<enough::StopReason> {
65        match self {
66            Self::Cancelled(r) => Some(*r),
67            _ => None,
68        }
69    }
70}
71
72impl From<ColorError> for ConvertError {
73    fn from(e: ColorError) -> Self {
74        Self::InvalidFormat(e)
75    }
76}
77
78impl From<LayoutError> for ConvertError {
79    fn from(e: LayoutError) -> Self {
80        Self::InvalidLayout(e)
81    }
82}
83
84impl From<BufferError> for ConvertError {
85    fn from(e: BufferError) -> Self {
86        match e {
87            BufferError::AllocationFailed => Self::AllocationFailed,
88            other => Self::Buffer(other),
89        }
90    }
91}
92
93impl fmt::Display for ConvertError {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        match self {
96            Self::InvalidFormat(e) => e.fmt(f),
97            Self::InvalidLayout(e) => e.fmt(f),
98            Self::Buffer(e) => e.fmt(f),
99            Self::MissingHdrAnchor => f.write_str(
100                "conversion between absolute PQ and relative light requires a DiffuseWhite anchor",
101            ),
102            Self::HlgRenderingRequired => f.write_str(
103                "converting scene-referred HLG requires explicit HlgRendering conditions",
104            ),
105            Self::MissingDeclaredPeak => f.write_str(
106                "PeakSource::Declared requested, but neither MaxCLL nor ST 2086 mastering peak is set",
107            ),
108            Self::HdrFeatureRequired => {
109                f.write_str("PQ/HLG conversions require the `hdr-transfers` feature")
110            }
111            Self::FeatureRequired(feat) => {
112                write!(f, "requested conversion requires Cargo feature `{feat}`")
113            }
114            Self::CmsRequired => {
115                f.write_str("ICC or CMYK conversion requires a configured CmsBackend")
116            }
117            Self::DepthReductionForbidden => {
118                f.write_str("bit-depth or precision reduction forbidden by DepthPolicy::Forbid")
119            }
120            Self::AlphaLossForbidden => {
121                f.write_str("dropping non-opaque alpha forbidden by AlphaPolicy")
122            }
123            Self::RangeConversionForbidden => {
124                f.write_str("Full<->Narrow signal range change forbidden by RangePolicy::Forbid")
125            }
126            Self::GamutLossForbidden => {
127                f.write_str("gamut clipping or narrowing forbidden by GamutPolicy::Forbid")
128            }
129            Self::UnsupportedRoute => {
130                f.write_str("unsupported color or layout conversion route")
131            }
132            Self::DimensionMismatch => {
133                f.write_str("source and destination image dimensions or row lengths do not match")
134            }
135            Self::FullImageMapperNotSupported => {
136                f.write_str("full-image buffering ToneMapper is not supported in streaming plans")
137            }
138            Self::ToneMapperFailed => f.write_str("tone mapper failed to prepare"),
139            Self::CmsBackendFailed => f.write_str("CMS backend failed to build or run transform"),
140            Self::OutputSignalingUnavailable => {
141                f.write_str("requested container CICP or ICC signaling is unavailable for destination color space")
142            }
143            Self::OutputSignalingMismatch => {
144                f.write_str("requested container color signaling contradicts the converted destination pixels")
145            }
146            Self::AllocationFailed => f.write_str("allocation failed during pixel conversion"),
147            Self::Cancelled(r) => write!(f, "conversion cancelled: {r:?}"),
148        }
149    }
150}
151
152impl core::error::Error for ConvertError {}
153
154#[cold]
155#[inline(never)]
156#[track_caller]
157pub(crate) fn err_at(e: ConvertError) -> At<ConvertError> {
158    whereat::at!(e)
159}