Skip to main content

zenpixels_convert/
plan.rs

1//! Type-safe row-level ([`RowPlan`]) and image-level ([`ImagePlan`]) conversion plans.
2//!
3//! - [`RowPlan::build`] accepts **`hdr_peak: Option<Nits>`** — a compile-time
4//!   known peak luminance. Passing `PeakSource::Measured` to a single-row
5//!   converter is impossible at compile time. Executing a `RowPlan` allocates
6//!   **zero heap scratch** (uses a 1 KiB stack 64-pixel SoA tile).
7//! - [`ImagePlan::build`] accepts **`peak: PeakSource`** (`Measured`, `Declared`,
8//!   or `Fixed(Nits)`), streams HDR peak measurement in O(1) row memory, runs
9//!   uniformly over any [`PixelSource`] → [`PixelSink`] (`PixelView`, `PixelBuf`,
10//!   `BandedBuf`), caches invariant row plans, and propagates proven [`SampleClaims`].
11
12use alloc::sync::Arc;
13use alloc::vec::Vec;
14use how_far::{Complete, PhaseSpec, Pulse, Stages, Total};
15use whereat::At;
16use zenpixels::{
17    AlphaMode, ColorSpace, DiffuseWhite, ExactDepth, FloatClaims, HdrMetadata, HlgMode,
18    HlgRendering, Nits, PeakSource, PixelBuf, PixelFormat, PixelSink, PixelSource, Primaries,
19    SampleClaims, SampleType, SignalRange, Transfer, full_range_grid_nests,
20    narrow_range_grid_nests,
21};
22
23use crate::accelerators::{self, Accelerators};
24use crate::cms::CmsTransform;
25use crate::error::{ConvertError, err_at};
26use crate::policy::{
27    AlphaPolicy, ConvertPolicy, DepthPolicy, GamutPolicy, LumaDomain, RangePolicy,
28};
29use crate::pulse::{check_pulse, is_stop_at, live_pulse, step_pulse};
30use crate::strip::{self, ByteFastPath, FastRow, MicroOp};
31use crate::tonemap::{PreparedMapper, StripMapper, ToneMapContext};
32
33#[cfg(feature = "hdr-transfers")]
34use crate::hlg_render::PreparedHlg;
35#[cfg(not(feature = "hdr-transfers"))]
36type PreparedHlg = ();
37#[cfg(feature = "oklab")]
38use crate::tonemap::SoftCompress;
39
40/// Execution strategy compiled inside a [`RowPlan`].
41#[derive(Clone)]
42enum RowExec {
43    /// Zero-float byte/integer/wide-layout fast path.
44    Byte(ByteFastPath),
45    /// Direct contiguous single-stage row fast path (zero AoS↔SoA bounce).
46    FastRow(FastRow),
47    /// Composable micro-op pipeline running on 64-pixel stack SoA strips.
48    Strip {
49        ops: Vec<MicroOp>,
50        src_opaque_alpha: bool,
51    },
52    /// External CMS row transform (`ColorSpace::Icc` / `ColorSpace::Cmyk`).
53    Cms {
54        transform: Arc<dyn CmsTransform>,
55        clip_f32_color: bool,
56    },
57}
58
59/// Shared preflight result used by both [`RowPlan::build`] and [`Negotiate`](crate::Negotiate).
60pub(crate) struct PreflightOutcome {
61    pub matte_color: Option<zenpixels::Color>,
62    pub range_change: bool,
63    pub uses_cms: bool,
64    pub is_identity: bool,
65    pub drops_alpha: bool,
66    pub alpha_proven_opaque: bool,
67    pub drops_chroma: bool,
68    pub chroma_proven_gray: bool,
69    pub gamut_narrows: bool,
70    pub is_hdr_to_sdr: bool,
71    pub depth_reduces: bool,
72}
73
74/// Compiled, reusable, thread-safe single-row pixel converter.
75///
76/// Built via [`RowPlan::build`] with an explicit optional `hdr_peak: Option<Nits>`.
77/// Calling [`convert_row`](Self::convert_row) on native routes allocates **zero
78/// heap memory** and uses a 1 KiB stack-allocated 64-pixel SoA tile.
79#[derive(Clone)]
80pub struct RowPlan {
81    src: PixelFormat,
82    dst: PixelFormat,
83    exec: RowExec,
84    depth_policy: DepthPolicy,
85    accel: Accelerators,
86    output_claims: SampleClaims,
87}
88
89impl core::fmt::Debug for RowPlan {
90    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
91        f.debug_struct("RowPlan")
92            .field("src", &self.src)
93            .field("dst", &self.dst)
94            .field("depth_policy", &self.depth_policy)
95            .field("accel", &self.accel)
96            .finish()
97    }
98}
99
100impl RowPlan {
101    /// Compile a single-row conversion plan from `src` to `dst` under `policy`.
102    ///
103    /// Accepts either borrowed `&PixelFormat` or owned `PixelFormat` at the call site (retaining
104    /// internal clones inside the compiled plan).
105    ///
106    /// For HDR → SDR tone mapping with a pipeline-managed mapper, pass
107    /// `resolved_source_peak: Some(nits)` (`None` means no peak supplied — never "measure this
108    /// row"). To measure peak automatically over a whole image, use [`ImagePlan::build`] with
109    /// [`PeakSource::Measured`].
110    #[inline]
111    pub fn build(
112        src: impl AsRef<PixelFormat>,
113        dst: impl AsRef<PixelFormat>,
114        policy: &ConvertPolicy,
115        resolved_source_peak: Option<Nits>,
116    ) -> Result<Self, At<ConvertError>> {
117        Self::build_inner(
118            src.as_ref(),
119            dst.as_ref(),
120            policy,
121            resolved_source_peak,
122            None,
123        )
124    }
125
126    /// Build a compiled [`RowPlan`] with optional cooperative cancellation and progress via
127    /// `pulse` (forwarded to [`CmsBackend::build_transform`](crate::CmsBackend::build_transform)
128    /// and [`ToneMapper::prepare`](crate::ToneMapper::prepare); pass `None` when not needed).
129    #[inline]
130    pub fn build_with_pulse(
131        src: impl AsRef<PixelFormat>,
132        dst: impl AsRef<PixelFormat>,
133        policy: &ConvertPolicy,
134        resolved_source_peak: Option<Nits>,
135        pulse: Option<&dyn Pulse>,
136    ) -> Result<Self, At<ConvertError>> {
137        Self::build_inner(
138            src.as_ref(),
139            dst.as_ref(),
140            policy,
141            resolved_source_peak,
142            pulse,
143        )
144    }
145
146    #[inline(never)]
147    fn build_inner(
148        src: &PixelFormat,
149        dst: &PixelFormat,
150        policy: &ConvertPolicy,
151        hdr_peak: Option<Nits>,
152        pulse: Option<&dyn Pulse>,
153    ) -> Result<Self, At<ConvertError>> {
154        let pre = preflight_and_classify(src, dst, policy)?;
155        let accel = accelerators::resolve(policy.accelerators);
156
157        // 1. Byte-exact identity (supports all 11 sample types).
158        if pre.is_identity {
159            return Ok(Self {
160                output_claims: policy.source_claims,
161                src: src.clone(),
162                dst: dst.clone(),
163                exec: RowExec::Byte(ByteFastPath::Memcpy),
164                depth_policy: policy.depth,
165                accel,
166            });
167        }
168
169        let matte_color = pre.matte_color;
170        let range_change = pre.range_change;
171
172        // 2. Fast byte-only path (also handles same-profile opaque ICC / CMYK layout, widening,
173        //    opaque alpha fill, same-depth integer repacking, and BT.2100 narrow bit shifts
174        //    without requiring a CMS backend!).
175        //    Pass `policy.source_claims.all_opaque` (proven stored max alpha, NOT merely logical
176        //    `AlphaMode::Opaque`) so unverified `Opaque` junk alpha bytes are canonicalized!
177        if let Some(bp) = strip::detect_byte_fast_path(
178            src,
179            dst,
180            policy.depth,
181            policy.luma,
182            policy.luma_domain,
183            matte_color.is_some(),
184            policy.source_claims.all_opaque,
185        ) {
186            let output_claims = derive_output_facts_byte(src, dst, policy.source_claims, bp);
187            return Ok(Self {
188                src: src.clone(),
189                dst: dst.clone(),
190                exec: RowExec::Byte(bp),
191                depth_policy: policy.depth,
192                accel,
193                output_claims,
194            });
195        }
196
197        // 3. ICC / CMYK routing (policy checks have ALREADY passed in `preflight_and_classify`!).
198        if pre.uses_cms {
199            if let (Some(sub_src), Some(sub_dst)) = (
200                try_substitute_icc(src, policy),
201                try_substitute_icc(dst, policy),
202            ) {
203                let mut inner = Self::build_inner(&sub_src, &sub_dst, policy, hdr_peak, pulse)?;
204                inner.src = src.clone();
205                inner.dst = dst.clone();
206                return Ok(inner);
207            }
208            return Self::build_cms(
209                src.clone(),
210                dst.clone(),
211                policy,
212                pre.matte_color.is_some(),
213                accel,
214                pulse,
215            );
216        }
217
218        // 4. Resolve photometry, transfers, HDR white anchors, and HLG BEFORE FastRow or Strip!
219        let src_tf = color_transfer(src.color());
220        let dst_tf = color_transfer(dst.color());
221        let src_range = color_range(src.color());
222        let dst_range = color_range(dst.color());
223        let src_bits = effective_color_bits(src);
224        let dst_bits = effective_color_bits(dst);
225
226        let src_is_pq = matches!(src_tf, Transfer::Pq);
227        let dst_is_pq = matches!(dst_tf, Transfer::Pq);
228
229        let relative_white_scale = if !src_is_pq && !dst_is_pq {
230            match (src.color().diffuse_white(), dst.color().diffuse_white()) {
231                (Some(sw), Some(dw)) if ((sw.nits() / dw.nits()) - 1.0).abs() > 1e-6 => {
232                    sw.nits() / dw.nits()
233                }
234                _ => 1.0,
235            }
236        } else {
237            1.0
238        };
239        let has_relative_white_rescale = (relative_white_scale - 1.0).abs() > 1e-6;
240
241        let need_linear_space = needs_linear_domain(
242            src.color(),
243            dst.color(),
244            matte_color.is_some(),
245            has_relative_white_rescale,
246            policy,
247        );
248
249        // Reject `Transfer::Unknown` whenever transfer changes or linear-domain math is required.
250        if (src_tf == Transfer::Unknown || dst_tf == Transfer::Unknown)
251            && (!src_tf.same_curve(dst_tf) || need_linear_space)
252        {
253            return Err(err_at(ConvertError::UnsupportedRoute));
254        }
255
256        let crosses_hdr_feature = src_tf.is_hdr() || dst_tf.is_hdr();
257        if crosses_hdr_feature && !cfg!(feature = "hdr-transfers") {
258            return Err(err_at(ConvertError::HdrFeatureRequired));
259        }
260
261        let white = if src_is_pq && !dst_is_pq {
262            dst.color()
263                .diffuse_white()
264                .or(policy.diffuse_white)
265                .ok_or_else(|| err_at(ConvertError::MissingHdrAnchor))?
266        } else if !src_is_pq && dst_is_pq {
267            src.color()
268                .diffuse_white()
269                .or(policy.diffuse_white)
270                .ok_or_else(|| err_at(ConvertError::MissingHdrAnchor))?
271        } else {
272            src.color()
273                .diffuse_white()
274                .or_else(|| dst.color().diffuse_white())
275                .or(policy.diffuse_white)
276                .unwrap_or(DiffuseWhite::BT2408)
277        };
278        let white_nits = white.nits();
279
280        // Separate source and destination white anchors for HLG display OOTF so a
281        // relative white rescale (`Linear(100) -> HLG(200)`) never double-scales (B16).
282        let src_hlg_white_nits = if src_is_pq || dst_is_pq {
283            white_nits
284        } else {
285            src.color()
286                .diffuse_white()
287                .or_else(|| dst.color().diffuse_white())
288                .or(policy.diffuse_white)
289                .unwrap_or(DiffuseWhite::BT2408)
290                .nits()
291        };
292        let dst_hlg_white_nits = if src_is_pq || dst_is_pq {
293            white_nits
294        } else {
295            dst.color()
296                .diffuse_white()
297                .or_else(|| src.color().diffuse_white())
298                .or(policy.diffuse_white)
299                .unwrap_or(DiffuseWhite::BT2408)
300                .nits()
301        };
302
303        let preserve_extended =
304            policy.gamut == GamutPolicy::PreserveExtended && dst.layout().sample().is_float();
305
306        // Resolve HLG display rendering BEFORE FastRow detection so identical semantics apply
307        // regardless of channel order / layout!
308        #[allow(unused_variables)]
309        let (src_hlg_tf, src_prepared_hlg) = resolve_hlg(
310            src.color(),
311            src_tf,
312            dst_tf,
313            policy.hlg_rendering,
314            false,
315            src_hlg_white_nits,
316            !preserve_extended,
317        )?;
318        #[allow(unused_variables)]
319        let (dst_hlg_tf, dst_prepared_hlg) = resolve_hlg(
320            dst.color(),
321            dst_tf,
322            src_tf,
323            policy.hlg_rendering,
324            true,
325            dst_hlg_white_nits,
326            !preserve_extended,
327        )?;
328
329        // 5. Direct contiguous single-stage row fast path (zero AoS↔SoA bounce)
330        // ONLY after policy, Transfer::Unknown, relative-white, and HLG are resolved!
331        let is_linear_hdr = is_scene_linear_hdr_candidate(src, dst)
332            && hdr_peak.is_some_and(|p| p.nits() > white_nits * (1.0 + 1e-4));
333        let is_hdr_to_sdr = pre.is_hdr_to_sdr || is_linear_hdr;
334        if !(is_hdr_to_sdr && policy.tone_map_hdr_to_sdr)
335            && !has_relative_white_rescale
336            && src_prepared_hlg.is_none()
337            && dst_prepared_hlg.is_none()
338            && policy.gamut != GamutPolicy::SoftCompress
339            && let Some(fr) = strip::detect_fast_row(
340                src,
341                dst,
342                policy.depth,
343                policy.gamut,
344                policy.allow_approximate,
345                matte_color.is_some(),
346                preserve_extended,
347                white_nits,
348            )
349        {
350            let clamped_color = !preserve_extended
351                && !dst_tf.is_hdr()
352                && !matches!(
353                    fr,
354                    FastRow::TransferF32 {
355                        transfer: Transfer::Pq,
356                        is_eotf: true,
357                        ..
358                    }
359                )
360                && matches!(
361                    fr,
362                    FastRow::SrgbU8ToLinF32 { .. }
363                        | FastRow::U8ToF32 { .. }
364                        | FastRow::U16ToF32 { .. }
365                        | FastRow::TransferF32 { .. }
366                );
367            let alpha_filled_opaque = matches!(
368                fr,
369                FastRow::Srgb8MatrixExact {
370                    fill_opaque: true,
371                    ..
372                } | FastRow::Srgb8MatrixApproxQ14 {
373                    fill_opaque: true,
374                    ..
375                }
376            );
377            let safe_no_subnormals = matches!(
378                fr,
379                FastRow::SrgbU8ToLinF32 { .. } | FastRow::U8ToF32 { .. } | FastRow::U16ToF32 { .. }
380            );
381            let output_claims = derive_output_facts_math(
382                src,
383                dst,
384                policy.source_claims,
385                clamped_color,
386                alpha_filled_opaque,
387                false,
388                matches!(fr, FastRow::F32ToF16 { .. } | FastRow::F16ToF32 { .. }),
389                safe_no_subnormals,
390            );
391            return Ok(Self {
392                src: src.clone(),
393                dst: dst.clone(),
394                exec: RowExec::FastRow(fr),
395                depth_policy: policy.depth,
396                accel,
397                output_claims,
398            });
399        }
400
401        // 6. Compile composable micro-op sequence on 64-px stack SoA StripBuf.
402        let mut ops: Vec<MicroOp> = Vec::with_capacity(14);
403        let narrow_depth_change = src_range == SignalRange::Narrow
404            && dst_range == SignalRange::Narrow
405            && src_bits != dst_bits;
406
407        // 6a. Source narrow range expansion (before unpremul/EOTF!).
408        if src_range == SignalRange::Narrow
409            && (range_change || need_linear_space || !src_tf.is_linear() || narrow_depth_change)
410        {
411            ops.push(MicroOp::ExpandNarrow { bits: src_bits });
412        }
413
414        // 6b. Unpremultiply source if premultiplied (when transfer/gamut/matte/alpha changes).
415        let src_premul = src.color().alpha() == AlphaMode::Premultiplied;
416        let dst_premul = dst.color().alpha() == AlphaMode::Premultiplied;
417        if src_premul && (need_linear_space || !dst_premul) {
418            ops.push(MicroOp::Unpremul);
419        }
420
421        // 6c. Source EOTF (into linear light) or Oklab/Perceptual/XYZ decode into linear RGB.
422        let mut cur_primaries = color_primaries(src.color());
423        let dst_primaries = color_primaries(dst.color());
424        let mut cur_is_gray = matches!(src.color(), ColorSpace::Gray { .. });
425        let mut already_in_dst_xyz = false;
426
427        match &src.color() {
428            ColorSpace::Xyz { white_point, .. } => {
429                if let ColorSpace::Xyz {
430                    white_point: dst_wp,
431                    ..
432                } = &dst.color()
433                    && *white_point == *dst_wp
434                    && matte_color.is_none()
435                    && policy.gamut != GamutPolicy::SoftCompress
436                {
437                    already_in_dst_xyz = true;
438                } else {
439                    let target_p = if !dst_primaries.is_unknown() {
440                        dst_primaries
441                    } else {
442                        RgbPrimaries::BT709
443                    };
444                    let m = target_p
445                        .xyz_to_rgb_f32(*white_point)
446                        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
447                    ops.push(MicroOp::Gamut3x3(m));
448                    cur_primaries = target_p;
449                }
450            }
451            ColorSpace::Oklab { .. } => {
452                #[cfg(not(feature = "oklab"))]
453                return Err(err_at(ConvertError::FeatureRequired("oklab")));
454                #[cfg(feature = "oklab")]
455                {
456                    let target_p = if !dst_primaries.is_unknown() {
457                        dst_primaries
458                    } else {
459                        RgbPrimaries::BT709
460                    };
461                    let space = target_p
462                        .oklab_space()
463                        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
464                    ops.push(MicroOp::OklabToRgb(*space.lms_to_rgb().rows()));
465                    cur_primaries = target_p;
466                }
467            }
468            ColorSpace::Perceptual { space, .. } => {
469                #[cfg(not(feature = "perceptual"))]
470                {
471                    let _ = space;
472                    return Err(err_at(ConvertError::FeatureRequired("perceptual")));
473                }
474                #[cfg(feature = "perceptual")]
475                {
476                    let target_std = dst_primaries
477                        .as_standard()
478                        .filter(|p| *p != Primaries::Unknown)
479                        .unwrap_or(Primaries::Bt709);
480                    ops.push(MicroOp::PerceptualToRgb {
481                        space: *space,
482                        primaries: target_std,
483                        diffuse_white: white,
484                    });
485                    cur_primaries = RgbPrimaries::Standard(target_std);
486                }
487            }
488            ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. } => {
489                if need_linear_space && !src_hlg_tf.is_linear() {
490                    let pq_scale = if src_is_pq {
491                        10_000.0 / white_nits
492                    } else {
493                        1.0
494                    };
495                    ops.push(MicroOp::Eotf {
496                        transfer: src_hlg_tf,
497                        pq_scale,
498                        #[cfg(feature = "hdr-transfers")]
499                        hlg: src_prepared_hlg,
500                        preserve_extended,
501                    });
502                }
503            }
504            _ => return Err(err_at(ConvertError::UnsupportedRoute)),
505        }
506
507        // If source was Gray and destination is RGB/Oklab/Perceptual, broadcast Y -> R,G,B.
508        if cur_is_gray && !matches!(dst.color(), ColorSpace::Gray { .. }) {
509            ops.push(MicroOp::GrayToRgb);
510            cur_is_gray = false;
511            cur_primaries = if !dst_primaries.is_unknown() {
512                dst_primaries
513            } else {
514                RgbPrimaries::BT709
515            };
516        }
517
518        // 6d. Relative-to-relative diffuse white rescale (in linear light).
519        if has_relative_white_rescale {
520            ops.push(MicroOp::ScaleLinear(relative_white_scale));
521        }
522
523        // 6e. Linear-light alpha matte compositing BEFORE tone mapping & gamut clipping!
524        // Both pixel RGB and matte color are in diffuse-white-relative linear light here.
525        if let Some(matte) = matte_color {
526            let matte_primaries = if cur_primaries.is_unknown() {
527                RgbPrimaries::BT709
528            } else {
529                cur_primaries
530            };
531            let matte_rgb = match matte_primaries {
532                RgbPrimaries::Standard(p) => matte.to_primaries(p),
533                RgbPrimaries::Custom(cp) => matte.to_custom_primaries(cp),
534            }
535            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
536            ops.push(MicroOp::CompositeMatte(matte_rgb));
537        }
538
539        // 6f. HDR -> SDR Tone Mapping (in linear light, in mapper's working primaries!).
540        if is_hdr_to_sdr && policy.tone_map_hdr_to_sdr {
541            let mapper_arc = resolve_tone_mapper(policy)?;
542            let work_std = mapper_arc
543                .working_primaries_for(dst_primaries.as_standard().unwrap_or(Primaries::Bt2020));
544            let work_primaries = RgbPrimaries::Standard(work_std);
545            if !cur_primaries.same_chromaticity(work_primaries) {
546                let m = cur_primaries
547                    .gamut_matrix_to(work_primaries)
548                    .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
549                ops.push(MicroOp::Gamut3x3(m));
550                cur_primaries = work_primaries;
551            }
552            let req = mapper_arc.requirements();
553            if req.full_image {
554                return Err(err_at(ConvertError::FullImageMapperNotSupported));
555            }
556            let (src_peak_nits, target_peak_nits) = if let Some((bs, bd)) = mapper_arc.baked_peaks()
557            {
558                (bs, bd)
559            } else {
560                let s_peak = if let Some(p) = hdr_peak {
561                    p.nits()
562                } else if !req.source_peak_nits {
563                    1000.0
564                } else if let Transfer::Hlg(HlgMode::Display(r)) = src_hlg_tf {
565                    r.peak().nits()
566                } else {
567                    return Err(err_at(ConvertError::MissingDeclaredPeak));
568                };
569                (s_peak, policy.sdr_peak.nits())
570            };
571            let ctx = ToneMapContext {
572                source_peak_nits: src_peak_nits,
573                target_peak_nits,
574                working_primaries: work_std,
575            };
576            let PreparedMapper::Streaming(strip_mapper) = mapper_arc.prepare(&ctx, pulse)?;
577            let mapper_shared: Arc<dyn StripMapper> = Arc::from(strip_mapper);
578            // Input strip is relative-linear (`1.0 = white_nits`); ToneMapper expects `1.0 = src_peak_nits`.
579            // Output of ToneMapper is `1.0 = target_peak_nits`. If destination declares a different
580            // SDR diffuse white than `target_peak_nits`, rescale cleanly.
581            let out_scale = match dst.color().diffuse_white() {
582                Some(dw) if ((target_peak_nits / dw.nits()) - 1.0).abs() > 1e-6 => {
583                    target_peak_nits / dw.nits()
584                }
585                _ => 1.0,
586            };
587            // Input strip is relative-linear (`1.0 = dst_hlg_white_nits`, after any relative white rescale).
588            let strip_white_nits = if has_relative_white_rescale {
589                dst_hlg_white_nits
590            } else {
591                white_nits
592            };
593            ops.push(MicroOp::ToneMap {
594                in_scale: strip_white_nits / src_peak_nits.max(1e-3),
595                out_scale,
596                mapper: mapper_shared,
597            });
598        }
599
600        // 6g. Linear-light 3×3 Gamut Matrix (ALWAYS BEFORE encoding or clamping!).
601        if !cur_is_gray && dst.color().is_rgb() && !cur_primaries.same_chromaticity(dst_primaries) {
602            let m = cur_primaries
603                .gamut_matrix_to(dst_primaries)
604                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
605            ops.push(MicroOp::Gamut3x3(m));
606            cur_primaries = dst_primaries;
607        }
608
609        // 6h. Gamut mapping (`SoftCompress` or `ClampUnit` in linear light before OETF!).
610        let mut clamped_color = false;
611        if !cur_is_gray && dst.color().is_rgb() {
612            match policy.gamut {
613                GamutPolicy::SoftCompress => {
614                    #[cfg(not(feature = "oklab"))]
615                    return Err(err_at(ConvertError::FeatureRequired("oklab")));
616                    #[cfg(feature = "oklab")]
617                    {
618                        let space = cur_primaries
619                            .oklab_space()
620                            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
621                        ops.push(MicroOp::SoftCompress(SoftCompress::new(
622                            &space,
623                            SoftCompress::DEFAULT_KNEE,
624                        )));
625                        if !preserve_extended {
626                            ops.push(MicroOp::ClampUnit);
627                            clamped_color = true;
628                        }
629                    }
630                }
631                GamutPolicy::Clip => {
632                    if !dst_tf.is_hdr()
633                        && !matches!(dst_tf, Transfer::DciCinema)
634                        && (pre.gamut_narrows || is_hdr_to_sdr || !dst.layout().sample().is_float())
635                    {
636                        ops.push(MicroOp::ClampUnit);
637                        clamped_color = true;
638                    }
639                }
640                GamutPolicy::PreserveExtended | GamutPolicy::Forbid => {}
641            }
642        }
643
644        // 6i. RGB -> Gray in linear light (or directly on encoded RGB when `!need_linear_space`).
645        // When `LumaDomain::Encoded` AND `need_linear_space` (e.g. Display P3 / Linear / matte -> sRGB Gray),
646        // defer `RgbToGray` until AFTER step 6j's destination OETF so luma weights evaluate in
647        // destination encoded space rather than linear light!
648        let defer_encoded_luma = !cur_is_gray
649            && matches!(dst.color(), ColorSpace::Gray { .. })
650            && need_linear_space
651            && policy.luma_domain == LumaDomain::Encoded;
652        let deferred_luma_weights =
653            if !cur_is_gray && matches!(dst.color(), ColorSpace::Gray { .. }) {
654                let weights = strip::resolve_luma_weights(policy.luma, cur_primaries)
655                    .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
656                if defer_encoded_luma {
657                    Some(weights)
658                } else {
659                    ops.push(MicroOp::RgbToGray(weights));
660                    None
661                }
662            } else {
663                None
664            };
665
666        // 6j. Encode to destination color model (`Xyz`, `Oklab`, `Perceptual`, or `Oetf`).
667        match &dst.color() {
668            ColorSpace::Xyz { white_point, .. } => {
669                if !already_in_dst_xyz {
670                    let m = cur_primaries
671                        .rgb_to_xyz_f32(*white_point)
672                        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
673                    ops.push(MicroOp::Gamut3x3(m));
674                }
675                clamped_color = false;
676            }
677            ColorSpace::Oklab { .. } => {
678                #[cfg(not(feature = "oklab"))]
679                return Err(err_at(ConvertError::FeatureRequired("oklab")));
680                #[cfg(feature = "oklab")]
681                {
682                    let space = cur_primaries
683                        .oklab_space()
684                        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
685                    ops.push(MicroOp::RgbToOklab(*space.rgb_to_lms().rows()));
686                    clamped_color = false;
687                }
688            }
689            ColorSpace::Perceptual { space, .. } => {
690                #[cfg(not(feature = "perceptual"))]
691                {
692                    let _ = space;
693                    return Err(err_at(ConvertError::FeatureRequired("perceptual")));
694                }
695                #[cfg(feature = "perceptual")]
696                {
697                    let perceptual_std = match cur_primaries {
698                        RgbPrimaries::Standard(p) => p,
699                        RgbPrimaries::Custom(_) => {
700                            let m = cur_primaries
701                                .gamut_matrix_to(RgbPrimaries::BT709)
702                                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
703                            ops.push(MicroOp::Gamut3x3(m));
704                            Primaries::Bt709
705                        }
706                    };
707                    ops.push(MicroOp::RgbToPerceptual {
708                        space: *space,
709                        primaries: perceptual_std,
710                        diffuse_white: white,
711                    });
712                    clamped_color = false;
713                }
714            }
715            ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. } => {
716                if need_linear_space && !dst_hlg_tf.is_linear() {
717                    let pq_inv_scale = if dst_is_pq {
718                        white_nits / 10_000.0
719                    } else {
720                        1.0
721                    };
722                    ops.push(MicroOp::Oetf {
723                        transfer: dst_hlg_tf,
724                        pq_inv_scale,
725                        #[cfg(feature = "hdr-transfers")]
726                        hlg: dst_prepared_hlg,
727                        preserve_extended,
728                        gray_only: matches!(dst.color(), ColorSpace::Gray { .. })
729                            && !defer_encoded_luma,
730                    });
731                    if !preserve_extended && !dst_hlg_tf.is_hdr() {
732                        clamped_color = true;
733                    }
734                }
735            }
736            _ => return Err(err_at(ConvertError::UnsupportedRoute)),
737        }
738
739        if let Some(weights) = deferred_luma_weights {
740            ops.push(MicroOp::RgbToGray(weights));
741        }
742
743        // 6k. Destination alpha normalization / premultiplication.
744        let mut alpha_filled_opaque = matte_color.is_some()
745            || !src.layout().order().has_alpha_slot()
746            || src.color().alpha() == AlphaMode::Opaque;
747        if matches!(dst.color().alpha(), AlphaMode::Opaque) {
748            ops.push(MicroOp::FillOpaqueAlpha);
749            alpha_filled_opaque = true;
750        }
751        if dst_premul && (need_linear_space || !src_premul) {
752            ops.push(MicroOp::Premul);
753        }
754
755        // 6l. Destination narrow range compression.
756        if dst_range == SignalRange::Narrow
757            && (range_change || need_linear_space || !dst_hlg_tf.is_linear() || narrow_depth_change)
758        {
759            ops.push(MicroOp::CompressNarrow { bits: dst_bits });
760        }
761
762        let src_opaque_alpha = src.color().alpha() == AlphaMode::Opaque;
763        let safe_no_subnormals = !has_relative_white_rescale
764            && !src.layout().sample().is_float()
765            && dst.layout().sample() == SampleType::F32
766            && matches!(src.layout().sample(), SampleType::U8 | SampleType::U16)
767            && !pre.gamut_narrows
768            && !is_hdr_to_sdr
769            && matte_color.is_none()
770            && matches!(
771                (src_tf, dst_tf),
772                (Transfer::Srgb, Transfer::Linear)
773                    | (Transfer::Linear, Transfer::Srgb)
774                    | (Transfer::Linear, Transfer::Linear)
775                    | (Transfer::Srgb, Transfer::Srgb)
776            );
777        let output_claims = derive_output_facts_math(
778            src,
779            dst,
780            policy.source_claims,
781            clamped_color,
782            alpha_filled_opaque,
783            matte_color.is_some(),
784            false,
785            safe_no_subnormals,
786        );
787
788        Ok(Self {
789            src: src.clone(),
790            dst: dst.clone(),
791            exec: RowExec::Strip {
792                ops,
793                src_opaque_alpha,
794            },
795            depth_policy: policy.depth,
796            accel,
797            output_claims,
798        })
799    }
800
801    fn build_cms(
802        src: PixelFormat,
803        dst: PixelFormat,
804        policy: &ConvertPolicy,
805        matte_active: bool,
806        accel: Accelerators,
807        pulse: Option<&dyn Pulse>,
808    ) -> Result<Self, At<ConvertError>> {
809        // CMS backends do not composite linear mattes, convert premultiplied alpha,
810        // apply Bayer ordered dithering, or run OKLch soft gamut compression.
811        if matte_active
812            || src.color().alpha() == AlphaMode::Premultiplied
813            || dst.color().alpha() == AlphaMode::Premultiplied
814            || policy.depth == DepthPolicy::OrderedDither
815            || policy.gamut == GamutPolicy::SoftCompress
816        {
817            return Err(err_at(ConvertError::UnsupportedRoute));
818        }
819        let cms = policy
820            .cms
821            .as_ref()
822            .ok_or_else(|| err_at(ConvertError::CmsRequired))?;
823        let transform = cms.build_transform(&src, &dst, pulse)?;
824        let depth = if dst.layout().sample() == SampleType::U8 && dst.layout().packing().is_full() {
825            ExactDepth::new(SampleType::U8, color_range(dst.color()), 8, 8).ok()
826        } else {
827            None
828        };
829        let all_opaque = matches!(
830            dst.color().alpha(),
831            AlphaMode::None | AlphaMode::Opaque | AlphaMode::Undefined
832        );
833        let output_claims = SampleClaims::NONE
834            .with_depth(depth)
835            .with_all_opaque(all_opaque)
836            .with_all_grayscale(matches!(dst.color(), ColorSpace::Gray { .. }))
837            .with_binary_alpha(all_opaque);
838        let clip_f32_color = policy.gamut == GamutPolicy::Clip
839            && dst.layout().sample() == SampleType::F32
840            && match &dst.color() {
841                ColorSpace::Rgb { transfer, .. }
842                | ColorSpace::RgbCustom { transfer, .. }
843                | ColorSpace::Gray { transfer, .. } => !transfer.is_hdr(),
844                ColorSpace::Icc { .. } => true,
845                _ => false,
846            };
847        Ok(Self {
848            output_claims,
849            src,
850            dst,
851            exec: RowExec::Cms {
852                transform,
853                clip_f32_color,
854            },
855            depth_policy: policy.depth,
856            accel,
857        })
858    }
859
860    /// Source image specification.
861    #[inline]
862    #[must_use]
863    pub fn source_format(&self) -> &PixelFormat {
864        &self.src
865    }
866
867    /// Destination image specification.
868    #[inline]
869    #[must_use]
870    pub fn destination_format(&self) -> &PixelFormat {
871        &self.dst
872    }
873
874    /// Proven [`SampleClaims`] guaranteed on pixels emitted by this plan.
875    #[inline]
876    #[must_use]
877    pub const fn output_claims(&self) -> SampleClaims {
878        self.output_claims
879    }
880
881    /// Whether this plan executes as a direct byte-copy (`Memcpy`) route with no per-sample work.
882    ///
883    /// Includes identical `src == dst` (unless unverified `AlphaMode::Opaque` requires alpha
884    /// canonicalization) as well as same-layout proven-opaque `Straight <-> Premultiplied` or
885    /// same-layout metadata relabels that need no pixel transformation.
886    #[inline]
887    #[must_use]
888    pub fn is_identity(&self) -> bool {
889        matches!(self.exec, RowExec::Byte(ByteFastPath::Memcpy))
890    }
891
892    /// Convert a single row of `width_pixels` pixels from `src_row` into `dst_row` with
893    /// **zero heap allocation**.
894    ///
895    /// Uses row index `0` for ordered dithering. When converting a multi-row image with
896    /// [`DepthPolicy::OrderedDither`], use [`convert_row_at`](Self::convert_row_at) to pass
897    /// the vertical row coordinate so the 2D Bayer 4×4 matrix varies across rows.
898    #[inline]
899    pub fn convert_row(
900        &self,
901        src_row: &[u8],
902        dst_row: &mut [u8],
903        width_pixels: u32,
904    ) -> Result<(), At<ConvertError>> {
905        self.convert_row_at(0, src_row, dst_row, width_pixels)
906    }
907
908    /// Convert a single row of `width_pixels` pixels at vertical coordinate `row_index` from
909    /// `src_row` into `dst_row` with **zero heap allocation**.
910    ///
911    /// `row_index` selects the vertical phase of the 2D Bayer 4×4 matrix under
912    /// [`DepthPolicy::OrderedDither`] so strips and bands produce identical dither patterns
913    /// to whole-image conversion.
914    pub fn convert_row_at(
915        &self,
916        row_index: u32,
917        src_row: &[u8],
918        dst_row: &mut [u8],
919        width_pixels: u32,
920    ) -> Result<(), At<ConvertError>> {
921        let w = width_pixels as usize;
922        let need_src = w
923            .checked_mul(self.src.layout().bytes_per_pixel())
924            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
925        let need_dst = w
926            .checked_mul(self.dst.layout().bytes_per_pixel())
927            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
928        if src_row.len() < need_src || dst_row.len() < need_dst {
929            return Err(err_at(ConvertError::DimensionMismatch));
930        }
931        if w == 0 {
932            return Ok(());
933        }
934        match &self.exec {
935            RowExec::Byte(bp) => {
936                bp.exec(
937                    &src_row[..need_src],
938                    &mut dst_row[..need_dst],
939                    w,
940                    &self.accel,
941                );
942                Ok(())
943            }
944            RowExec::FastRow(fr) => {
945                strip::exec_fast_row(
946                    fr,
947                    &src_row[..need_src],
948                    &mut dst_row[..need_dst],
949                    w,
950                    &self.accel,
951                );
952                Ok(())
953            }
954            RowExec::Strip {
955                ops,
956                src_opaque_alpha,
957            } => {
958                strip::exec_strip_row(
959                    self.src.layout(),
960                    self.dst.layout(),
961                    ops,
962                    self.depth_policy,
963                    *src_opaque_alpha,
964                    &self.accel,
965                    &src_row[..need_src],
966                    &mut dst_row[..need_dst],
967                    w,
968                    row_index,
969                );
970                Ok(())
971            }
972            RowExec::Cms {
973                transform,
974                clip_f32_color,
975            } => {
976                let dst_active = &mut dst_row[..need_dst];
977                transform.transform_row(&src_row[..need_src], dst_active, width_pixels)?;
978                if *clip_f32_color {
979                    let ch = self.dst.layout().channels();
980                    let color_ch = if self.dst.layout().order().has_alpha_slot() {
981                        ch - 1
982                    } else {
983                        ch
984                    };
985                    if let Ok(floats) = bytemuck::try_cast_slice_mut::<u8, f32>(dst_active) {
986                        for px in floats.chunks_exact_mut(ch) {
987                            for v in &mut px[..color_ch] {
988                                *v = v.clamp(0.0, 1.0);
989                            }
990                        }
991                    } else {
992                        let px_bytes = ch * 4;
993                        for px in dst_active.chunks_exact_mut(px_bytes) {
994                            for slot in px[..color_ch * 4].as_chunks_mut::<4>().0 {
995                                let v = f32::from_ne_bytes(*slot).clamp(0.0, 1.0);
996                                *slot = v.to_ne_bytes();
997                            }
998                        }
999                    }
1000                }
1001                Ok(())
1002            }
1003        }
1004    }
1005}
1006
1007/// Zero-allocation sized wrapper allowing any `S: PixelSource + ?Sized` (including
1008/// `dyn PixelSource` itself) to coerce to `&dyn PixelSource` for monomorphization erasure.
1009#[repr(transparent)]
1010pub(crate) struct RefSource<'a, S: PixelSource + ?Sized>(pub(crate) &'a S);
1011
1012impl<S: PixelSource + ?Sized> PixelSource for RefSource<'_, S> {
1013    #[inline]
1014    fn source_width(&self) -> u32 {
1015        self.0.source_width()
1016    }
1017    #[inline]
1018    fn source_height(&self) -> u32 {
1019        self.0.source_height()
1020    }
1021    #[inline]
1022    fn source_format(&self) -> &PixelFormat {
1023        self.0.source_format()
1024    }
1025    #[inline]
1026    fn source_claims(&self) -> SampleClaims {
1027        self.0.source_claims()
1028    }
1029    #[inline]
1030    fn source_hdr(&self) -> HdrMetadata {
1031        self.0.source_hdr()
1032    }
1033    #[inline]
1034    fn source_origin(&self) -> Option<&zenpixels::ColorOrigin> {
1035        self.0.source_origin()
1036    }
1037    #[inline]
1038    fn source_orientation(&self) -> zenpixels::Orientation {
1039        self.0.source_orientation()
1040    }
1041    #[inline]
1042    fn source_row(&self, y: u32) -> &[u8] {
1043        self.0.source_row(y)
1044    }
1045}
1046
1047/// Zero-allocation sized wrapper allowing any `D: PixelSink + ?Sized` (including
1048/// `dyn PixelSink` itself) to coerce to `&mut dyn PixelSink` for monomorphization erasure.
1049#[repr(transparent)]
1050pub(crate) struct RefSink<'a, D: PixelSink + ?Sized>(pub(crate) &'a mut D);
1051
1052impl<D: PixelSink + ?Sized> PixelSink for RefSink<'_, D> {
1053    #[inline]
1054    fn sink_width(&self) -> u32 {
1055        self.0.sink_width()
1056    }
1057    #[inline]
1058    fn sink_height(&self) -> u32 {
1059        self.0.sink_height()
1060    }
1061    #[inline]
1062    fn sink_format(&self) -> &PixelFormat {
1063        self.0.sink_format()
1064    }
1065    #[inline]
1066    fn sink_row_mut(&mut self, y: u32) -> Result<&mut [u8], At<zenpixels::BufferError>> {
1067        self.0.sink_row_mut(y)
1068    }
1069    #[inline]
1070    fn sink_finish(&mut self, claims: SampleClaims, hdr: HdrMetadata) {
1071        self.0.sink_finish(claims, hdr);
1072    }
1073    #[inline]
1074    fn sink_set_origin(&mut self, origin: zenpixels::ColorOrigin) {
1075        self.0.sink_set_origin(origin);
1076    }
1077    #[inline]
1078    fn sink_set_orientation(&mut self, orientation: zenpixels::Orientation) {
1079        self.0.sink_set_orientation(orientation);
1080    }
1081}
1082
1083/// Whole-image conversion plan supporting streaming HDR peak measurement
1084/// ([`PeakSource::Measured`]), container metadata peaks ([`PeakSource::Declared`]),
1085/// and uniform execution across [`PixelView`](zenpixels::PixelView), [`PixelBuf`], and [`BandedBuf`](zenpixels::BandedBuf).
1086#[derive(Clone, Debug)]
1087pub struct ImagePlan {
1088    src: PixelFormat,
1089    dst: PixelFormat,
1090    policy: ConvertPolicy,
1091    peak: PeakSource,
1092    /// Cached compiled [`RowPlan`] when the route does not depend on per-image
1093    /// measured/declared HDR peaks or runtime buffer [`SampleClaims`].
1094    cached_row_plan: Option<RowPlan>,
1095}
1096
1097impl ImagePlan {
1098    /// Policy used to construct this plan (crate-internal for streaming `OutputPlan`).
1099    #[inline]
1100    pub(crate) fn policy(&self) -> &ConvertPolicy {
1101        &self.policy
1102    }
1103
1104    /// Validate and construct an image-level conversion plan.
1105    ///
1106    /// Accepts either borrowed `&PixelFormat` or owned `PixelFormat` at the call site and borrows
1107    /// `&ConvertPolicy` (retaining internal clones inside the built plan).
1108    ///
1109    /// When the route does not require per-image HDR peak resolution or runtime
1110    /// buffer facts (`DiscardIfOpaque` / `Forbid` on U16→U8, RGB→Gray, or float→int),
1111    /// the compiled [`RowPlan`] is built **once** and reused across every `execute` call.
1112    #[inline]
1113    pub fn build(
1114        src: impl AsRef<PixelFormat>,
1115        dst: impl AsRef<PixelFormat>,
1116        policy: &ConvertPolicy,
1117        peak: PeakSource,
1118    ) -> Result<Self, At<ConvertError>> {
1119        Self::build_inner(src.as_ref(), dst.as_ref(), policy, peak, None)
1120    }
1121
1122    /// Build a reusable [`ImagePlan`] with optional cooperative cancellation and progress via
1123    /// `pulse` (forwarded to [`CmsBackend::build_transform`](crate::CmsBackend::build_transform)
1124    /// and [`ToneMapper::prepare`](crate::ToneMapper::prepare) when eagerly compiling the row
1125    /// plan; pass `None` when not needed).
1126    #[inline]
1127    pub fn build_with_pulse(
1128        src: impl AsRef<PixelFormat>,
1129        dst: impl AsRef<PixelFormat>,
1130        policy: &ConvertPolicy,
1131        peak: PeakSource,
1132        pulse: Option<&dyn Pulse>,
1133    ) -> Result<Self, At<ConvertError>> {
1134        Self::build_inner(src.as_ref(), dst.as_ref(), policy, peak, pulse)
1135    }
1136
1137    #[inline(never)]
1138    fn build_inner(
1139        src: &PixelFormat,
1140        dst: &PixelFormat,
1141        policy: &ConvertPolicy,
1142        peak: PeakSource,
1143        pulse: Option<&dyn Pulse>,
1144    ) -> Result<Self, At<ConvertError>> {
1145        let u16_narrowable = src.layout().sample() == SampleType::U16
1146            && src.layout().packing().is_full()
1147            && !dst.layout().sample().is_float()
1148            && color_range(src.color()) == color_range(dst.color())
1149            && same_color_meaning(src.color(), dst.color())
1150            && is_depth_reducing(src, dst, policy.source_claims);
1151
1152        let reassociates_alpha = matches!(
1153            (src.color().alpha(), dst.color().alpha()),
1154            (AlphaMode::Straight, AlphaMode::Premultiplied)
1155                | (AlphaMode::Premultiplied, AlphaMode::Straight)
1156        );
1157
1158        let needs_runtime_facts = (src == dst
1159            && src.color().alpha() == AlphaMode::Opaque
1160            && src.layout().order().has_alpha_slot()
1161            && !policy.source_claims.all_opaque)
1162            || (policy.alpha == AlphaPolicy::DiscardIfOpaque
1163                && matches!(
1164                    src.color().alpha(),
1165                    AlphaMode::Straight | AlphaMode::Premultiplied
1166                )
1167                && matches!(
1168                    dst.color().alpha(),
1169                    AlphaMode::None | AlphaMode::Undefined | AlphaMode::Opaque
1170                )
1171                && !policy.source_claims.all_opaque)
1172            || (policy.depth == DepthPolicy::Forbid
1173                && reassociates_alpha
1174                && !policy.source_claims.all_opaque)
1175            || (policy.depth == DepthPolicy::Forbid && u16_narrowable)
1176            || ((policy.depth == DepthPolicy::Forbid || policy.gamut == GamutPolicy::Forbid)
1177                && !matches!(src.color(), ColorSpace::Gray { .. })
1178                && matches!(dst.color(), ColorSpace::Gray { .. })
1179                && !policy.source_claims.all_grayscale)
1180            || (policy.gamut == GamutPolicy::Forbid
1181                && src.layout().sample().is_float()
1182                && !dst.layout().sample().is_float()
1183                && !policy.source_claims.float.is_unit_interval());
1184
1185        let is_hdr_tonemap = color_transfer(src.color()).is_hdr()
1186            && !color_transfer(dst.color()).is_hdr()
1187            && matches!(
1188                dst.color(),
1189                ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. }
1190            )
1191            && policy.tone_map_hdr_to_sdr;
1192
1193        let is_linear_hdr_candidate =
1194            is_scene_linear_hdr_candidate(src, dst) && policy.tone_map_hdr_to_sdr;
1195
1196        let mapper_needs_runtime_peak = (is_hdr_tonemap
1197            && !matches!(peak, PeakSource::Fixed(_))
1198            && resolve_tone_mapper(policy)
1199                .map(|m| m.requirements().source_peak_nits && m.baked_peaks().is_none())
1200                .unwrap_or(true))
1201            || (is_linear_hdr_candidate && !matches!(peak, PeakSource::Fixed(_)));
1202
1203        if !needs_runtime_facts && !mapper_needs_runtime_peak {
1204            let fixed_peak = match peak {
1205                PeakSource::Fixed(n) => {
1206                    if is_linear_hdr_candidate {
1207                        let ceiling = linear_sdr_ceiling_nits(src, dst, policy);
1208                        if n.nits() > ceiling * (1.0 + 1e-4) {
1209                            Some(n)
1210                        } else {
1211                            None
1212                        }
1213                    } else {
1214                        Some(n)
1215                    }
1216                }
1217                _ => None,
1218            };
1219            let compiled = RowPlan::build_inner(src, dst, policy, fixed_peak, pulse)?;
1220            return Ok(Self {
1221                src: src.clone(),
1222                dst: dst.clone(),
1223                policy: policy.clone(),
1224                peak,
1225                cached_row_plan: Some(compiled),
1226            });
1227        }
1228
1229        // Validate structural/policy compatibility without needlessly invoking CMS/mapper twice.
1230        let mut probe_policy = policy.clone();
1231        if src != dst && (probe_policy.alpha == AlphaPolicy::DiscardIfOpaque || reassociates_alpha)
1232        {
1233            probe_policy.source_claims.all_opaque = true;
1234        }
1235        if probe_policy.depth == DepthPolicy::Forbid && u16_narrowable {
1236            let sr = color_range(src.color());
1237            let min_c = min_color_bits(dst).max(if sr == SignalRange::Narrow { 8 } else { 1 });
1238            let min_a = if dst.layout().order().has_alpha_slot() {
1239                raw_channel_bits(dst, dst.layout().channels() - 1).min(16)
1240            } else {
1241                16
1242            };
1243            probe_policy.source_claims.depth =
1244                ExactDepth::new(SampleType::U16, sr, min_c.min(16), min_a.max(1)).ok();
1245        }
1246        if (probe_policy.depth == DepthPolicy::Forbid || probe_policy.gamut == GamutPolicy::Forbid)
1247            && !matches!(src.color(), ColorSpace::Gray { .. })
1248            && matches!(dst.color(), ColorSpace::Gray { .. })
1249        {
1250            probe_policy.source_claims.all_grayscale = true;
1251        }
1252        if probe_policy.gamut == GamutPolicy::Forbid
1253            && src.layout().sample().is_float()
1254            && !dst.layout().sample().is_float()
1255        {
1256            probe_policy.source_claims.float = FloatClaims::UNIT_INTERVAL;
1257        }
1258        let pre = preflight_and_classify(src, dst, &probe_policy)?;
1259        if !pre.uses_cms {
1260            let test_peak = match peak {
1261                PeakSource::Fixed(n) => Some(n),
1262                _ if is_hdr_tonemap => Some(Nits::new_positive_or_panic(1000.0)),
1263                _ => None,
1264            };
1265            let _ = RowPlan::build_inner(src, dst, &probe_policy, test_peak, pulse)?;
1266        }
1267        Ok(Self {
1268            src: src.clone(),
1269            dst: dst.clone(),
1270            policy: policy.clone(),
1271            peak,
1272            cached_row_plan: None,
1273        })
1274    }
1275
1276    /// Execute into an existing [`PixelSink`] (`PixelViewMut`, `PixelBuf`, `BandedBuf`)
1277    /// with O(1) row scratch memory (never allocates a full-image F32 temporary!).
1278    #[inline]
1279    pub fn execute_into<S: PixelSource + ?Sized, D: PixelSink + ?Sized>(
1280        &self,
1281        src: &S,
1282        dst: &mut D,
1283    ) -> Result<(), At<ConvertError>> {
1284        self.execute_into_dyn(&RefSource(src), &mut RefSink(dst), None)
1285    }
1286
1287    /// Execute into an existing [`PixelSink`] with optional cooperative cancellation and
1288    /// row progress via `pulse` (pass `None` when not needed).
1289    #[inline]
1290    pub fn execute_into_with_pulse<S: PixelSource + ?Sized, D: PixelSink + ?Sized>(
1291        &self,
1292        src: &S,
1293        dst: &mut D,
1294        pulse: Option<&dyn Pulse>,
1295    ) -> Result<(), At<ConvertError>> {
1296        self.execute_into_dyn(&RefSource(src), &mut RefSink(dst), pulse)
1297    }
1298
1299    #[inline(never)]
1300    fn execute_into_dyn(
1301        &self,
1302        src: &dyn PixelSource,
1303        dst: &mut dyn PixelSink,
1304        pulse: Option<&dyn Pulse>,
1305    ) -> Result<(), At<ConvertError>> {
1306        let pulse = live_pulse(pulse);
1307        check_pulse(pulse)?;
1308        let w = src.source_width();
1309        let h = src.source_height();
1310        if dst.sink_width() != w || dst.sink_height() != h {
1311            return Err(err_at(ConvertError::DimensionMismatch));
1312        }
1313        if src.source_format() != &self.src || dst.sink_format() != &self.dst {
1314            return Err(err_at(ConvertError::UnsupportedRoute));
1315        }
1316
1317        let merged_src_facts = merge_facts(self.policy.source_claims, src.source_claims());
1318        let built_plan: RowPlan;
1319        let row_plan: &RowPlan = if let Some(cached) = &self.cached_row_plan {
1320            Self::run_rows_dyn(cached, src, dst, w, h, pulse)?;
1321            cached
1322        } else {
1323            let mut eff_policy = self.policy.clone();
1324            eff_policy.source_claims = merged_src_facts;
1325            if let Some(p) = pulse
1326                && self.needs_measured_peak_pass(&eff_policy)
1327            {
1328                let rows = u64::from(h);
1329                built_plan = Stages::new(
1330                    p,
1331                    &[
1332                        PhaseSpec::new("measure-peak", 1, Total::Exact(rows)).units("rows"),
1333                        PhaseSpec::new("convert", 3, Total::Exact(rows)).units("rows"),
1334                    ],
1335                )
1336                .complete_with_classified(is_stop_at, |stages| {
1337                    let resolved_peak = stages.run_classified(is_stop_at, |st| {
1338                        self.resolve_peak_dyn(src, &eff_policy, Some(st))
1339                    })?;
1340                    stages.run_classified(is_stop_at, |st| {
1341                        let plan = RowPlan::build_inner(
1342                            &self.src,
1343                            &self.dst,
1344                            &eff_policy,
1345                            resolved_peak,
1346                            Some(st),
1347                        )?;
1348                        Self::run_rows_dyn(&plan, src, dst, w, h, Some(st))?;
1349                        Ok(plan)
1350                    })
1351                })?;
1352            } else {
1353                let resolved_peak = self.resolve_peak_dyn(src, &eff_policy, pulse)?;
1354                built_plan =
1355                    RowPlan::build_inner(&self.src, &self.dst, &eff_policy, resolved_peak, pulse)?;
1356                Self::run_rows_dyn(&built_plan, src, dst, w, h, pulse)?;
1357            }
1358            &built_plan
1359        };
1360
1361        let preserves_icc_hdr = matches!(self.dst.color(), ColorSpace::Icc { .. })
1362            && !(self.src.layout().sample().is_float() && !self.dst.layout().sample().is_float());
1363        let out_hdr = if same_photometry(self.src.color(), self.dst.color())
1364            && (self.dst.can_represent_hdr() || preserves_icc_hdr)
1365        {
1366            src.source_hdr()
1367        } else {
1368            HdrMetadata::default()
1369        };
1370        let out_facts = match &row_plan.exec {
1371            RowExec::Byte(bp) => {
1372                derive_output_facts_byte(&self.src, &self.dst, merged_src_facts, *bp)
1373            }
1374            _ => row_plan.output_claims(),
1375        };
1376        if same_color_meaning(self.src.color(), self.dst.color())
1377            && let Some(orig) = src.source_origin()
1378        {
1379            dst.sink_set_origin(orig.clone());
1380        } else {
1381            // Clear any stale `ColorOrigin` on a reused sink when color meaning changed!
1382            dst.sink_set_origin(zenpixels::ColorOrigin::assumed());
1383        }
1384        dst.sink_set_orientation(src.source_orientation());
1385        dst.sink_finish(out_facts, out_hdr);
1386        Ok(())
1387    }
1388
1389    #[inline(never)]
1390    fn run_rows_dyn(
1391        row_plan: &RowPlan,
1392        src: &dyn PixelSource,
1393        dst: &mut dyn PixelSink,
1394        w: u32,
1395        h: u32,
1396        pulse: Option<&dyn Pulse>,
1397    ) -> Result<(), At<ConvertError>> {
1398        for y in 0..h {
1399            let dst_row = dst
1400                .sink_row_mut(y)
1401                .map_err(|e| err_at((*e.error()).into()))?;
1402            row_plan.convert_row_at(y, src.source_row(y), dst_row, w)?;
1403            step_pulse(pulse, 1)?;
1404        }
1405        Ok(())
1406    }
1407
1408    /// Execute into a freshly allocated tightly packed [`PixelBuf`].
1409    #[inline]
1410    pub fn execute<S: PixelSource + ?Sized>(&self, src: &S) -> Result<PixelBuf, At<ConvertError>> {
1411        self.execute_dyn(&RefSource(src), None)
1412    }
1413
1414    /// Execute into a freshly allocated tightly packed [`PixelBuf`] with optional cooperative
1415    /// cancellation and row progress via `pulse` (pass `None` when not needed).
1416    #[inline]
1417    pub fn execute_with_pulse<S: PixelSource + ?Sized>(
1418        &self,
1419        src: &S,
1420        pulse: Option<&dyn Pulse>,
1421    ) -> Result<PixelBuf, At<ConvertError>> {
1422        self.execute_dyn(&RefSource(src), pulse)
1423    }
1424
1425    #[inline(never)]
1426    fn execute_dyn(
1427        &self,
1428        src: &dyn PixelSource,
1429        pulse: Option<&dyn Pulse>,
1430    ) -> Result<PixelBuf, At<ConvertError>> {
1431        let pulse = live_pulse(pulse);
1432        check_pulse(pulse)?;
1433        // Validate source spec BEFORE allocating destination memory!
1434        if src.source_format() != &self.src {
1435            return Err(err_at(ConvertError::UnsupportedRoute));
1436        }
1437        let mut out = PixelBuf::new(src.source_width(), src.source_height(), self.dst.clone())
1438            .map_err(|e| err_at((*e.error()).into()))?;
1439        self.execute_into_dyn(src, &mut out, pulse)?;
1440        Ok(out)
1441    }
1442
1443    /// One-shot conversion from any [`PixelSource`] ([`PixelBuf`], [`PixelView`](zenpixels::PixelView),
1444    /// [`BandedBuf`](zenpixels::BandedBuf), or `dyn PixelSource`) into a newly allocated
1445    /// tightly packed [`PixelBuf`].
1446    ///
1447    /// Resolves HDR source peak via [`PeakSource::Measured`] **only when HDR→SDR tone mapping
1448    /// actually requires it**; for explicit peak control (`Declared` / `Fixed`), use
1449    /// [`ImagePlan::convert_with_peak`].
1450    #[inline]
1451    pub fn convert<S: PixelSource + ?Sized>(
1452        src: &S,
1453        destination_format: impl AsRef<PixelFormat>,
1454        policy: &ConvertPolicy,
1455    ) -> Result<PixelBuf, At<ConvertError>> {
1456        Self::convert_with_peak_dyn(
1457            &RefSource(src),
1458            destination_format.as_ref(),
1459            policy,
1460            PeakSource::Measured,
1461            None,
1462        )
1463    }
1464
1465    /// One-shot conversion from any [`PixelSource`] into a newly allocated [`PixelBuf`]
1466    /// with an explicit [`PeakSource`] (`Measured`, `Declared`, or `Fixed`).
1467    #[inline]
1468    pub fn convert_with_peak<S: PixelSource + ?Sized>(
1469        src: &S,
1470        destination_format: impl AsRef<PixelFormat>,
1471        policy: &ConvertPolicy,
1472        peak: PeakSource,
1473    ) -> Result<PixelBuf, At<ConvertError>> {
1474        Self::convert_with_peak_dyn(
1475            &RefSource(src),
1476            destination_format.as_ref(),
1477            policy,
1478            peak,
1479            None,
1480        )
1481    }
1482
1483    /// One-shot conversion from any [`PixelSource`] into a newly allocated [`PixelBuf`]
1484    /// with an explicit [`PeakSource`] and optional cooperative cancellation/progress via
1485    /// `pulse` (pass `None` when not needed).
1486    #[inline]
1487    pub fn convert_with_pulse<S: PixelSource + ?Sized>(
1488        src: &S,
1489        destination_format: impl AsRef<PixelFormat>,
1490        policy: &ConvertPolicy,
1491        peak: PeakSource,
1492        pulse: Option<&dyn Pulse>,
1493    ) -> Result<PixelBuf, At<ConvertError>> {
1494        Self::convert_with_peak_dyn(
1495            &RefSource(src),
1496            destination_format.as_ref(),
1497            policy,
1498            peak,
1499            pulse,
1500        )
1501    }
1502
1503    #[inline(never)]
1504    fn convert_with_peak_dyn(
1505        src: &dyn PixelSource,
1506        destination_format: &PixelFormat,
1507        policy: &ConvertPolicy,
1508        peak: PeakSource,
1509        pulse: Option<&dyn Pulse>,
1510    ) -> Result<PixelBuf, At<ConvertError>> {
1511        let pulse = live_pulse(pulse);
1512        check_pulse(pulse)?;
1513        let plan = Self::build_inner(src.source_format(), destination_format, policy, peak, pulse)?;
1514        plan.execute_dyn(src, pulse)
1515    }
1516
1517    /// One-shot conversion from any [`PixelSource`] into any existing [`PixelSink`]
1518    /// (`PixelBuf`, [`PixelViewMut`](zenpixels::PixelViewMut), or
1519    /// [`BandedBuf`](zenpixels::BandedBuf)) with O(1) row scratch memory.
1520    ///
1521    /// Resolves HDR source peak via [`PeakSource::Measured`] **only when HDR→SDR tone mapping
1522    /// actually requires it**; for explicit peak control, use [`ImagePlan::convert_into_with_peak`].
1523    #[inline]
1524    pub fn convert_into<S: PixelSource + ?Sized, D: PixelSink + ?Sized>(
1525        src: &S,
1526        dst: &mut D,
1527        policy: &ConvertPolicy,
1528    ) -> Result<(), At<ConvertError>> {
1529        Self::convert_into_with_peak_dyn(
1530            &RefSource(src),
1531            &mut RefSink(dst),
1532            policy,
1533            PeakSource::Measured,
1534            None,
1535        )
1536    }
1537
1538    /// One-shot conversion from any [`PixelSource`] into any [`PixelSink`] with an explicit
1539    /// [`PeakSource`].
1540    #[inline]
1541    pub fn convert_into_with_peak<S: PixelSource + ?Sized, D: PixelSink + ?Sized>(
1542        src: &S,
1543        dst: &mut D,
1544        policy: &ConvertPolicy,
1545        peak: PeakSource,
1546    ) -> Result<(), At<ConvertError>> {
1547        Self::convert_into_with_peak_dyn(&RefSource(src), &mut RefSink(dst), policy, peak, None)
1548    }
1549
1550    /// One-shot conversion from any [`PixelSource`] into any [`PixelSink`] with an explicit
1551    /// [`PeakSource`] and optional cooperative cancellation/progress via `pulse` (pass `None`
1552    /// when not needed).
1553    #[inline]
1554    pub fn convert_into_with_pulse<S: PixelSource + ?Sized, D: PixelSink + ?Sized>(
1555        src: &S,
1556        dst: &mut D,
1557        policy: &ConvertPolicy,
1558        peak: PeakSource,
1559        pulse: Option<&dyn Pulse>,
1560    ) -> Result<(), At<ConvertError>> {
1561        Self::convert_into_with_peak_dyn(&RefSource(src), &mut RefSink(dst), policy, peak, pulse)
1562    }
1563
1564    #[inline(never)]
1565    fn convert_into_with_peak_dyn(
1566        src: &dyn PixelSource,
1567        dst: &mut dyn PixelSink,
1568        policy: &ConvertPolicy,
1569        peak: PeakSource,
1570        pulse: Option<&dyn Pulse>,
1571    ) -> Result<(), At<ConvertError>> {
1572        let pulse = live_pulse(pulse);
1573        check_pulse(pulse)?;
1574        let plan = Self::build_inner(src.source_format(), dst.sink_format(), policy, peak, pulse)?;
1575        plan.execute_into_dyn(src, dst, pulse)
1576    }
1577
1578    /// One-shot conversion from any [`PixelSource`] to full-range sRGB `RGB8` under
1579    /// `ConvertPolicy::permissive().with_alpha(AlphaPolicy::DiscardIfOpaque)`.
1580    ///
1581    /// `DiscardIfOpaque` is a **metadata-only** check (`AlphaMode::None`, `AlphaMode::Opaque`,
1582    /// `AlphaMode::Undefined`, or `src.source_claims().all_opaque == true`) — it does **not** scan
1583    /// pixels. For straight-alpha buffers whose pixels happen to be opaque, run
1584    /// [`PixelScanExt::measure_claims`](crate::PixelScanExt::measure_claims) first (or pass [`AlphaPolicy::CompositeOnto`] /
1585    /// [`AlphaPolicy::DiscardUnchecked`] to [`ImagePlan::convert`]).
1586    #[doc(alias = "to_rgb8")]
1587    #[inline]
1588    pub fn to_rgb8_if_opaque<S: PixelSource + ?Sized>(
1589        src: &S,
1590    ) -> Result<PixelBuf, At<ConvertError>> {
1591        Self::to_rgb8_if_opaque_dyn(&RefSource(src))
1592    }
1593
1594    #[inline(never)]
1595    fn to_rgb8_if_opaque_dyn(src: &dyn PixelSource) -> Result<PixelBuf, At<ConvertError>> {
1596        let policy = ConvertPolicy::permissive().with_alpha(AlphaPolicy::DiscardIfOpaque);
1597        Self::convert_with_peak_dyn(
1598            src,
1599            &zenpixels::formats::RGB8_SRGB,
1600            &policy,
1601            PeakSource::Measured,
1602            None,
1603        )
1604    }
1605
1606    /// One-shot conversion from any [`PixelSource`] to full-range sRGB straight-alpha `RGBA8`
1607    /// under [`ConvertPolicy::permissive`].
1608    #[inline]
1609    pub fn to_rgba8<S: PixelSource + ?Sized>(src: &S) -> Result<PixelBuf, At<ConvertError>> {
1610        Self::to_rgba8_dyn(&RefSource(src))
1611    }
1612
1613    #[inline(never)]
1614    fn to_rgba8_dyn(src: &dyn PixelSource) -> Result<PixelBuf, At<ConvertError>> {
1615        Self::convert_with_peak_dyn(
1616            src,
1617            &zenpixels::formats::RGBA8_SRGB,
1618            &ConvertPolicy::permissive(),
1619            PeakSource::Measured,
1620            None,
1621        )
1622    }
1623
1624    /// One-shot conversion from any [`PixelSource`] to full-range sRGB `GRAY8` (encoded Y' luma
1625    /// by default) under `ConvertPolicy::permissive().with_alpha(AlphaPolicy::DiscardIfOpaque)`.
1626    ///
1627    /// `DiscardIfOpaque` is a **metadata-only** check (`AlphaMode::None`, `AlphaMode::Opaque`,
1628    /// `AlphaMode::Undefined`, or `src.source_claims().all_opaque == true`) — it does **not** scan
1629    /// pixels. For straight-alpha buffers whose pixels happen to be opaque, run
1630    /// [`PixelScanExt::measure_claims`](crate::PixelScanExt::measure_claims) first (or pass [`AlphaPolicy::CompositeOnto`] /
1631    /// [`AlphaPolicy::DiscardUnchecked`] to [`ImagePlan::convert`]).
1632    #[doc(alias = "to_gray8")]
1633    #[inline]
1634    pub fn to_gray8_if_opaque<S: PixelSource + ?Sized>(
1635        src: &S,
1636    ) -> Result<PixelBuf, At<ConvertError>> {
1637        Self::to_gray8_if_opaque_dyn(&RefSource(src))
1638    }
1639
1640    #[inline(never)]
1641    fn to_gray8_if_opaque_dyn(src: &dyn PixelSource) -> Result<PixelBuf, At<ConvertError>> {
1642        let policy = ConvertPolicy::permissive().with_alpha(AlphaPolicy::DiscardIfOpaque);
1643        Self::convert_with_peak_dyn(
1644            src,
1645            &zenpixels::formats::GRAY8_SRGB,
1646            &policy,
1647            PeakSource::Measured,
1648            None,
1649        )
1650    }
1651
1652    /// One-shot conversion from any [`PixelSource`] to full-range sRGB straight-alpha `BGRA8`
1653    /// under [`ConvertPolicy::permissive`].
1654    #[inline]
1655    pub fn to_bgra8<S: PixelSource + ?Sized>(src: &S) -> Result<PixelBuf, At<ConvertError>> {
1656        Self::to_bgra8_dyn(&RefSource(src))
1657    }
1658
1659    #[inline(never)]
1660    fn to_bgra8_dyn(src: &dyn PixelSource) -> Result<PixelBuf, At<ConvertError>> {
1661        Self::convert_with_peak_dyn(
1662            src,
1663            &zenpixels::formats::BGRA8_SRGB,
1664            &ConvertPolicy::permissive(),
1665            PeakSource::Measured,
1666            None,
1667        )
1668    }
1669
1670    fn needs_measured_peak_pass(&self, policy: &ConvertPolicy) -> bool {
1671        if self.peak != PeakSource::Measured || !policy.tone_map_hdr_to_sdr {
1672            return false;
1673        }
1674        let is_transfer_hdr = color_transfer(self.src.color()).is_hdr()
1675            && !color_transfer(self.dst.color()).is_hdr()
1676            && matches!(
1677                self.dst.color(),
1678                ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. }
1679            );
1680        let is_linear_hdr_cand = is_scene_linear_hdr_candidate(&self.src, &self.dst);
1681        if is_linear_hdr_cand {
1682            return !policy.source_claims.float.is_unit_interval();
1683        }
1684        if !is_transfer_hdr {
1685            return false;
1686        }
1687        resolve_tone_mapper(policy)
1688            .map(|m| m.requirements().source_peak_nits && m.baked_peaks().is_none())
1689            .unwrap_or(true)
1690    }
1691
1692    #[inline(never)]
1693    fn resolve_peak_dyn(
1694        &self,
1695        src: &dyn PixelSource,
1696        policy: &ConvertPolicy,
1697        pulse: Option<&dyn Pulse>,
1698    ) -> Result<Option<Nits>, At<ConvertError>> {
1699        let is_transfer_hdr = color_transfer(self.src.color()).is_hdr()
1700            && !color_transfer(self.dst.color()).is_hdr()
1701            && matches!(
1702                self.dst.color(),
1703                ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. }
1704            );
1705        let is_linear_hdr_cand = is_scene_linear_hdr_candidate(&self.src, &self.dst);
1706
1707        if (!is_transfer_hdr && !is_linear_hdr_cand) || !policy.tone_map_hdr_to_sdr {
1708            return Ok(None);
1709        }
1710
1711        if is_linear_hdr_cand {
1712            let ceiling = linear_sdr_ceiling_nits(&self.src, &self.dst, policy);
1713            let threshold = ceiling * (1.0 + 1e-4);
1714            return match self.peak {
1715                PeakSource::Fixed(n) => {
1716                    if n.nits() > threshold {
1717                        Ok(Some(n))
1718                    } else {
1719                        Ok(None)
1720                    }
1721                }
1722                PeakSource::Declared => {
1723                    let hdr = src.source_hdr();
1724                    if let Some(cll) = hdr.content_light_level
1725                        && f32::from(cll.max_content_light_level) > threshold
1726                        && let Some(n) = Nits::new_positive(f32::from(cll.max_content_light_level))
1727                    {
1728                        return Ok(Some(n));
1729                    }
1730                    if let Some(md) = hdr.mastering
1731                        && md.max_luminance > threshold
1732                        && let Some(n) = Nits::new_positive(md.max_luminance)
1733                    {
1734                        return Ok(Some(n));
1735                    }
1736                    Ok(None)
1737                }
1738                PeakSource::Measured => {
1739                    if policy.source_claims.float.is_unit_interval() {
1740                        return Ok(None);
1741                    }
1742                    let white = self
1743                        .src
1744                        .color()
1745                        .diffuse_white()
1746                        .or_else(|| self.dst.color().diffuse_white())
1747                        .or(policy.diffuse_white)
1748                        .unwrap_or(DiffuseWhite::BT2408);
1749                    let measured = crate::measure::measure_max_nits_streaming_dyn(
1750                        src,
1751                        white,
1752                        policy.hlg_rendering,
1753                        pulse,
1754                    )?;
1755                    if measured > threshold {
1756                        Ok(Nits::new_positive(measured))
1757                    } else {
1758                        Ok(None)
1759                    }
1760                }
1761                _ => Err(err_at(ConvertError::UnsupportedRoute)),
1762            };
1763        }
1764
1765        if let Ok(mapper) = resolve_tone_mapper(policy)
1766            && (!mapper.requirements().source_peak_nits || mapper.baked_peaks().is_some())
1767        {
1768            return Ok(None);
1769        }
1770        match self.peak {
1771            PeakSource::Fixed(n) => Ok(Some(n)),
1772            PeakSource::Declared => {
1773                let hdr = src.source_hdr();
1774                if let Some(cll) = hdr.content_light_level
1775                    && cll.max_content_light_level > 0
1776                    && let Some(n) = Nits::new_positive(f32::from(cll.max_content_light_level))
1777                {
1778                    return Ok(Some(n));
1779                }
1780                if let Some(md) = hdr.mastering
1781                    && let Some(n) = Nits::new_positive(md.max_luminance)
1782                {
1783                    return Ok(Some(n));
1784                }
1785                Err(err_at(ConvertError::MissingDeclaredPeak))
1786            }
1787            PeakSource::Measured => {
1788                let white = self
1789                    .src
1790                    .color()
1791                    .diffuse_white()
1792                    .or_else(|| self.dst.color().diffuse_white())
1793                    .or(policy.diffuse_white)
1794                    .unwrap_or(DiffuseWhite::BT2408);
1795                let measured = crate::measure::measure_max_nits_streaming_dyn(
1796                    src,
1797                    white,
1798                    policy.hlg_rendering,
1799                    pulse,
1800                )?;
1801                Ok(Some(
1802                    Nits::new_positive(measured.max(policy.sdr_peak.nits()))
1803                        .unwrap_or(policy.sdr_peak),
1804                ))
1805            }
1806            _ => Err(err_at(ConvertError::UnsupportedRoute)),
1807        }
1808    }
1809}
1810
1811/// Ergonomic one-shot conversion methods directly on any [`PixelSource`]
1812/// ([`PixelBuf`], [`PixelView`](zenpixels::PixelView), [`BandedBuf`](zenpixels::BandedBuf), or `dyn PixelSource`).
1813///
1814/// Every method is a 1-line `#[inline]` shim over [`ImagePlan`]'s type-erased execution core,
1815/// so calling `src.convert_to(...)` or `src.convert_into(&mut dst, ...)` across any combination
1816/// of carriers compiles to a single non-generic implementation with zero monomorphization bloat.
1817pub trait PixelConvertExt: PixelSource {
1818    /// Convert `self` into a newly allocated tightly packed [`PixelBuf`].
1819    ///
1820    /// Resolves HDR source peak via [`PeakSource::Measured`] only when HDR→SDR tone mapping
1821    /// requires it; use [`convert_to_with_peak`](Self::convert_to_with_peak) for explicit control.
1822    #[inline]
1823    fn convert_to(
1824        &self,
1825        destination_format: impl AsRef<PixelFormat>,
1826        policy: &ConvertPolicy,
1827    ) -> Result<PixelBuf, At<ConvertError>> {
1828        ImagePlan::convert(self, destination_format, policy)
1829    }
1830
1831    /// Convert `self` into a newly allocated [`PixelBuf`] with an explicit [`PeakSource`].
1832    #[inline]
1833    fn convert_to_with_peak(
1834        &self,
1835        destination_format: impl AsRef<PixelFormat>,
1836        policy: &ConvertPolicy,
1837        peak: PeakSource,
1838    ) -> Result<PixelBuf, At<ConvertError>> {
1839        ImagePlan::convert_with_peak(self, destination_format, policy, peak)
1840    }
1841
1842    /// Convert `self` directly into any existing [`PixelSink`] (`PixelBuf`,
1843    /// [`PixelViewMut`](zenpixels::PixelViewMut), or [`BandedBuf`](zenpixels::BandedBuf)).
1844    #[inline]
1845    fn convert_into<D: PixelSink + ?Sized>(
1846        &self,
1847        dst: &mut D,
1848        policy: &ConvertPolicy,
1849    ) -> Result<(), At<ConvertError>> {
1850        ImagePlan::convert_into(self, dst, policy)
1851    }
1852
1853    /// Convert `self` directly into any existing [`PixelSink`] with an explicit [`PeakSource`].
1854    #[inline]
1855    fn convert_into_with_peak<D: PixelSink + ?Sized>(
1856        &self,
1857        dst: &mut D,
1858        policy: &ConvertPolicy,
1859        peak: PeakSource,
1860    ) -> Result<(), At<ConvertError>> {
1861        ImagePlan::convert_into_with_peak(self, dst, policy, peak)
1862    }
1863
1864    /// Convert `self` to full-range sRGB `RGB8`, refusing unproven alpha discard
1865    /// (`AlphaPolicy::DiscardIfOpaque`).
1866    ///
1867    /// The alpha-discard decision trusts the source format and attached facts.
1868    /// To prove opacity from the bytes of an owned buffer, use
1869    /// [`PixelBuf::into_opaque_verified`] before conversion.
1870    #[doc(alias = "to_rgb8")]
1871    #[inline]
1872    fn to_rgb8_if_opaque(&self) -> Result<PixelBuf, At<ConvertError>> {
1873        ImagePlan::to_rgb8_if_opaque(self)
1874    }
1875
1876    /// Convert `self` to full-range sRGB straight-alpha `RGBA8` under [`ConvertPolicy::permissive`].
1877    #[inline]
1878    fn to_rgba8(&self) -> Result<PixelBuf, At<ConvertError>> {
1879        ImagePlan::to_rgba8(self)
1880    }
1881
1882    /// Convert `self` to full-range sRGB `GRAY8`, refusing unproven alpha discard
1883    /// (`AlphaPolicy::DiscardIfOpaque`).
1884    ///
1885    /// The alpha-discard decision trusts the source format and attached facts.
1886    /// To prove opacity from the bytes of an owned buffer, use
1887    /// [`PixelBuf::into_opaque_verified`] before conversion.
1888    #[doc(alias = "to_gray8")]
1889    #[inline]
1890    fn to_gray8_if_opaque(&self) -> Result<PixelBuf, At<ConvertError>> {
1891        ImagePlan::to_gray8_if_opaque(self)
1892    }
1893
1894    /// Convert `self` to full-range sRGB straight-alpha `BGRA8` under [`ConvertPolicy::permissive`].
1895    #[inline]
1896    fn to_bgra8(&self) -> Result<PixelBuf, At<ConvertError>> {
1897        ImagePlan::to_bgra8(self)
1898    }
1899}
1900
1901impl<S: PixelSource + ?Sized> PixelConvertExt for S {}
1902
1903// ---------------------------------------------------------------------------
1904// Internal validation, preflight, and planning helpers
1905// ---------------------------------------------------------------------------
1906
1907/// Shared policy & feasibility preflight invoked BEFORE CMS, ByteFastPath, FastRow, or Strip.
1908pub(crate) fn preflight_and_classify(
1909    src: &PixelFormat,
1910    dst: &PixelFormat,
1911    policy: &ConvertPolicy,
1912) -> Result<PreflightOutcome, At<ConvertError>> {
1913    if src == dst {
1914        let needs_opaque_canon = src.color().alpha() == AlphaMode::Opaque
1915            && src.layout().order().has_alpha_slot()
1916            && !policy.source_claims.all_opaque;
1917        if needs_opaque_canon && !strip::can_fill_opaque_alpha(src.layout()) {
1918            return Err(err_at(ConvertError::UnsupportedRoute));
1919        }
1920        return Ok(PreflightOutcome {
1921            matte_color: None,
1922            range_change: false,
1923            uses_cms: false,
1924            is_identity: !needs_opaque_canon,
1925            drops_alpha: false,
1926            alpha_proven_opaque: true,
1927            drops_chroma: false,
1928            chroma_proven_gray: true,
1929            gamut_narrows: false,
1930            is_hdr_to_sdr: false,
1931            depth_reduces: false,
1932        });
1933    }
1934
1935    let raw_uses_cms = matches!(
1936        (&src.color(), &dst.color()),
1937        (ColorSpace::Icc { .. } | ColorSpace::Cmyk { .. }, _)
1938            | (_, ColorSpace::Icc { .. } | ColorSpace::Cmyk { .. })
1939    );
1940
1941    if matches!(
1942        (&src.color(), &dst.color()),
1943        (ColorSpace::Untagged { .. }, _) | (_, ColorSpace::Untagged { .. })
1944    ) {
1945        return Err(err_at(ConvertError::UnsupportedRoute));
1946    }
1947
1948    let src_has_meaningful_alpha = matches!(
1949        src.color().alpha(),
1950        AlphaMode::Straight | AlphaMode::Premultiplied
1951    );
1952    let dst_drops_alpha = matches!(
1953        dst.color().alpha(),
1954        AlphaMode::None | AlphaMode::Undefined | AlphaMode::Opaque
1955    );
1956    let drops_alpha = src_has_meaningful_alpha && dst_drops_alpha;
1957    let alpha_proven_opaque = !drops_alpha || policy.source_claims.all_opaque;
1958    let matte_color = if drops_alpha {
1959        match policy.alpha {
1960            AlphaPolicy::Forbid => return Err(err_at(ConvertError::AlphaLossForbidden)),
1961            AlphaPolicy::DiscardIfOpaque => {
1962                if policy.source_claims.all_opaque {
1963                    None
1964                } else {
1965                    return Err(err_at(ConvertError::AlphaLossForbidden));
1966                }
1967            }
1968            AlphaPolicy::DiscardUnchecked => None,
1969            AlphaPolicy::CompositeOnto(c) => Some(c),
1970        }
1971    } else {
1972        None
1973    };
1974
1975    let src_proven_opaque = is_src_proven_opaque(src, policy.source_claims);
1976    let byte_fast_path_available = strip::detect_byte_fast_path(
1977        src,
1978        dst,
1979        policy.depth,
1980        policy.luma,
1981        policy.luma_domain,
1982        matte_color.is_some(),
1983        policy.source_claims.all_opaque,
1984    )
1985    .is_some();
1986
1987    // Same-profile ICC/CMYK layout, widening, opaque alpha fill, and identity copy bypass CMS (D01).
1988    let uses_cms = raw_uses_cms && !byte_fast_path_available;
1989
1990    if !uses_cms && !byte_fast_path_available {
1991        if !src.layout().sample().is_standard_color() && !src.layout().packing().is_packed_word() {
1992            return Err(err_at(ConvertError::UnsupportedRoute));
1993        }
1994        if !dst.layout().sample().is_standard_color() && !dst.layout().packing().is_packed_word() {
1995            return Err(err_at(ConvertError::UnsupportedRoute));
1996        }
1997    }
1998
1999    // Policy checks apply UNIFORMLY to native AND CMS routes!
2000    let reassociates_alpha = matches!(
2001        (src.color().alpha(), dst.color().alpha()),
2002        (AlphaMode::Straight, AlphaMode::Premultiplied)
2003            | (AlphaMode::Premultiplied, AlphaMode::Straight)
2004    );
2005    let lossy_reassociation = reassociates_alpha && !src_proven_opaque;
2006
2007    let cross_profile_cms = uses_cms
2008        && (try_substitute_icc(src, policy).is_none() || try_substitute_icc(dst, policy).is_none())
2009        && !same_color_meaning(src.color(), dst.color());
2010
2011    let range_change = check_range_policy(src, dst, policy)?;
2012
2013    let depth_reduces = is_depth_reducing(src, dst, policy.source_claims)
2014        || lossy_reassociation
2015        || (cross_profile_cms && !dst.layout().sample().is_float());
2016    if depth_reduces && policy.depth == DepthPolicy::Forbid {
2017        return Err(err_at(ConvertError::DepthReductionForbidden));
2018    }
2019
2020    let drops_chroma = !matches!(src.color(), ColorSpace::Gray { .. })
2021        && matches!(dst.color(), ColorSpace::Gray { .. });
2022    let chroma_proven_gray = !drops_chroma || policy.source_claims.all_grayscale;
2023    if drops_chroma
2024        && !chroma_proven_gray
2025        && (policy.depth == DepthPolicy::Forbid || policy.gamut == GamutPolicy::Forbid)
2026    {
2027        return Err(err_at(ConvertError::GamutLossForbidden));
2028    }
2029
2030    let src_tf = color_transfer(src.color());
2031    let dst_tf = color_transfer(dst.color());
2032    let is_hdr_to_sdr = src_tf.is_hdr()
2033        && !dst_tf.is_hdr()
2034        && matches!(
2035            dst.color(),
2036            ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. }
2037        );
2038
2039    let gamut_narrows =
2040        is_gamut_narrowing(color_primaries(src.color()), color_primaries(dst.color()))
2041            || cross_profile_cms;
2042    let unproven_float_to_int = src.layout().sample().is_float()
2043        && !dst.layout().sample().is_float()
2044        && !policy.source_claims.float.is_unit_interval();
2045    if policy.gamut == GamutPolicy::Forbid
2046        && (gamut_narrows
2047            || (is_hdr_to_sdr && !dst.layout().sample().is_float())
2048            || unproven_float_to_int)
2049    {
2050        return Err(err_at(ConvertError::GamutLossForbidden));
2051    }
2052    // Bounded integer destinations cannot preserve out-of-gamut / extended values:
2053    // forbid silent clipping under `lossless()` (`PreserveExtended` + `DepthPolicy::Forbid`).
2054    if policy.gamut == GamutPolicy::PreserveExtended
2055        && policy.depth == DepthPolicy::Forbid
2056        && !dst.layout().sample().is_float()
2057        && (gamut_narrows || is_hdr_to_sdr)
2058    {
2059        return Err(err_at(ConvertError::GamutLossForbidden));
2060    }
2061
2062    // If CMS will be used (no byte fast path and no substitution), verify CMS is configured and supports requested policy.
2063    if uses_cms
2064        && !byte_fast_path_available
2065        && (try_substitute_icc(src, policy).is_none() || try_substitute_icc(dst, policy).is_none())
2066    {
2067        if policy.cms.is_none() {
2068            return Err(err_at(ConvertError::CmsRequired));
2069        }
2070        if matte_color.is_some()
2071            || src.color().alpha() == AlphaMode::Premultiplied
2072            || dst.color().alpha() == AlphaMode::Premultiplied
2073            || policy.depth == DepthPolicy::OrderedDither
2074            || policy.gamut == GamutPolicy::SoftCompress
2075        {
2076            return Err(err_at(ConvertError::UnsupportedRoute));
2077        }
2078    }
2079
2080    Ok(PreflightOutcome {
2081        matte_color,
2082        range_change,
2083        uses_cms,
2084        is_identity: false,
2085        drops_alpha,
2086        alpha_proven_opaque,
2087        drops_chroma,
2088        chroma_proven_gray,
2089        gamut_narrows,
2090        is_hdr_to_sdr,
2091        depth_reduces,
2092    })
2093}
2094
2095pub(crate) fn same_color_meaning(a: &ColorSpace, b: &ColorSpace) -> bool {
2096    match (a, b) {
2097        (
2098            ColorSpace::Rgb {
2099                transfer: ta,
2100                range: ra,
2101                diffuse_white: wa,
2102                ..
2103            }
2104            | ColorSpace::RgbCustom {
2105                transfer: ta,
2106                range: ra,
2107                diffuse_white: wa,
2108                ..
2109            },
2110            ColorSpace::Rgb {
2111                transfer: tb,
2112                range: rb,
2113                diffuse_white: wb,
2114                ..
2115            }
2116            | ColorSpace::RgbCustom {
2117                transfer: tb,
2118                range: rb,
2119                diffuse_white: wb,
2120                ..
2121            },
2122        ) => a.same_rgb_chromaticity(b) && ta.same_curve(*tb) && ra == rb && wa == wb,
2123        (
2124            ColorSpace::Gray {
2125                transfer: ta,
2126                range: ra,
2127                diffuse_white: wa,
2128                ..
2129            },
2130            ColorSpace::Gray {
2131                transfer: tb,
2132                range: rb,
2133                diffuse_white: wb,
2134                ..
2135            },
2136        ) => ta.same_curve(*tb) && ra == rb && wa == wb,
2137        (
2138            ColorSpace::Xyz {
2139                white_point: wa,
2140                diffuse_white: wwa,
2141                ..
2142            },
2143            ColorSpace::Xyz {
2144                white_point: wb,
2145                diffuse_white: wwb,
2146                ..
2147            },
2148        ) => wa == wb && wwa == wwb,
2149        (ColorSpace::Oklab { .. }, ColorSpace::Oklab { .. }) => true,
2150        (ColorSpace::Perceptual { space: sa, .. }, ColorSpace::Perceptual { space: sb, .. }) => {
2151            sa == sb
2152        }
2153        (
2154            ColorSpace::Cmyk {
2155                icc: ia,
2156                inverted: inva,
2157                ..
2158            },
2159            ColorSpace::Cmyk {
2160                icc: ib,
2161                inverted: invb,
2162                ..
2163            },
2164        ) => {
2165            inva == invb
2166                && match (ia, ib) {
2167                    (Some(x), Some(y)) => zenpixels::icc::normalized_eq(x, y),
2168                    (None, None) => true,
2169                    _ => false,
2170                }
2171        }
2172        (
2173            ColorSpace::Icc {
2174                profile: pa,
2175                color_channels: ca,
2176                intent: ia,
2177                ..
2178            },
2179            ColorSpace::Icc {
2180                profile: pb,
2181                color_channels: cb,
2182                intent: ib,
2183                ..
2184            },
2185        ) => ca == cb && ia == ib && zenpixels::icc::normalized_eq(pa, pb),
2186        (
2187            ColorSpace::Untagged {
2188                total_channels: ca, ..
2189            },
2190            ColorSpace::Untagged {
2191                total_channels: cb, ..
2192            },
2193        ) => ca == cb,
2194        _ => false,
2195    }
2196}
2197
2198pub(crate) fn same_photometry(a: &ColorSpace, b: &ColorSpace) -> bool {
2199    match (a, b) {
2200        (
2201            ColorSpace::Rgb {
2202                transfer: ta,
2203                diffuse_white: wa,
2204                ..
2205            }
2206            | ColorSpace::RgbCustom {
2207                transfer: ta,
2208                diffuse_white: wa,
2209                ..
2210            },
2211            ColorSpace::Rgb {
2212                transfer: tb,
2213                diffuse_white: wb,
2214                ..
2215            }
2216            | ColorSpace::RgbCustom {
2217                transfer: tb,
2218                diffuse_white: wb,
2219                ..
2220            },
2221        ) => a.same_rgb_chromaticity(b) && ta.same_curve(*tb) && wa == wb,
2222        (
2223            ColorSpace::Gray {
2224                transfer: ta,
2225                diffuse_white: wa,
2226                ..
2227            },
2228            ColorSpace::Gray {
2229                transfer: tb,
2230                diffuse_white: wb,
2231                ..
2232            },
2233        ) => ta.same_curve(*tb) && wa == wb,
2234        _ => same_color_meaning(a, b),
2235    }
2236}
2237
2238fn is_src_proven_opaque(src: &PixelFormat, facts: SampleClaims) -> bool {
2239    matches!(
2240        src.color().alpha(),
2241        AlphaMode::None | AlphaMode::Undefined | AlphaMode::Opaque
2242    ) || !src.layout().order().has_alpha_slot()
2243        || facts.all_opaque
2244}
2245
2246pub(crate) fn is_scene_linear_hdr_candidate(src: &PixelFormat, dst: &PixelFormat) -> bool {
2247    matches!(color_transfer(src.color()), Transfer::Linear)
2248        && src.layout().sample().is_float()
2249        && !dst.can_represent_hdr()
2250        && matches!(
2251            dst.color(),
2252            ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. }
2253        )
2254}
2255
2256fn linear_sdr_ceiling_nits(src: &PixelFormat, dst: &PixelFormat, policy: &ConvertPolicy) -> f32 {
2257    src.color()
2258        .diffuse_white()
2259        .or_else(|| dst.color().diffuse_white())
2260        .or(policy.diffuse_white)
2261        .unwrap_or(DiffuseWhite::BT2408)
2262        .nits()
2263}
2264
2265pub(crate) fn merge_facts(policy_facts: SampleClaims, buf_facts: SampleClaims) -> SampleClaims {
2266    let depth = match (policy_facts.depth, buf_facts.depth) {
2267        (Some(a), Some(b)) => ExactDepth::intersect_same_buffer(a, b).or(Some(a)),
2268        (Some(a), None) => Some(a),
2269        (None, Some(b)) => Some(b),
2270        (None, None) => None,
2271    };
2272    let all_opaque = policy_facts.all_opaque || buf_facts.all_opaque;
2273    SampleClaims::NONE
2274        .with_float(policy_facts.float | buf_facts.float)
2275        .with_depth(depth)
2276        .with_all_opaque(all_opaque)
2277        .with_all_grayscale(policy_facts.all_grayscale || buf_facts.all_grayscale)
2278        .with_binary_alpha(all_opaque || policy_facts.binary_alpha || buf_facts.binary_alpha)
2279}
2280
2281pub(crate) fn try_substitute_icc(
2282    spec: &PixelFormat,
2283    policy: &ConvertPolicy,
2284) -> Option<PixelFormat> {
2285    if !policy.allow_icc_substitution {
2286        return None;
2287    }
2288    match &spec.color() {
2289        ColorSpace::Cmyk { .. } => None,
2290        ColorSpace::Icc {
2291            profile,
2292            color_channels,
2293            alpha,
2294            intent,
2295        } => {
2296            // Check ICC header color-space signature matches carrier channel count.
2297            let sig = zenpixels::IccColorSpace::from_icc(profile)?;
2298            if (*color_channels == 1 && sig != zenpixels::IccColorSpace::Gray)
2299                || (*color_channels == 3 && sig != zenpixels::IccColorSpace::Rgb)
2300            {
2301                return None;
2302            }
2303            // Intent-aware lookup: refuses AbsoluteColorimetric and honors per-intent safety mask.
2304            // When a CMS backend is configured, require StrictTrc (±1 u16) tolerance so approximate
2305            // LUT profiles use the real CMS instead of silently bypassing it.
2306            let tolerance = if policy.cms.is_some() {
2307                zenpixels::icc::IccMatchTolerance::StrictTrc
2308            } else {
2309                zenpixels::icc::IccMatchTolerance::RelaxedTrc
2310            };
2311            let id = zenpixels::icc::IccIdentification::from_icc_for_intent(
2312                profile, *intent, tolerance,
2313            )?;
2314            let color = if *color_channels == 1 {
2315                ColorSpace::Gray {
2316                    transfer: id.transfer(),
2317                    range: SignalRange::Full,
2318                    alpha: *alpha,
2319                    diffuse_white: None,
2320                }
2321            } else if *color_channels == 3 {
2322                ColorSpace::Rgb {
2323                    primaries: id.primaries(),
2324                    transfer: id.transfer(),
2325                    range: SignalRange::Full,
2326                    alpha: *alpha,
2327                    diffuse_white: None,
2328                }
2329            } else {
2330                return None;
2331            };
2332            PixelFormat::new(spec.layout(), color).ok()
2333        }
2334        _ => Some(spec.clone()),
2335    }
2336}
2337
2338fn effective_color_bits(spec: &PixelFormat) -> u8 {
2339    if !spec.layout().packing().is_full() {
2340        let mc = spec.layout().packing().max_code(spec.layout().sample(), 0);
2341        return (32 - mc.leading_zeros()) as u8;
2342    }
2343    spec.layout().sample().bits()
2344}
2345
2346fn raw_channel_bits(spec: &PixelFormat, channel: usize) -> u8 {
2347    if !spec.layout().packing().is_full() {
2348        let mc = spec
2349            .layout()
2350            .packing()
2351            .max_code(spec.layout().sample(), channel);
2352        return (32 - mc.leading_zeros()) as u8;
2353    }
2354    match spec.layout().sample() {
2355        SampleType::U8 | SampleType::I8 => 8,
2356        SampleType::U16 | SampleType::I16 => 16,
2357        SampleType::F16 => 11, // IEEE binary16 significand precision (11 bits)
2358        SampleType::F32 => 24, // IEEE binary32 significand precision (24 bits)
2359        SampleType::U32 | SampleType::I32 => 32,
2360        SampleType::F64 => 53,
2361        SampleType::U64 | SampleType::I64 => 64,
2362        _ => 32,
2363    }
2364}
2365
2366fn min_color_bits(spec: &PixelFormat) -> u8 {
2367    let ch = spec.layout().channels();
2368    let color_ch = ch.saturating_sub(usize::from(
2369        spec.layout().order().has_alpha_slot() || spec.layout().order().has_padding_slot(),
2370    ));
2371    let mut min_b = u8::MAX;
2372    for c in 0..color_ch {
2373        min_b = min_b.min(raw_channel_bits(spec, c));
2374    }
2375    if min_b == u8::MAX { 8 } else { min_b }
2376}
2377
2378/// Per-channel lossless precision and exact code-grid inclusion check (B01 & B02).
2379///
2380/// - Float → integer always reduces precision.
2381/// - Non-identity transfer, gamut matrix, cross-model, range, or diffuse-white changes
2382///   into a bounded integer destination are non-injective / precision-reducing (B01).
2383/// - Integer → integer checks exact grid inclusion per channel (`full_range_grid_nests`
2384///   where `dst_bits % src_bits == 0`, or `narrow_range_grid_nests` where `dst >= src >= 8`)
2385///   and checks color and alpha grids independently, consulting validated [`ExactDepth`]
2386///   evidence when the nominal grid does not nest (B02).
2387fn is_depth_reducing(src: &PixelFormat, dst: &PixelFormat, facts: SampleClaims) -> bool {
2388    let src_is_float = src.layout().sample().is_float();
2389    let dst_is_float = dst.layout().sample().is_float();
2390
2391    // Floating-point -> integer is always precision-reducing (loses extended range & sub-LSB precision).
2392    if src_is_float && !dst_is_float {
2393        return true;
2394    }
2395
2396    let valid_depth = facts.depth.filter(|d| d.validate_format(src).is_ok());
2397
2398    // B01: Any non-identity color math (transfer, gamut matrix, color model, signal range,
2399    // or diffuse-white rescale) into an integer destination is non-injective / precision-reducing.
2400    if !dst_is_float {
2401        let src_tf = color_transfer(src.color());
2402        let dst_tf = color_transfer(dst.color());
2403        let transfer_changes = !src_tf.same_curve(dst_tf);
2404        let gamut_changes = src.color().is_rgb()
2405            && dst.color().is_rgb()
2406            && !color_primaries(src.color()).same_chromaticity(color_primaries(dst.color()));
2407        let model_changes_lossy = (matches!(
2408            src.color(),
2409            ColorSpace::Xyz { .. } | ColorSpace::Oklab { .. } | ColorSpace::Perceptual { .. }
2410        ) || matches!(
2411            dst.color(),
2412            ColorSpace::Xyz { .. } | ColorSpace::Oklab { .. } | ColorSpace::Perceptual { .. }
2413        )) && !same_color_meaning(src.color(), dst.color());
2414        let range_changes = color_range(src.color()) != color_range(dst.color());
2415        let white_changes = match (src.color().diffuse_white(), dst.color().diffuse_white()) {
2416            (Some(a), Some(b)) => ((a.nits() / b.nits()) - 1.0).abs() > 1e-6,
2417            _ => false,
2418        };
2419        if transfer_changes
2420            || gamut_changes
2421            || model_changes_lossy
2422            || range_changes
2423            || white_changes
2424        {
2425            return true;
2426        }
2427    }
2428
2429    let src_ch = src.layout().channels();
2430    let dst_ch = dst.layout().channels();
2431    let src_has_alpha = src.layout().order().has_alpha_slot();
2432    let dst_has_alpha = dst.layout().order().has_alpha_slot();
2433    let src_color_ch = src_ch.saturating_sub(usize::from(
2434        src_has_alpha || src.layout().order().has_padding_slot(),
2435    ));
2436    let dst_color_ch = dst_ch.saturating_sub(usize::from(
2437        dst_has_alpha || dst.layout().order().has_padding_slot(),
2438    ));
2439
2440    if !src_is_float && !dst_is_float {
2441        let range = color_range(src.color());
2442        // Check every color channel pair for exact code-grid inclusion (B02).
2443        for sc in 0..src_color_ch {
2444            let s_bits = raw_channel_bits(src, sc);
2445            for dc in 0..dst_color_ch {
2446                let d_bits = raw_channel_bits(dst, dc);
2447                let nests = match range {
2448                    SignalRange::Full => full_range_grid_nests(s_bits, d_bits),
2449                    SignalRange::Narrow => narrow_range_grid_nests(s_bits, d_bits),
2450                    _ => false,
2451                };
2452                if !nests {
2453                    let proven = valid_depth.is_some_and(|d| d.color_exact_at(d_bits));
2454                    if !proven {
2455                        return true;
2456                    }
2457                }
2458            }
2459        }
2460        // Check alpha channel independently (always full scale).
2461        if src_has_alpha
2462            && dst_has_alpha
2463            && matches!(
2464                src.color().alpha(),
2465                AlphaMode::Straight | AlphaMode::Premultiplied
2466            )
2467            && matches!(
2468                dst.color().alpha(),
2469                AlphaMode::Straight | AlphaMode::Premultiplied
2470            )
2471        {
2472            let sa_bits = raw_channel_bits(src, src_ch - 1);
2473            let da_bits = raw_channel_bits(dst, dst_ch - 1);
2474            if !full_range_grid_nests(sa_bits, da_bits) {
2475                let proven = valid_depth.is_some_and(|d| d.alpha_exact_at(da_bits));
2476                if !proven {
2477                    return true;
2478                }
2479            }
2480        }
2481        return false;
2482    }
2483
2484    // Float destination (`int -> float` or `float -> float`): compare against float significand bits.
2485    let dst_sig_bits = raw_channel_bits(dst, 0);
2486    let mut src_max_color_bits = 0u8;
2487    for c in 0..src_color_ch {
2488        src_max_color_bits = src_max_color_bits.max(raw_channel_bits(src, c));
2489    }
2490    let eff_color_bits = valid_depth.map_or(src_max_color_bits, |d| d.color_bits());
2491    if dst_sig_bits < eff_color_bits {
2492        return true;
2493    }
2494
2495    if src_has_alpha
2496        && dst_has_alpha
2497        && matches!(
2498            src.color().alpha(),
2499            AlphaMode::Straight | AlphaMode::Premultiplied
2500        )
2501        && matches!(
2502            dst.color().alpha(),
2503            AlphaMode::Straight | AlphaMode::Premultiplied
2504        )
2505    {
2506        let sa_bits = raw_channel_bits(src, src_ch - 1);
2507        let eff_alpha_bits = valid_depth.map_or(sa_bits, |d| d.alpha_bits());
2508        if dst_sig_bits < eff_alpha_bits {
2509            return true;
2510        }
2511    }
2512
2513    false
2514}
2515
2516fn check_range_policy(
2517    src: &PixelFormat,
2518    dst: &PixelFormat,
2519    policy: &ConvertPolicy,
2520) -> Result<bool, At<ConvertError>> {
2521    let sr = color_range(src.color());
2522    let dr = color_range(dst.color());
2523    if sr != dr {
2524        if policy.range == RangePolicy::Forbid {
2525            return Err(err_at(ConvertError::RangeConversionForbidden));
2526        }
2527        return Ok(true);
2528    }
2529    Ok(false)
2530}
2531
2532#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2533pub(crate) enum RgbPrimaries {
2534    Standard(Primaries),
2535    Custom(zenpixels::CustomPrimaries),
2536}
2537
2538impl RgbPrimaries {
2539    pub(crate) const UNKNOWN: Self = Self::Standard(Primaries::Unknown);
2540    pub(crate) const BT709: Self = Self::Standard(Primaries::Bt709);
2541
2542    #[inline]
2543    pub(crate) const fn is_unknown(self) -> bool {
2544        matches!(self, Self::Standard(Primaries::Unknown))
2545    }
2546
2547    #[inline]
2548    pub(crate) const fn as_standard(self) -> Option<Primaries> {
2549        match self {
2550            Self::Standard(p) => Some(p),
2551            Self::Custom(_) => None,
2552        }
2553    }
2554
2555    #[inline]
2556    pub(crate) const fn to_custom(self) -> Option<zenpixels::CustomPrimaries> {
2557        match self {
2558            Self::Standard(p) => p.to_custom(),
2559            Self::Custom(cp) => Some(cp),
2560        }
2561    }
2562
2563    #[inline]
2564    pub(crate) const fn same_chromaticity(self, other: Self) -> bool {
2565        match (self, other) {
2566            (Self::Standard(a), Self::Standard(b)) => a.same_chromaticity(b),
2567            (Self::Custom(a), Self::Custom(b)) => a.same_chromaticity(b),
2568            _ => match (self.to_custom(), other.to_custom()) {
2569                (Some(a), Some(b)) => a.same_chromaticity(b),
2570                _ => false,
2571            },
2572        }
2573    }
2574
2575    #[inline]
2576    pub(crate) const fn gamut_matrix_to(self, dst: Self) -> Option<[[f32; 3]; 3]> {
2577        match (self, dst) {
2578            (Self::Standard(a), Self::Standard(b)) => a.gamut_matrix_to(b),
2579            _ => match (self.to_custom(), dst.to_custom()) {
2580                (Some(a), Some(b)) => a.gamut_matrix_to(b),
2581                _ => None,
2582            },
2583        }
2584    }
2585
2586    #[inline]
2587    pub(crate) const fn xyz_to_rgb_f32(
2588        self,
2589        src_white: zenpixels::WhitePoint,
2590    ) -> Option<[[f32; 3]; 3]> {
2591        match self {
2592            Self::Standard(p) => p.xyz_to_rgb_f32(src_white),
2593            Self::Custom(cp) => cp.xyz_to_rgb_f32(src_white),
2594        }
2595    }
2596
2597    #[inline]
2598    pub(crate) const fn rgb_to_xyz_f32(
2599        self,
2600        dst_white: zenpixels::WhitePoint,
2601    ) -> Option<[[f32; 3]; 3]> {
2602        match self {
2603            Self::Standard(p) => p.rgb_to_xyz_f32(dst_white),
2604            Self::Custom(cp) => cp.rgb_to_xyz_f32(dst_white),
2605        }
2606    }
2607
2608    #[inline]
2609    pub(crate) const fn try_luma_weights(self) -> Option<[f32; 3]> {
2610        match self {
2611            Self::Standard(p) => p.try_luma_weights(),
2612            Self::Custom(cp) => cp.try_luma_weights(),
2613        }
2614    }
2615
2616    #[cfg(feature = "gainmap")]
2617    #[inline]
2618    pub(crate) const fn luma_weights(self) -> [f32; 3] {
2619        match self {
2620            Self::Standard(p) => p.luma_weights(),
2621            Self::Custom(cp) => cp.luma_weights(),
2622        }
2623    }
2624
2625    #[cfg(feature = "oklab")]
2626    #[inline]
2627    pub(crate) fn oklab_space(self) -> Option<crate::oklab::OklabSpace> {
2628        match self {
2629            Self::Standard(p) => crate::oklab::OklabSpace::for_primaries(p),
2630            Self::Custom(cp) => crate::oklab::OklabSpace::for_custom_primaries(cp),
2631        }
2632    }
2633
2634    #[cfg(feature = "gainmap")]
2635    #[inline]
2636    pub(crate) fn to_color_space(
2637        self,
2638        transfer: Transfer,
2639        range: SignalRange,
2640        alpha: AlphaMode,
2641        white: Option<DiffuseWhite>,
2642    ) -> ColorSpace {
2643        match self {
2644            Self::Standard(primaries) => ColorSpace::Rgb {
2645                primaries,
2646                transfer,
2647                range,
2648                alpha,
2649                diffuse_white: white,
2650            },
2651            Self::Custom(primaries) => {
2652                ColorSpace::rgb_custom(primaries, transfer, range, alpha, white)
2653            }
2654        }
2655    }
2656}
2657
2658pub(crate) fn color_range(cs: &ColorSpace) -> SignalRange {
2659    match *cs {
2660        ColorSpace::Rgb { range, .. }
2661        | ColorSpace::RgbCustom { range, .. }
2662        | ColorSpace::Gray { range, .. } => range,
2663        _ => SignalRange::Full,
2664    }
2665}
2666
2667pub(crate) fn color_transfer(cs: &ColorSpace) -> Transfer {
2668    match *cs {
2669        ColorSpace::Rgb { transfer, .. }
2670        | ColorSpace::RgbCustom { transfer, .. }
2671        | ColorSpace::Gray { transfer, .. } => transfer,
2672        _ => Transfer::Linear,
2673    }
2674}
2675
2676pub(crate) fn color_primaries(cs: &ColorSpace) -> RgbPrimaries {
2677    match cs {
2678        ColorSpace::Rgb { primaries, .. } => RgbPrimaries::Standard(*primaries),
2679        ColorSpace::RgbCustom { primaries, .. } => RgbPrimaries::Custom(**primaries),
2680        ColorSpace::Gray { .. } => RgbPrimaries::BT709,
2681        _ => RgbPrimaries::UNKNOWN,
2682    }
2683}
2684
2685fn needs_linear_domain(
2686    src: &ColorSpace,
2687    dst: &ColorSpace,
2688    matte_active: bool,
2689    white_rescale: bool,
2690    policy: &ConvertPolicy,
2691) -> bool {
2692    if matte_active || white_rescale {
2693        return true;
2694    }
2695    if matches!(
2696        src,
2697        ColorSpace::Oklab { .. } | ColorSpace::Perceptual { .. } | ColorSpace::Xyz { .. }
2698    ) || matches!(
2699        dst,
2700        ColorSpace::Oklab { .. } | ColorSpace::Perceptual { .. } | ColorSpace::Xyz { .. }
2701    ) {
2702        return true;
2703    }
2704    let st = color_transfer(src);
2705    let dt = color_transfer(dst);
2706    if !st.same_curve(dt) {
2707        return true;
2708    }
2709    if src.is_rgb() && dst.is_rgb() && !color_primaries(src).same_chromaticity(color_primaries(dst))
2710    {
2711        return true;
2712    }
2713    if src.is_rgb()
2714        && matches!(dst, ColorSpace::Gray { .. })
2715        && policy.luma_domain == LumaDomain::LinearLight
2716    {
2717        return true;
2718    }
2719    if policy.gamut == GamutPolicy::SoftCompress {
2720        return true;
2721    }
2722    false
2723}
2724
2725fn resolve_hlg(
2726    cs: &ColorSpace,
2727    tf: Transfer,
2728    other_tf: Transfer,
2729    override_rendering: Option<HlgRendering>,
2730    inverse: bool,
2731    white_nits: f32,
2732    clip: bool,
2733) -> Result<(Transfer, Option<PreparedHlg>), At<ConvertError>> {
2734    match tf {
2735        Transfer::Hlg(HlgMode::Display(r)) => {
2736            #[cfg(feature = "hdr-transfers")]
2737            {
2738                Ok((
2739                    Transfer::Hlg(HlgMode::Display(r)),
2740                    Some(PreparedHlg::new(r, inverse, white_nits, clip)),
2741                ))
2742            }
2743            #[cfg(not(feature = "hdr-transfers"))]
2744            {
2745                let _ = (r, inverse, white_nits, clip);
2746                Err(err_at(ConvertError::HdrFeatureRequired))
2747            }
2748        }
2749        Transfer::Hlg(HlgMode::Scene) => {
2750            if matches!(other_tf, Transfer::Hlg(HlgMode::Scene)) {
2751                return Ok((Transfer::Hlg(HlgMode::Scene), None));
2752            }
2753            if let Some(r) = override_rendering {
2754                // Display HLG OOTF is defined over BT.2020 full-range RGB only.
2755                let is_bt2020_rgb_full = matches!(
2756                    cs,
2757                    ColorSpace::Rgb {
2758                        primaries: Primaries::Bt2020,
2759                        range: SignalRange::Full,
2760                        ..
2761                    }
2762                );
2763                if !is_bt2020_rgb_full {
2764                    return Err(err_at(ConvertError::InvalidFormat(
2765                        zenpixels::ColorError::HlgDisplayRequiresBt2020Full,
2766                    )));
2767                }
2768                #[cfg(feature = "hdr-transfers")]
2769                {
2770                    Ok((
2771                        Transfer::Hlg(HlgMode::Display(r)),
2772                        Some(PreparedHlg::new(r, inverse, white_nits, clip)),
2773                    ))
2774                }
2775                #[cfg(not(feature = "hdr-transfers"))]
2776                {
2777                    let _ = (r, inverse, white_nits, clip);
2778                    Err(err_at(ConvertError::HdrFeatureRequired))
2779                }
2780            } else {
2781                Err(err_at(ConvertError::HlgRenderingRequired))
2782            }
2783        }
2784        other => Ok((other, None)),
2785    }
2786}
2787
2788pub(crate) fn resolve_tone_mapper(
2789    policy: &ConvertPolicy,
2790) -> Result<Arc<dyn crate::tonemap::ToneMapper>, At<ConvertError>> {
2791    if let Some(m) = &policy.tone_mapper {
2792        return Ok(Arc::clone(m));
2793    }
2794    #[cfg(feature = "bt2446a")]
2795    {
2796        Ok(Arc::new(crate::tonemap::Bt2446A::pipeline_managed()))
2797    }
2798    #[cfg(not(feature = "bt2446a"))]
2799    {
2800        Err(err_at(ConvertError::FeatureRequired("bt2446a")))
2801    }
2802}
2803
2804pub(crate) fn is_gamut_narrowing(src: RgbPrimaries, dst: RgbPrimaries) -> bool {
2805    if src.same_chromaticity(dst) || src.is_unknown() || dst.is_unknown() {
2806        return false;
2807    }
2808    // Exact geometric test over convex RGB cones: source primaries lie inside destination
2809    // gamut iff every entry of the 3x3 linear transform matrix is non-negative.
2810    match src.gamut_matrix_to(dst) {
2811        Some(m) => m.iter().flatten().any(|&v| v < -1e-5),
2812        None => false,
2813    }
2814}
2815
2816fn derive_output_facts_byte(
2817    src: &PixelFormat,
2818    dst: &PixelFormat,
2819    src_facts: SampleClaims,
2820    bp: ByteFastPath,
2821) -> SampleClaims {
2822    let float = if dst.layout().sample().is_float() {
2823        src_facts.float
2824    } else {
2825        FloatClaims::NONE
2826    };
2827    let dst_range = color_range(dst.color());
2828    let valid_src_depth = src_facts.depth.filter(|d| d.validate_format(src).is_ok());
2829    let fills_alpha = matches!(
2830        bp,
2831        ByteFastPath::Rgb8ToRgba8
2832            | ByteFastPath::Rgb8ToBgra8
2833            | ByteFastPath::FillAlpha4U8
2834            | ByteFastPath::SwapRbFillAlpha4U8
2835            | ByteFastPath::Gray8ToRgba8
2836            | ByteFastPath::AddAlpha3To4B2(_)
2837            | ByteFastPath::SwapAddAlpha3To4B2(_)
2838            | ByteFastPath::GrayToRgbaB2(_)
2839            | ByteFastPath::AddAlpha3To4B4
2840            | ByteFastPath::SwapAddAlpha3To4B4
2841            | ByteFastPath::GrayToRgbaB4
2842            | ByteFastPath::FillAlpha4B2(_)
2843            | ByteFastPath::SwapRbFillAlpha4B2(_)
2844            | ByteFastPath::FillAlpha4B4
2845            | ByteFastPath::SwapRbFillAlpha4B4
2846            | ByteFastPath::FillAlpha2U8
2847            | ByteFastPath::FillAlpha2B2(_)
2848            | ByteFastPath::FillAlpha2B4
2849            | ByteFastPath::CopyFillOpaqueAlpha(_)
2850            | ByteFastPath::RepackIntSameDepth {
2851                fill_opaque_alpha: true,
2852                ..
2853            }
2854            | ByteFastPath::NarrowBitShift {
2855                fill_opaque_alpha: true,
2856                ..
2857            }
2858    );
2859    // Exhaustive allow-list: ONLY byte paths that move, broadcast, or exactly widen/repack
2860    // samples without modifying color code values may propagate source `ExactDepth::color_bits`.
2861    let preserves_color_values = match bp {
2862        ByteFastPath::Memcpy
2863        | ByteFastPath::Rgb8ToRgba8
2864        | ByteFastPath::Rgb8ToBgra8
2865        | ByteFastPath::Rgba8ToRgb8
2866        | ByteFastPath::Bgra8ToRgb8
2867        | ByteFastPath::SwapRb3U8
2868        | ByteFastPath::SwapRb4U8
2869        | ByteFastPath::FillAlpha4U8
2870        | ByteFastPath::SwapRbFillAlpha4U8
2871        | ByteFastPath::Gray8ToRgb8
2872        | ByteFastPath::Gray8ToRgba8
2873        | ByteFastPath::U8ToU16Exact
2874        | ByteFastPath::DropAlpha4To3B2
2875        | ByteFastPath::SwapDropAlpha4To3B2
2876        | ByteFastPath::AddAlpha3To4B2(_)
2877        | ByteFastPath::SwapAddAlpha3To4B2(_)
2878        | ByteFastPath::SwapRb3B2
2879        | ByteFastPath::SwapRb4B2
2880        | ByteFastPath::GrayToRgbB2
2881        | ByteFastPath::GrayToRgbaB2(_)
2882        | ByteFastPath::DropAlpha4To3B4
2883        | ByteFastPath::SwapDropAlpha4To3B4
2884        | ByteFastPath::AddAlpha3To4B4
2885        | ByteFastPath::SwapAddAlpha3To4B4
2886        | ByteFastPath::SwapRb3B4
2887        | ByteFastPath::SwapRb4B4
2888        | ByteFastPath::GrayToRgbB4
2889        | ByteFastPath::GrayToRgbaB4
2890        | ByteFastPath::FillAlpha4B2(_)
2891        | ByteFastPath::SwapRbFillAlpha4B2(_)
2892        | ByteFastPath::FillAlpha4B4
2893        | ByteFastPath::SwapRbFillAlpha4B4
2894        | ByteFastPath::FillAlpha2U8
2895        | ByteFastPath::FillAlpha2B2(_)
2896        | ByteFastPath::FillAlpha2B4
2897        | ByteFastPath::CopyFillOpaqueAlpha(_)
2898        | ByteFastPath::RepackIntSameDepth { .. }
2899        | ByteFastPath::NarrowBitShift { .. } => true,
2900        ByteFastPath::U16ToU8Round
2901        | ByteFastPath::U16ToU8Trunc
2902        | ByteFastPath::Rgba8StraightToPremul { .. }
2903        | ByteFastPath::Rgba8PremulToStraight
2904        | ByteFastPath::Rgb8ToGray8 { .. } => false,
2905    };
2906    let all_opaque = !dst.layout().order().has_alpha_slot()
2907        || fills_alpha
2908        || !src.layout().order().has_alpha_slot()
2909        || src_facts.all_opaque;
2910    let binary_alpha = all_opaque || src_facts.binary_alpha;
2911    // Full-range U8 -> U16 widening (`v * 257`) preserves an N-bit sub-grid ONLY when N divides 8
2912    // (`1, 2, 4, 8`): e.g. U8 3-bit code `36` widens to `9252 != round(65535/7) = 9362`!
2913    let widen_u8_full_bits = |b: u8| if b > 0 && 8 % b == 0 { b } else { 8 };
2914    let depth = match dst.layout().sample() {
2915        SampleType::U8 if dst.layout().packing().is_full() => {
2916            if src.layout().sample() == SampleType::U8 && src.layout().packing().is_full() {
2917                if let Some(d) = valid_src_depth {
2918                    let c_bits = if preserves_color_values {
2919                        d.color_bits()
2920                    } else {
2921                        8
2922                    };
2923                    let a_bits = if all_opaque && dst.layout().order().has_alpha_slot() {
2924                        1
2925                    } else if dst.layout().order().has_alpha_slot() {
2926                        d.alpha_bits()
2927                    } else {
2928                        8
2929                    };
2930                    ExactDepth::new(SampleType::U8, dst_range, c_bits, a_bits).ok()
2931                } else {
2932                    ExactDepth::new(SampleType::U8, dst_range, 8, if all_opaque { 1 } else { 8 })
2933                        .ok()
2934                }
2935            } else {
2936                ExactDepth::new(SampleType::U8, dst_range, 8, if all_opaque { 1 } else { 8 }).ok()
2937            }
2938        }
2939        SampleType::U16 if dst.layout().packing().is_full() => match bp {
2940            ByteFastPath::U8ToU16Exact => {
2941                let c_bits = valid_src_depth.map_or(8, |d| widen_u8_full_bits(d.color_bits()));
2942                let a_bits = if all_opaque && dst.layout().order().has_alpha_slot() {
2943                    1
2944                } else if dst.layout().order().has_alpha_slot() {
2945                    valid_src_depth.map_or(8, |d| widen_u8_full_bits(d.alpha_bits()))
2946                } else {
2947                    16
2948                };
2949                ExactDepth::new(SampleType::U16, SignalRange::Full, c_bits, a_bits).ok()
2950            }
2951            ByteFastPath::NarrowBitShift {
2952                src_bits,
2953                dst_bits: 16,
2954                ..
2955            } if src_bits < 16 => {
2956                let c_bits = valid_src_depth.map_or(src_bits, |d| d.color_bits());
2957                let a_bits = if all_opaque && dst.layout().order().has_alpha_slot() {
2958                    1
2959                } else if dst.layout().order().has_alpha_slot() {
2960                    valid_src_depth.map_or(src_bits, |d| {
2961                        if src_bits == 8 {
2962                            widen_u8_full_bits(d.alpha_bits())
2963                        } else {
2964                            src_bits
2965                        }
2966                    })
2967                } else {
2968                    16
2969                };
2970                ExactDepth::new(SampleType::U16, SignalRange::Narrow, c_bits, a_bits).ok()
2971            }
2972            _ if src.layout().sample() == SampleType::U16 && src.layout().packing().is_full() => {
2973                valid_src_depth.and_then(|d| {
2974                    let c_bits = if preserves_color_values {
2975                        d.color_bits()
2976                    } else {
2977                        16
2978                    };
2979                    let a_bits = if !dst.layout().order().has_alpha_slot() {
2980                        16
2981                    } else if all_opaque {
2982                        1
2983                    } else {
2984                        d.alpha_bits()
2985                    };
2986                    ExactDepth::new(SampleType::U16, dst_range, c_bits, a_bits).ok()
2987                })
2988            }
2989            _ => None,
2990        },
2991        _ => None,
2992    };
2993    let all_grayscale = matches!(dst.color(), ColorSpace::Gray { .. })
2994        || matches!(src.color(), ColorSpace::Gray { .. })
2995        || src_facts.all_grayscale;
2996    SampleClaims::NONE
2997        .with_float(float)
2998        .with_depth(depth)
2999        .with_all_opaque(all_opaque)
3000        .with_all_grayscale(all_grayscale)
3001        .with_binary_alpha(binary_alpha)
3002}
3003
3004#[allow(clippy::too_many_arguments)]
3005fn derive_output_facts_math(
3006    src: &PixelFormat,
3007    dst: &PixelFormat,
3008    src_facts: SampleClaims,
3009    clamped_color: bool,
3010    alpha_filled_opaque: bool,
3011    matte_applied: bool,
3012    is_f16_cast_only: bool,
3013    safe_no_subnormals: bool,
3014) -> SampleClaims {
3015    let dst_is_rgb_or_gray = matches!(
3016        dst.color(),
3017        ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. }
3018    );
3019    let float = if dst.layout().sample().is_float() && dst_is_rgb_or_gray {
3020        if is_f16_cast_only {
3021            // F32 -> F16 overflows > 65504 to +/-inf and preserves NaN/Inf; only UNIT_INTERVAL
3022            // survives safely as UNIT_INTERVAL (subnormals can arise in F16!).
3023            if src_facts.float.is_unit_interval() {
3024                FloatClaims::UNIT_INTERVAL
3025            } else {
3026                FloatClaims::NONE
3027            }
3028        } else if clamped_color {
3029            let alpha_unit = !dst.layout().order().has_alpha_slot()
3030                || alpha_filled_opaque
3031                || !src.layout().sample().is_float()
3032                || src_facts.float.is_unit_interval();
3033            if alpha_unit {
3034                if safe_no_subnormals {
3035                    FloatClaims::NORMAL_UNIT_INTERVAL
3036                } else {
3037                    // Clamping guarantees [0, 1] finite, NOT absence of subnormals.
3038                    FloatClaims::UNIT_INTERVAL
3039                }
3040            } else {
3041                FloatClaims::NONE
3042            }
3043        } else {
3044            FloatClaims::NONE
3045        }
3046    } else {
3047        FloatClaims::NONE
3048    };
3049
3050    let all_opaque = matches!(
3051        dst.color().alpha(),
3052        AlphaMode::None | AlphaMode::Opaque | AlphaMode::Undefined
3053    ) || matte_applied
3054        || alpha_filled_opaque
3055        || src_facts.all_opaque;
3056    let binary_alpha = all_opaque || src_facts.binary_alpha;
3057    // Never propagate U8 exactness into U16 after transfer/gamut/narrow/premul math!
3058    let depth = if dst.layout().sample() == SampleType::U8 && dst.layout().packing().is_full() {
3059        ExactDepth::new(
3060            SampleType::U8,
3061            color_range(dst.color()),
3062            8,
3063            if all_opaque { 1 } else { 8 },
3064        )
3065        .ok()
3066    } else {
3067        None
3068    };
3069    let all_grayscale = matches!(dst.color(), ColorSpace::Gray { .. });
3070    SampleClaims::NONE
3071        .with_float(float)
3072        .with_depth(depth)
3073        .with_all_opaque(all_opaque)
3074        .with_all_grayscale(all_grayscale)
3075        .with_binary_alpha(binary_alpha)
3076}