Skip to main content

zenpixels_convert/
policy.rs

1//! Single cohesive conversion policy (`ConvertPolicy`) governing depth, alpha,
2//! gamut, signal range, HDR white anchor, HLG rendering, tone mapping, CMS, and SIMD.
3
4use alloc::sync::Arc;
5use zenpixels::{Color, DiffuseWhite, HlgRendering, Nits, SampleClaims};
6
7use crate::accelerators::Accelerators;
8use crate::cms::{CmsBackend, CmsChoice, ColorServices};
9use crate::tonemap::ToneMapper;
10
11/// Policy when destination has lower numeric precision than source (e.g. `F32 → U8`, `U16 → U8`).
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum DepthPolicy {
15    /// Refuse any precision reduction (`ConvertError::DepthReductionForbidden`).
16    Forbid,
17    /// Round to nearest integer (`floor(v * max + 0.5)`). Default for display/lossy output.
18    #[default]
19    Round,
20    /// Truncate toward zero (`floor(v * max)` / high-byte drop for `U16 → U8`).
21    Truncate,
22    /// Ordered 4×4 Bayer dithering before quantization (reduces banding in 8-bit gradients).
23    OrderedDither,
24}
25
26/// Policy when destination drops an alpha channel (`RGBA → RGB`, `GrayA → Gray`).
27#[derive(Clone, Copy, Debug, Default, PartialEq)]
28#[non_exhaustive]
29pub enum AlphaPolicy {
30    /// Refuse dropping any alpha channel unless destination also carries alpha (`ConvertError::AlphaLossForbidden`).
31    #[default]
32    Forbid,
33    /// Allow dropping alpha only when proven opaque (`AlphaMode::Opaque` or `SampleClaims::exact.all_opaque`).
34    DiscardIfOpaque,
35    /// Unconditionally drop the alpha channel without compositing.
36    DiscardUnchecked,
37    /// Composite transparent pixels over an explicit linear-light matte [`Color`] before dropping alpha.
38    CompositeOnto(Color),
39}
40
41/// Policy when converting from a wider gamut or HDR range into a narrower or bounded destination.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
43#[non_exhaustive]
44pub enum GamutPolicy {
45    /// Refuse any gamut narrowing or out-of-range clipping (`ConvertError::GamutLossForbidden`).
46    Forbid,
47    /// Preserve extended `< 0.0` and `> 1.0` values on floating-point targets (odd-symmetric transfer curves).
48    PreserveExtended,
49    /// Hard-clamp out-of-gamut channels to `[0.0, 1.0]`.
50    #[default]
51    Clip,
52    /// Smooth OKLch chroma roll-off preserving hue and lightness (requires `oklab` feature).
53    SoftCompress,
54}
55
56/// Policy when source and destination disagree on [`SignalRange`](zenpixels::SignalRange) (`Full ↔ Narrow`).
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
58#[non_exhaustive]
59pub enum RangePolicy {
60    /// Refuse silent Full↔Narrow range conversion (`ConvertError::RangeConversionForbidden`).
61    Forbid,
62    /// Explicitly expand narrow studio swing (`16..=235` / `4096..=60160`) ↔ full swing (`0..=255` / `0..=65535`).
63    #[default]
64    Convert,
65}
66
67/// Luminance weights used when converting `RGB → Gray`.
68#[derive(Clone, Copy, Debug, Default, PartialEq)]
69#[non_exhaustive]
70pub enum LumaCoefficients {
71    /// Derive linear luminance weights from the source RGB primaries (`Bt709`, `DisplayP3`, `Bt2020`, `AdobeRgb`).
72    #[default]
73    FromSourcePrimaries,
74    /// ITU-R BT.709 (`0.2126, 0.7152, 0.0722`).
75    Bt709,
76    /// ITU-R BT.601 (`0.299, 0.587, 0.114`).
77    Bt601,
78    /// ITU-R BT.2020 (`0.2627, 0.6780, 0.0593`).
79    Bt2020,
80    /// Custom linear luminance weights `[Yr, Yg, Yb]`.
81    Custom([f32; 3]),
82}
83
84/// Domain in which `RGB → Gray` luminance weights are evaluated.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
86#[non_exhaustive]
87pub enum LumaDomain {
88    /// Evaluate luma weights directly on transfer-encoded RGB samples (`Y' = w_r·R' + w_g·G' + w_b·B'`).
89    ///
90    /// Matches the JPEG/video Y' convention and `zenpixels 0.2/0.4` defaults, preserves
91    /// neutral gray (`R' = G' = B' → Y' = R'`) bit-for-bit, and enables SIMD integer
92    /// `U8` fast paths.
93    #[default]
94    Encoded,
95    /// Linearize RGB via the source EOTF, compute physical luminance (`Y = w_r·R + w_g·G + w_b·B`),
96    /// then apply the destination OETF.
97    LinearLight,
98}
99
100/// Cohesive conversion policy controlling precision, alpha, gamut, signal range,
101/// HDR anchors, tone mapping, CMS fallback, and SIMD acceleration.
102///
103/// ## Preset Defaults
104///
105/// | Field | `lossless()` / `default()` | `working_linear()` | `permissive()` | `display_sdr(white, peak)` |
106/// |---|---|---|---|---|
107/// | `depth` | `Forbid` | `Round` | `Round` | `Round` |
108/// | `alpha` | `Forbid` | `DiscardIfOpaque` | `DiscardUnchecked` | `CompositeOnto(BLACK)` |
109/// | `gamut` | `PreserveExtended` | `PreserveExtended` | `Clip` | `Clip` |
110/// | `range` | `Forbid` | `Convert` | `Convert` | `Convert` |
111/// | `diffuse_white` | `None` | `Some(BT2408)` | `None` | `Some(white)` |
112/// | `hlg_rendering` | `None` | `None` | `None` | `Some(REFERENCE_1000_NIT)` |
113/// | `tone_map_hdr_to_sdr` | `false` | `false` | `false` | `true` |
114/// | `allow_icc_substitution` | `false` | `true` | `true` | `true` |
115/// | `allow_approximate` | `false` | `false` | `false` | `false` |
116#[derive(Clone, Debug)]
117#[non_exhaustive]
118pub struct ConvertPolicy {
119    /// Depth/quantization behavior.
120    pub depth: DepthPolicy,
121    /// Alpha removal / compositing behavior.
122    pub alpha: AlphaPolicy,
123    /// Gamut narrowing / extended-range behavior.
124    pub gamut: GamutPolicy,
125    /// Explicit Full ↔ Narrow range conversion policy.
126    pub range: RangePolicy,
127    /// RGB → Gray luma weights.
128    pub luma: LumaCoefficients,
129    /// Domain in which `RGB → Gray` weights are evaluated (`Encoded` Y' default vs `LinearLight` Y).
130    pub luma_domain: LumaDomain,
131    /// Relative-linear `1.0` diffuse white anchor (required when crossing PQ ↔ relative light unless carried on `ColorSpace`).
132    pub diffuse_white: Option<DiffuseWhite>,
133    /// Target SDR peak luminance in cd/m² for HDR → SDR tone mapping (default `100.0` cd/m²).
134    pub sdr_peak: Nits,
135    /// Explicit HLG display rendering override when source/dest carries `HlgMode::Scene`.
136    pub hlg_rendering: Option<HlgRendering>,
137    /// Optional custom HDR → SDR tone mapper (defaults to built-in `Bt2446A` when `bt2446a` feature is enabled).
138    pub tone_mapper: Option<Arc<dyn ToneMapper>>,
139    /// Optional CMS backend for arbitrary `ColorSpace::Icc` or `ColorSpace::Cmyk` transforms.
140    pub cms: Option<Arc<dyn CmsBackend>>,
141    /// Optional hermetic accelerator table override (when `None`, consults the process registry / `fast` feature default).
142    pub accelerators: Option<Accelerators>,
143    /// Caller-asserted source sample facts (merged with buffer facts in `ImagePlan`).
144    pub source_claims: SampleClaims,
145    /// Whether to apply tone mapping when converting HDR → SDR (`true` in `display_sdr()`, `false` in `lossless()`/`working_linear()`).
146    pub tone_map_hdr_to_sdr: bool,
147    /// Whether recognized matrix+TRC ICC profiles may substitute directly into native math
148    /// (for non-absolute intents) instead of requiring a CMS backend.
149    ///
150    /// Default is `true` in `permissive()`/`working_linear()`/`display_sdr()`, and `false` in `lossless()`.
151    pub allow_icc_substitution: bool,
152    /// Whether opt-in fast fixed-point approximations (max error <= 1 LSB vs exact float,
153    /// e.g. Q13/Q14 integer LUT U8 sRGB-matrix fast path) may be selected.
154    ///
155    /// Default is `false` (exact 0-bit parity with the float strip pipeline).
156    pub allow_approximate: bool,
157}
158
159impl Default for ConvertPolicy {
160    /// Defaults to [`ConvertPolicy::lossless`] so callers never silently discard alpha,
161    /// narrow bit depth, clip gamut, or rescale signal range without opting in.
162    ///
163    /// Use [`ConvertPolicy::permissive`], [`ConvertPolicy::working_linear`], or
164    /// [`ConvertPolicy::display_sdr`] when lossy conversion is desired.
165    fn default() -> Self {
166        Self::lossless()
167    }
168}
169
170impl ConvertPolicy {
171    /// Strict lossless-permission policy: forbids depth reduction, alpha loss, gamut clipping,
172    /// RGB→Gray chroma loss (unless proven grayscale), and range scaling.
173    ///
174    /// Allows lossless widening (`U8 → U16 → F32`), channel reordering (`RGB ↔ BGR`),
175    /// adding opaque alpha, and floating-point extended-gamut preservation. Note that
176    /// `lossless()` describes **loss-permission settings** rather than mathematical
177    /// invertibility of arbitrary floating-point color transforms.
178    #[must_use]
179    pub fn lossless() -> Self {
180        Self {
181            depth: DepthPolicy::Forbid,
182            alpha: AlphaPolicy::Forbid,
183            gamut: GamutPolicy::PreserveExtended,
184            range: RangePolicy::Forbid,
185            luma: LumaCoefficients::FromSourcePrimaries,
186            luma_domain: LumaDomain::Encoded,
187            diffuse_white: None,
188            sdr_peak: Nits::new_positive_or_panic(100.0),
189            hlg_rendering: None,
190            tone_mapper: None,
191            cms: None,
192            accelerators: None,
193            source_claims: SampleClaims::NONE,
194            tone_map_hdr_to_sdr: false,
195            allow_icc_substitution: false,
196            allow_approximate: false,
197        }
198    }
199
200    /// Linear-light working-space policy: preserves extended values, defaults diffuse white
201    /// to ITU-R BT.2408 (`203 cd/m²`, override via `.with_diffuse_white(...)`), and disables tone mapping.
202    ///
203    /// Use [`ConvertPolicy::permissive`] or [`ConvertPolicy::lossless`] when unanchored
204    /// PQ ↔ relative routes must fail with [`ConvertError::MissingHdrAnchor`](crate::ConvertError::MissingHdrAnchor)
205    /// unless a diffuse white is explicitly provided.
206    #[inline]
207    #[must_use]
208    pub fn working_linear() -> Self {
209        Self {
210            depth: DepthPolicy::Round,
211            alpha: AlphaPolicy::DiscardIfOpaque,
212            gamut: GamutPolicy::PreserveExtended,
213            range: RangePolicy::Convert,
214            luma: LumaCoefficients::FromSourcePrimaries,
215            luma_domain: LumaDomain::Encoded,
216            diffuse_white: Some(DiffuseWhite::BT2408),
217            sdr_peak: Nits::new_positive_or_panic(100.0),
218            hlg_rendering: None,
219            tone_mapper: None,
220            cms: None,
221            accelerators: None,
222            source_claims: SampleClaims::NONE,
223            tone_map_hdr_to_sdr: false,
224            allow_icc_substitution: true,
225            allow_approximate: false,
226        }
227    }
228
229    /// Display-referred SDR output policy: enables HDR → SDR tone mapping, rounds depth, converts narrow range, and clips/compresses gamut.
230    #[must_use]
231    pub fn display_sdr(white: DiffuseWhite, sdr_peak: Nits) -> Self {
232        Self {
233            depth: DepthPolicy::Round,
234            alpha: AlphaPolicy::CompositeOnto(Color::BLACK),
235            gamut: GamutPolicy::Clip,
236            range: RangePolicy::Convert,
237            luma: LumaCoefficients::FromSourcePrimaries,
238            luma_domain: LumaDomain::Encoded,
239            diffuse_white: Some(white),
240            sdr_peak,
241            hlg_rendering: Some(HlgRendering::REFERENCE_1000_NIT),
242            tone_mapper: None,
243            cms: None,
244            accelerators: None,
245            source_claims: SampleClaims::NONE,
246            tone_map_hdr_to_sdr: true,
247            allow_icc_substitution: true,
248            allow_approximate: false,
249        }
250    }
251
252    /// Permissive general-purpose policy (rounds depth, clips gamut, converts narrow range, discards alpha unchecked unless configured).
253    #[must_use]
254    pub fn permissive() -> Self {
255        Self {
256            depth: DepthPolicy::Round,
257            alpha: AlphaPolicy::DiscardUnchecked,
258            gamut: GamutPolicy::Clip,
259            range: RangePolicy::Convert,
260            luma: LumaCoefficients::FromSourcePrimaries,
261            luma_domain: LumaDomain::Encoded,
262            diffuse_white: None,
263            sdr_peak: Nits::new_positive_or_panic(100.0),
264            hlg_rendering: None,
265            tone_mapper: None,
266            cms: None,
267            accelerators: None,
268            source_claims: SampleClaims::NONE,
269            tone_map_hdr_to_sdr: false,
270            allow_icc_substitution: true,
271            allow_approximate: false,
272        }
273    }
274
275    /// Set depth reduction policy (`Forbid`, `Round`, `Truncate`, `OrderedDither`).
276    #[inline]
277    #[must_use]
278    pub fn with_depth(mut self, depth: DepthPolicy) -> Self {
279        self.depth = depth;
280        self
281    }
282
283    /// Set alpha removal/compositing policy.
284    #[inline]
285    #[must_use]
286    pub fn with_alpha(mut self, alpha: AlphaPolicy) -> Self {
287        self.alpha = alpha;
288        self
289    }
290
291    /// Set gamut narrowing / extended-range policy.
292    #[inline]
293    #[must_use]
294    pub fn with_gamut(mut self, gamut: GamutPolicy) -> Self {
295        self.gamut = gamut;
296        self
297    }
298
299    /// Set explicit Full ↔ Narrow signal range conversion policy.
300    #[inline]
301    #[must_use]
302    pub fn with_range(mut self, range: RangePolicy) -> Self {
303        self.range = range;
304        self
305    }
306
307    /// Set RGB → Gray luminance weights.
308    #[inline]
309    #[must_use]
310    pub fn with_luma(mut self, luma: LumaCoefficients) -> Self {
311        self.luma = luma;
312        self
313    }
314
315    /// Set RGB → Gray evaluation domain ([`LumaDomain::Encoded`] Y' default vs [`LumaDomain::LinearLight`] Y).
316    #[inline]
317    #[must_use]
318    pub fn with_luma_domain(mut self, domain: LumaDomain) -> Self {
319        self.luma_domain = domain;
320        self
321    }
322
323    /// Set relative-linear `1.0` diffuse white anchor (e.g. `DiffuseWhite::BT2408` = 203 nits).
324    #[inline]
325    #[must_use]
326    pub fn with_diffuse_white(mut self, white: DiffuseWhite) -> Self {
327        self.diffuse_white = Some(white);
328        self
329    }
330
331    /// Set target SDR peak luminance in cd/m² for HDR → SDR tone mapping.
332    #[inline]
333    #[must_use]
334    pub fn with_sdr_peak(mut self, peak: Nits) -> Self {
335        self.sdr_peak = peak;
336        self
337    }
338
339    /// Set explicit BT.2100-3 HLG display rendering conditions.
340    #[inline]
341    #[must_use]
342    pub fn with_hlg_rendering(mut self, rendering: HlgRendering) -> Self {
343        self.hlg_rendering = Some(rendering);
344        self
345    }
346
347    /// Enable or disable HDR → SDR tone mapping.
348    #[inline]
349    #[must_use]
350    pub fn with_tone_mapping(mut self, enable: bool) -> Self {
351        self.tone_map_hdr_to_sdr = enable;
352        self
353    }
354
355    /// Attach a custom [`ToneMapper`] and enable HDR → SDR tone mapping.
356    #[inline]
357    #[must_use]
358    pub fn with_tone_mapper(mut self, mapper: Arc<dyn ToneMapper>) -> Self {
359        self.tone_mapper = Some(mapper);
360        self.tone_map_hdr_to_sdr = true;
361        self
362    }
363
364    /// Attach a [`CmsBackend`] for arbitrary ICC profiles and CMYK conversions.
365    #[inline]
366    #[must_use]
367    pub fn with_cms(mut self, cms: Arc<dyn CmsBackend>) -> Self {
368        self.cms = Some(cms);
369        self
370    }
371
372    /// Apply a shared [`ColorServices`] bundle to this policy.
373    ///
374    /// - [`CmsChoice::Inherit`]: leaves `cms` and `allow_icc_substitution` unchanged.
375    /// - [`CmsChoice::StrictNoIcc`]: clears `cms` and sets `allow_icc_substitution = false`,
376    ///   permitting validated same-profile ICC carriage and known-space math while refusing
377    ///   both CMS evaluation and inferred matrix+TRC ICC substitution.
378    /// - [`CmsChoice::Use`]: installs the binding's [`CmsBackend`].
379    /// - `services.tone_mapper`: attaches the tone mapper if present without altering
380    ///   `tone_map_hdr_to_sdr`.
381    ///
382    /// Apply `with_color_services` last when composing a policy: subsequent calls to
383    /// [`with_cms`](Self::with_cms) or [`with_icc_substitution`](Self::with_icc_substitution)
384    /// overwrite the fields set here.
385    #[inline]
386    #[must_use]
387    pub fn with_color_services(mut self, services: &ColorServices) -> Self {
388        match &services.cms {
389            CmsChoice::Inherit => {}
390            CmsChoice::StrictNoIcc => {
391                self.cms = None;
392                self.allow_icc_substitution = false;
393            }
394            CmsChoice::Use(binding) => {
395                self.cms = Some(Arc::clone(binding.backend()));
396            }
397        }
398        if let Some(mapper) = &services.tone_mapper {
399            self.tone_mapper = Some(Arc::clone(mapper));
400        }
401        self
402    }
403
404    /// Override the SIMD accelerator table hermetically for plans built with this policy.
405    #[inline]
406    #[must_use]
407    pub fn with_accelerators(mut self, accel: Accelerators) -> Self {
408        self.accelerators = Some(accel);
409        self
410    }
411
412    /// Supply proven source [`SampleClaims`] for row-level plans without buffer headers
413    /// (merged with runtime buffer facts in [`ImagePlan`](crate::ImagePlan)).
414    #[inline]
415    #[must_use]
416    pub fn with_source_claims(mut self, facts: SampleClaims) -> Self {
417        self.source_claims = facts;
418        self
419    }
420
421    /// Control whether recognized matrix+TRC ICC profiles may substitute into native math.
422    #[inline]
423    #[must_use]
424    pub fn with_icc_substitution(mut self, allow: bool) -> Self {
425        self.allow_icc_substitution = allow;
426        self
427    }
428
429    /// Control whether fast fixed-point approximations (max error <= 1 LSB vs exact float)
430    /// may be used on supported U8 color-matrix routes (default `false`).
431    #[inline]
432    #[must_use]
433    pub fn with_approximate(mut self, allow: bool) -> Self {
434        self.allow_approximate = allow;
435        self
436    }
437}