Skip to main content

zenpixels_convert/
planar_capture.rs

1//! Forward packed-to-planar capture ([`PlanarCaptureSpec`], [`PlanarCapturePlan`],
2//! [`CaptureScratch`]): strided interleaved pixels → multi-plane YCbCr / YCgCo /
3//! Identity GBR / planar RGB / monochrome [`PlanarViewMut`] (`U8`, `U16` 8/10/12/16-bit
4//! including `P010` / `U10_LSB`, `U32`, and `F32` planar RGB).
5//!
6//! Two-stage execution guarantees identical color, transfer, HDR white/peak, HLG OOTF,
7//! alpha matte, gamut, and CMS behavior with [`RowPlan`]:
8//! 1. Stage 1 converts source rows into full-range `f32` in the destination's primaries,
9//!    transfer, diffuse white, and alpha mode using a compiled [`RowPlan`]
10//!    over an O(width) ring buffer of at most `2 * max_vertical_subsampling + 1` rows
11//!    (5 rows for 4:2:0 — ~230 KiB at 4K instead of a full frame buffer).
12//! 2. Stage 2 evaluates exact `f64` ITU-T H.273 matrix encoding, phase-exact chroma
13//!    downsampling honoring [`PlanarCaptureSpec::chroma_siting`] and
14//!    [`PlanarCaptureSpec::visible_rect`] crop origin (using local integer coordinates
15//!    immune to large-offset float rounding), final `f64` quantization (`Round` /
16//!    `Truncate` / `OrderedDither`), and [`BitPacking::pack_code`](zenpixels::BitPacking::pack_code).
17
18use alloc::boxed::Box;
19use alloc::vec::Vec;
20use how_far::Pulse;
21use whereat::At;
22use zenpixels::{
23    AlphaMode, ChromaSiting, Cicp, ColorSpace, DiffuseWhite, HdrMetadata, Nits, PixelFormat,
24    PixelRect, PixelView, PlanarBuf, PlanarViewMut, PlaneFormat, PlaneRole, Primaries,
25    SampleLayout, SampleType, SignalRange, Transfer,
26};
27
28use crate::error::{ConvertError, err_at};
29use crate::plan::{
30    RowPlan, color_primaries, color_transfer, is_gamut_narrowing, is_scene_linear_hdr_candidate,
31    try_substitute_icc,
32};
33use crate::policy::{ConvertPolicy, DepthPolicy, GamutPolicy, RangePolicy};
34use crate::pulse::{check_pulse, live_pulse, step_pulse};
35use crate::ycbcr::YcbcrMatrix;
36
37/// 4×4 Bayer ordered-dither integer thresholds (`0..=15`, normalized as `(b + 0.5) / 16`).
38const BAYER_4X4_INT: [i128; 16] = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
39
40/// 4×4 Bayer ordered-dither threshold matrix normalized to `[0.5/16, 15.5/16]`.
41const BAYER_4X4: [f64; 16] = [
42    0.5 / 16.0,
43    8.5 / 16.0,
44    2.5 / 16.0,
45    10.5 / 16.0,
46    12.5 / 16.0,
47    4.5 / 16.0,
48    14.5 / 16.0,
49    6.5 / 16.0,
50    3.5 / 16.0,
51    11.5 / 16.0,
52    1.5 / 16.0,
53    9.5 / 16.0,
54    15.5 / 16.0,
55    7.5 / 16.0,
56    13.5 / 16.0,
57    5.5 / 16.0,
58];
59
60/// Chroma downsampling filter for subsampled YCbCr capture (`4:2:0`, `4:2:2`, `4:4:0`, `4:1:1`).
61///
62/// Ignored for full-resolution (`1×1`) planar RGB, 4:4:4 YCbCr/GBR, and monochrome targets.
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
64#[non_exhaustive]
65pub enum ChromaDownsample {
66    /// Phase-exact separable triangle downsampler honoring [`PlanarCaptureSpec::chroma_siting`]
67    /// and [`PlanarCaptureSpec::visible_rect`] crop origin.
68    ///
69    /// Produces exact `[1, 2, 1]/4` co-sited filtering for `Left`/`TopLeft` 2× axes,
70    /// `[1, 3, 3, 1]/8` dual-bilinear filtering for `Center` 2× axes, and exact
71    /// dyadic triangle taps for 4× axes, with zero phase shift and edge clamping.
72    ///
73    /// Refuses [`ChromaSiting::Unknown`] on any subsampled axis unless
74    /// [`PlanarCaptureOptions::unknown_siting_fallback`] is set.
75    #[default]
76    SitingAware,
77    /// Unweighted box average over each chroma cell's luma pixels, honoring crop origin
78    /// and clamping at visible edges. Works even when `chroma_siting == ChromaSiting::Unknown`.
79    BoxAverage,
80    /// Nearest luma sample at each chroma sample center, honoring [`PlanarCaptureSpec::chroma_siting`]
81    /// and [`PlanarCaptureSpec::visible_rect`] crop origin.
82    ///
83    /// Refuses [`ChromaSiting::Unknown`] on any subsampled axis unless
84    /// [`PlanarCaptureOptions::unknown_siting_fallback`] is set.
85    Nearest,
86}
87
88/// Configuration for forward planar capture ([`PlanarCapturePlan`]).
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
90#[non_exhaustive]
91pub struct PlanarCaptureOptions {
92    /// Chroma downsampling kernel (`SitingAware` default).
93    pub downsample: ChromaDownsample,
94    /// Optional fallback [`ChromaSiting`] used when a siting-dependent downsample
95    /// (`SitingAware` or `Nearest`) runs on a subsampled target whose
96    /// `spec.chroma_siting == ChromaSiting::Unknown`.
97    pub unknown_siting_fallback: Option<ChromaSiting>,
98}
99
100impl PlanarCaptureOptions {
101    /// Phase-exact siting-aware chroma downsampling (`ChromaDownsample::SitingAware`).
102    #[inline]
103    #[must_use]
104    pub const fn siting_aware() -> Self {
105        Self {
106            downsample: ChromaDownsample::SitingAware,
107            unknown_siting_fallback: None,
108        }
109    }
110
111    /// Cell box-average chroma downsampling (`ChromaDownsample::BoxAverage`).
112    #[inline]
113    #[must_use]
114    pub const fn box_average() -> Self {
115        Self {
116            downsample: ChromaDownsample::BoxAverage,
117            unknown_siting_fallback: None,
118        }
119    }
120
121    /// Nearest-sample chroma downsampling (`ChromaDownsample::Nearest`).
122    #[inline]
123    #[must_use]
124    pub const fn nearest() -> Self {
125        Self {
126            downsample: ChromaDownsample::Nearest,
127            unknown_siting_fallback: None,
128        }
129    }
130
131    /// Select the chroma downsampling kernel.
132    #[inline]
133    #[must_use]
134    pub const fn with_downsample(mut self, downsample: ChromaDownsample) -> Self {
135        self.downsample = downsample;
136        self
137    }
138
139    /// Provide an explicit fallback [`ChromaSiting`] when the target declares `ChromaSiting::Unknown`.
140    #[inline]
141    #[must_use]
142    pub const fn with_unknown_siting_fallback(mut self, siting: ChromaSiting) -> Self {
143        self.unknown_siting_fallback = Some(siting);
144        self
145    }
146}
147
148/// Target planar geometry, plane layout, chroma siting, and true coded CICP signal
149/// for [`PlanarCapturePlan`].
150#[derive(Clone, Debug, PartialEq, Eq, Hash)]
151#[non_exhaustive]
152pub struct PlanarCaptureSpec {
153    /// Full coded frame dimensions `(width, height)` in luma pixels.
154    pub coded_extent: (u32, u32),
155    /// Visible active rectangle within `coded_extent`; its `(x, y)` origin establishes
156    /// the subsampling phase against the coded grid, and `(width, height)` must match
157    /// the source [`PixelView`] and destination [`PlanarViewMut`] dimensions.
158    pub visible_rect: PixelRect,
159    /// Target plane storage specifications (roles, sample types, bit packing, subsampling).
160    pub planes: Box<[PlaneFormat]>,
161    /// Target chroma sample siting.
162    pub chroma_siting: ChromaSiting,
163    /// True coded destination CICP signal (primaries, transfer, matrix coefficients, full/narrow range).
164    pub signal: Cicp,
165    /// Target alpha association when `planes` includes [`PlaneRole::Alpha`] (default `Straight`).
166    pub alpha: AlphaMode,
167    /// Optional relative-linear `1.0` diffuse-white anchor for the destination color space.
168    pub diffuse_white: Option<DiffuseWhite>,
169}
170
171impl PlanarCaptureSpec {
172    /// Construct a planar capture specification with explicit `coded_extent` and `visible_rect`.
173    #[must_use]
174    pub fn new(
175        coded_extent: (u32, u32),
176        visible_rect: PixelRect,
177        planes: impl Into<Box<[PlaneFormat]>>,
178        chroma_siting: ChromaSiting,
179        signal: Cicp,
180    ) -> Self {
181        Self {
182            coded_extent,
183            visible_rect,
184            planes: planes.into(),
185            chroma_siting,
186            signal,
187            alpha: AlphaMode::Straight,
188            diffuse_white: None,
189        }
190    }
191
192    /// Construct a full-frame planar capture specification (`visible_rect` covers `(0, 0, width, height)`).
193    #[must_use]
194    pub fn full_frame(
195        width: u32,
196        height: u32,
197        planes: impl Into<Box<[PlaneFormat]>>,
198        chroma_siting: ChromaSiting,
199        signal: Cicp,
200    ) -> Self {
201        Self::new(
202            (width, height),
203            PixelRect::new(0, 0, width, height),
204            planes,
205            chroma_siting,
206            signal,
207        )
208    }
209
210    /// Set alpha association mode for an optional [`PlaneRole::Alpha`] plane.
211    #[inline]
212    #[must_use]
213    pub const fn with_alpha(mut self, alpha: AlphaMode) -> Self {
214        self.alpha = alpha;
215        self
216    }
217
218    /// Set explicit diffuse-white anchor for the destination color space.
219    #[inline]
220    #[must_use]
221    pub const fn with_diffuse_white(mut self, white: DiffuseWhite) -> Self {
222        self.diffuse_white = Some(white);
223        self
224    }
225}
226
227#[derive(Debug)]
228enum ScratchBacking<'a> {
229    Borrowed(&'a mut [f64]),
230    Owned(Vec<f64>),
231}
232
233/// Reusable caller-owned or budget-borrowed `f64` scratch workspace for [`PlanarCapturePlan::execute`].
234///
235/// Use [`CaptureScratch::from_f64_slice`] with a caller-allocated or `StorageBudget`-backed
236/// slice for zero-heap capture on native conversion routes (a custom external `CmsTransform`
237/// invoked inside Stage 1 may still allocate unless its [`CmsQuote::apply_scratch_bytes`](crate::CmsQuote::apply_scratch_bytes)
238/// is `Some(0)`), or [`CaptureScratch::owned`] to reuse one fallibly allocated buffer across frames.
239#[derive(Debug)]
240pub struct CaptureScratch<'a> {
241    backing: ScratchBacking<'a>,
242}
243
244impl Default for CaptureScratch<'static> {
245    fn default() -> Self {
246        Self::owned()
247    }
248}
249
250impl<'a> CaptureScratch<'a> {
251    /// Borrow a caller-provided `&mut [f64]` workspace (never heap-allocates; fails with
252    /// [`ConvertError::DimensionMismatch`] if shorter than [`PlanarCapturePlan::required_scratch_f64s`]).
253    #[inline]
254    #[must_use]
255    pub fn from_f64_slice(slice: &'a mut [f64]) -> Self {
256        Self {
257            backing: ScratchBacking::Borrowed(slice),
258        }
259    }
260
261    /// Number of `f64` elements currently available without reallocating.
262    #[inline]
263    #[must_use]
264    pub fn len_f64s(&self) -> usize {
265        match &self.backing {
266            ScratchBacking::Borrowed(s) => s.len(),
267            ScratchBacking::Owned(v) => v.len(),
268        }
269    }
270
271    fn acquire(&mut self, needed: usize) -> Result<&mut [f64], At<ConvertError>> {
272        match &mut self.backing {
273            ScratchBacking::Borrowed(s) => {
274                if s.len() < needed {
275                    return Err(err_at(ConvertError::DimensionMismatch));
276                }
277                Ok(&mut s[..needed])
278            }
279            ScratchBacking::Owned(v) => {
280                if v.len() < needed {
281                    let extra = needed - v.len();
282                    v.try_reserve_exact(extra)
283                        .map_err(|_| err_at(ConvertError::AllocationFailed))?;
284                    v.resize(needed, 0.0);
285                }
286                Ok(&mut v[..needed])
287            }
288        }
289    }
290}
291
292impl CaptureScratch<'static> {
293    /// Create an empty owned scratch buffer that grows fallibly on first use and reuses capacity.
294    #[inline]
295    #[must_use]
296    pub const fn owned() -> Self {
297        Self {
298            backing: ScratchBacking::Owned(Vec::new()),
299        }
300    }
301
302    /// Pre-allocate an owned scratch buffer for at least `len_f64s` `f64` elements.
303    pub fn with_capacity_f64s(len_f64s: usize) -> Result<Self, At<ConvertError>> {
304        let mut v = Vec::new();
305        v.try_reserve_exact(len_f64s)
306            .map_err(|_| err_at(ConvertError::AllocationFailed))?;
307        v.resize(len_f64s, 0.0);
308        Ok(Self {
309            backing: ScratchBacking::Owned(v),
310        })
311    }
312}
313
314#[derive(Clone, Copy, Debug)]
315enum TargetLayout {
316    Monochrome {
317        y_idx: usize,
318        alpha_idx: Option<usize>,
319    },
320    PlanarRgb {
321        r_idx: usize,
322        g_idx: usize,
323        b_idx: usize,
324        alpha_idx: Option<usize>,
325    },
326    YcbcrPlanar {
327        y_idx: usize,
328        cb_idx: usize,
329        cr_idx: usize,
330        alpha_idx: Option<usize>,
331    },
332    YcbcrSemi {
333        y_idx: usize,
334        uv_idx: usize,
335        swapped: bool,
336        alpha_idx: Option<usize>,
337    },
338}
339
340#[derive(Clone, Copy, Debug)]
341enum ForwardMatrix {
342    Identity,
343    YCgCo,
344    Ncl {
345        kr: f64,
346        kg: f64,
347        kb: f64,
348        inv_2_1_minus_kb: f64,
349        inv_2_1_minus_kr: f64,
350        /// Exact `(kr_num, kg_num, kb_num, den)` integer rational coefficients for known
351        /// ITU-T H.273 NCL matrices so integer-RGB inputs round exact half-ties without
352        /// IEEE-754 ULP drift.
353        exact_rational: Option<(i128, i128, i128, i128)>,
354    },
355}
356
357#[derive(Clone, Copy, Debug)]
358struct DirectIntRgb {
359    is_u16: bool,
360    channels: usize,
361    r_idx: usize,
362    g_idx: usize,
363    b_idx: usize,
364    a_idx: Option<usize>,
365}
366
367/// Prepared, reusable, thread-safe forward planar capture plan.
368///
369/// Built via [`PlanarCapturePlan::build`] or [`PlanarCapturePlan::build_with_options`],
370/// capturing the validated target [`PlanarCaptureSpec`], compiled color/transfer [`RowPlan`],
371/// exact `f64` / rational `i128` YCbCr/GBR forward matrix, and chroma downsampling geometry.
372#[derive(Clone, Debug)]
373pub struct PlanarCapturePlan {
374    spec: PlanarCaptureSpec,
375    options: PlanarCaptureOptions,
376    row_plan: RowPlan,
377    direct_int_rgb: Option<DirectIntRgb>,
378    inter_channels: usize,
379    layout: TargetLayout,
380    matrix: ForwardMatrix,
381    range: SignalRange,
382    depth_policy: DepthPolicy,
383    resolved_siting: ChromaSiting,
384    any_subsampled: bool,
385    ring_rows: usize,
386    dst_color: ColorSpace,
387    dst_can_represent_hdr: bool,
388}
389
390fn exact_ncl_rational(ym: YcbcrMatrix) -> Option<(i128, i128, i128, i128)> {
391    match ym {
392        YcbcrMatrix::Bt709 => Some((2126, 7152, 722, 10_000)),
393        YcbcrMatrix::Fcc => Some((3000, 5900, 1100, 10_000)),
394        YcbcrMatrix::Bt470Bg | YcbcrMatrix::Bt601 => Some((2990, 5870, 1140, 10_000)),
395        YcbcrMatrix::Smpte240M => Some((2120, 7010, 870, 10_000)),
396        YcbcrMatrix::Bt2020 => Some((2627, 6780, 593, 10_000)),
397        YcbcrMatrix::ChromaDerivedNcl | YcbcrMatrix::Identity | YcbcrMatrix::YCgCo => None,
398    }
399}
400
401fn exact_ncl_kr_kb_f64(ym: YcbcrMatrix, primaries: Option<Primaries>) -> Option<(f64, f64)> {
402    match ym {
403        YcbcrMatrix::Bt709 => Some((0.2126, 0.0722)),
404        YcbcrMatrix::Fcc => Some((0.30, 0.11)),
405        YcbcrMatrix::Bt470Bg | YcbcrMatrix::Bt601 => Some((0.299, 0.114)),
406        YcbcrMatrix::Smpte240M => Some((0.212, 0.087)),
407        YcbcrMatrix::Bt2020 => Some((0.2627, 0.0593)),
408        YcbcrMatrix::ChromaDerivedNcl => {
409            let (kr, kb) = ym.kr_kb_for(primaries)?;
410            Some((f64::from(kr), f64::from(kb)))
411        }
412        YcbcrMatrix::Identity | YcbcrMatrix::YCgCo => None,
413    }
414}
415
416impl PlanarCapturePlan {
417    /// Compile a forward planar capture plan with default [`PlanarCaptureOptions::siting_aware()`]
418    /// and no pre-resolved HDR peak.
419    pub fn build(
420        src: &PixelFormat,
421        dst: PlanarCaptureSpec,
422        policy: &ConvertPolicy,
423    ) -> Result<Self, At<ConvertError>> {
424        Self::build_with_options(src, dst, policy, PlanarCaptureOptions::default(), None)
425    }
426
427    /// Compile a forward planar capture plan with explicit [`PlanarCaptureOptions`] and
428    /// optional resolved HDR source peak luminance (for HDR → SDR tone mapping).
429    pub fn build_with_options(
430        src: &PixelFormat,
431        dst: PlanarCaptureSpec,
432        policy: &ConvertPolicy,
433        options: PlanarCaptureOptions,
434        resolved_source_peak: Option<Nits>,
435    ) -> Result<Self, At<ConvertError>> {
436        Self::build_with_pulse(src, dst, policy, options, resolved_source_peak, None)
437    }
438
439    /// Compile a forward planar capture plan with explicit [`PlanarCaptureOptions`], optional
440    /// resolved HDR source peak luminance, and optional cooperative cancellation/progress via
441    /// `pulse` (forwarded to any configured [`CmsBackend`](crate::CmsBackend) or
442    /// [`ToneMapper`](crate::ToneMapper); pass `None` when not needed).
443    pub fn build_with_pulse(
444        src: &PixelFormat,
445        dst: PlanarCaptureSpec,
446        policy: &ConvertPolicy,
447        options: PlanarCaptureOptions,
448        resolved_source_peak: Option<Nits>,
449        pulse: Option<&dyn Pulse>,
450    ) -> Result<Self, At<ConvertError>> {
451        // 1. Validate coded_extent & visible_rect containment.
452        let (cw, ch) = dst.coded_extent;
453        let vis = dst.visible_rect;
454        if cw == 0 || ch == 0 || vis.width == 0 || vis.height == 0 {
455            return Err(err_at(ConvertError::DimensionMismatch));
456        }
457        let end_x = vis
458            .x
459            .checked_add(vis.width)
460            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
461        let end_y = vis
462            .y
463            .checked_add(vis.height)
464            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
465        if end_x > cw || end_y > ch {
466            return Err(err_at(ConvertError::DimensionMismatch));
467        }
468        if dst.planes.is_empty() {
469            return Err(err_at(ConvertError::UnsupportedRoute));
470        }
471
472        // 2. Parse & validate destination plane formats.
473        let (layout, has_alpha, is_mono, allow_f32_planes, any_subsampled, max_vy, min_int_bits) =
474            parse_target_planes(&dst.planes, vis)?;
475
476        // 3. Resolve destination range, transfer, primaries, matrix, and chroma siting.
477        let dst_range = if dst.signal.full_range {
478            SignalRange::Full
479        } else {
480            SignalRange::Narrow
481        };
482        // Floating-point planar RGB carries normalized full-range values; refuse narrow F32.
483        if dst_range == SignalRange::Narrow
484            && dst.planes.iter().any(|p| p.sample() == SampleType::F32)
485        {
486            return Err(err_at(ConvertError::UnsupportedRoute));
487        }
488        let src_range = src.color().range().unwrap_or(SignalRange::Full);
489        if src_range != dst_range && policy.range == RangePolicy::Forbid {
490            return Err(err_at(ConvertError::RangeConversionForbidden));
491        }
492
493        let transfer = Transfer::from_cicp(dst.signal.transfer_characteristics)
494            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
495        let primaries = if is_mono {
496            Primaries::Bt709
497        } else {
498            Primaries::from_cicp(dst.signal.color_primaries)
499                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?
500        };
501
502        let dst_alpha = if has_alpha {
503            match dst.alpha {
504                AlphaMode::Straight | AlphaMode::Premultiplied | AlphaMode::Opaque => dst.alpha,
505                _ => return Err(err_at(ConvertError::UnsupportedRoute)),
506            }
507        } else {
508            AlphaMode::None
509        };
510
511        let matrix = match layout {
512            TargetLayout::Monochrome { .. } | TargetLayout::PlanarRgb { .. } => {
513                if matches!(layout, TargetLayout::PlanarRgb { .. })
514                    && dst.signal.matrix_coefficients != 0
515                {
516                    return Err(err_at(ConvertError::UnsupportedRoute));
517                }
518                ForwardMatrix::Identity
519            }
520            TargetLayout::YcbcrPlanar { .. } | TargetLayout::YcbcrSemi { .. } => {
521                let ym = YcbcrMatrix::from_cicp_code(dst.signal.matrix_coefficients)
522                    .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
523                match ym {
524                    YcbcrMatrix::Identity => {
525                        if matches!(layout, TargetLayout::YcbcrSemi { .. }) || any_subsampled {
526                            return Err(err_at(ConvertError::UnsupportedRoute));
527                        }
528                        ForwardMatrix::Identity
529                    }
530                    YcbcrMatrix::YCgCo => ForwardMatrix::YCgCo,
531                    _ => {
532                        let p_opt = if primaries == Primaries::Unknown {
533                            None
534                        } else {
535                            Some(primaries)
536                        };
537                        let (kr, kb) = exact_ncl_kr_kb_f64(ym, p_opt)
538                            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
539                        let kg = 1.0 - kr - kb;
540                        if kg <= 1e-9 || (1.0 - kr).abs() <= 1e-9 || (1.0 - kb).abs() <= 1e-9 {
541                            return Err(err_at(ConvertError::UnsupportedRoute));
542                        }
543                        ForwardMatrix::Ncl {
544                            kr,
545                            kg,
546                            kb,
547                            inv_2_1_minus_kb: 1.0 / (2.0 * (1.0 - kb)),
548                            inv_2_1_minus_kr: 1.0 / (2.0 * (1.0 - kr)),
549                            exact_rational: exact_ncl_rational(ym),
550                        }
551                    }
552                }
553            }
554        };
555
556        let needs_siting = any_subsampled
557            && matches!(
558                options.downsample,
559                ChromaDownsample::SitingAware | ChromaDownsample::Nearest
560            );
561        let resolved_siting = if needs_siting {
562            if dst.chroma_siting != ChromaSiting::Unknown {
563                dst.chroma_siting
564            } else if let Some(fb) = options.unknown_siting_fallback
565                && fb != ChromaSiting::Unknown
566            {
567                fb
568            } else {
569                return Err(err_at(ConvertError::UnsupportedRoute));
570            }
571        } else if dst.chroma_siting != ChromaSiting::Unknown {
572            dst.chroma_siting
573        } else {
574            options
575                .unknown_siting_fallback
576                .unwrap_or(ChromaSiting::Unknown)
577        };
578
579        // 4. Enforce final-plane depth & gamut policies that Stage 1 (targeting F32) wouldn't see.
580        let targets_bounded_int =
581            !allow_f32_planes || dst.planes.iter().any(|p| p.sample() != SampleType::F32);
582        if targets_bounded_int {
583            let src_bits = src_effective_bits(src);
584            let depth_reduces = src.layout().sample().is_float() || min_int_bits < src_bits;
585            if depth_reduces && policy.depth == DepthPolicy::Forbid {
586                return Err(err_at(ConvertError::DepthReductionForbidden));
587            }
588        }
589
590        // 5. Build full-range F32 intermediate PixelFormat and compile Stage 1 RowPlan.
591        let (inter_layout, inter_color, dst_color) = if is_mono {
592            let layout_inter = if has_alpha {
593                SampleLayout::GRAYAF32
594            } else {
595                SampleLayout::GRAYF32
596            };
597            let inter_cs = ColorSpace::Gray {
598                transfer,
599                range: SignalRange::Full,
600                alpha: dst_alpha,
601                diffuse_white: dst.diffuse_white,
602            };
603            let tagged_cs = ColorSpace::Gray {
604                transfer,
605                range: dst_range,
606                alpha: dst_alpha,
607                diffuse_white: dst.diffuse_white,
608            };
609            (layout_inter, inter_cs, tagged_cs)
610        } else {
611            let layout_inter = if has_alpha {
612                SampleLayout::RGBAF32
613            } else {
614                SampleLayout::RGBF32
615            };
616            let inter_cs = ColorSpace::Rgb {
617                primaries,
618                transfer,
619                range: SignalRange::Full,
620                alpha: dst_alpha,
621                diffuse_white: dst.diffuse_white,
622            };
623            let tagged_cs = ColorSpace::Rgb {
624                primaries,
625                transfer,
626                range: dst_range,
627                alpha: dst_alpha,
628                diffuse_white: dst.diffuse_white,
629            };
630            (layout_inter, inter_cs, tagged_cs)
631        };
632        let inter_fmt =
633            PixelFormat::new(inter_layout, inter_color).map_err(|e| err_at((*e.error()).into()))?;
634
635        if targets_bounded_int {
636            let src_p = color_primaries(src.color());
637            let dst_p = color_primaries(inter_fmt.color());
638            let cross_profile_cms = matches!(
639                src.color(),
640                ColorSpace::Icc { .. } | ColorSpace::Cmyk { .. }
641            ) && try_substitute_icc(src, policy).is_none();
642            let gamut_narrows = is_gamut_narrowing(src_p, dst_p) || cross_profile_cms;
643            let src_tf = color_transfer(src.color());
644            let dst_tf = color_transfer(inter_fmt.color());
645            let is_hdr_to_sdr = (src_tf.is_hdr() && !dst_tf.is_hdr())
646                || (is_scene_linear_hdr_candidate(src, &inter_fmt)
647                    && !policy.source_claims.float.is_unit_interval());
648            let unproven_float_to_int =
649                src.layout().sample().is_float() && !policy.source_claims.float.is_unit_interval();
650            if (policy.gamut == GamutPolicy::Forbid
651                && (gamut_narrows || is_hdr_to_sdr || unproven_float_to_int))
652                || (policy.gamut == GamutPolicy::PreserveExtended
653                    && policy.depth == DepthPolicy::Forbid
654                    && (gamut_narrows || is_hdr_to_sdr || unproven_float_to_int))
655            {
656                return Err(err_at(ConvertError::GamutLossForbidden));
657            }
658        }
659
660        // Stage 1 converts to full-range F32; we already checked `policy.range` against `dst_range`.
661        let mut stage1_policy = policy.clone();
662        stage1_policy.range = RangePolicy::Convert;
663        // Ordered dither applies at final integer plane quantization in Stage 2, not into F32.
664        if stage1_policy.depth == DepthPolicy::OrderedDither {
665            stage1_policy.depth = DepthPolicy::Round;
666        }
667        let row_plan = RowPlan::build_with_pulse(
668            src,
669            &inter_fmt,
670            &stage1_policy,
671            resolved_source_peak,
672            pulse,
673        )?;
674        let direct_int_rgb = if is_mono {
675            None
676        } else {
677            detect_direct_int_rgb(src, &inter_fmt, has_alpha)
678        };
679
680        let ring_rows = if any_subsampled && max_vy > 1 {
681            match options.downsample {
682                ChromaDownsample::SitingAware => usize::from(max_vy) * 2 + 1,
683                ChromaDownsample::BoxAverage => usize::from(max_vy) + 1,
684                ChromaDownsample::Nearest => 2,
685            }
686        } else {
687            1
688        };
689
690        let dst_can_represent_hdr =
691            transfer.is_hdr() || (transfer.is_linear() && !targets_bounded_int);
692
693        Ok(Self {
694            spec: dst,
695            options,
696            row_plan,
697            direct_int_rgb,
698            inter_channels: inter_layout.channels(),
699            layout,
700            matrix,
701            range: dst_range,
702            depth_policy: policy.depth,
703            resolved_siting,
704            any_subsampled,
705            ring_rows,
706            dst_color,
707            dst_can_represent_hdr,
708        })
709    }
710
711    /// Validated destination [`PlanarCaptureSpec`].
712    #[inline]
713    #[must_use]
714    pub fn spec(&self) -> &PlanarCaptureSpec {
715        &self.spec
716    }
717
718    /// Expected source [`PixelFormat`].
719    #[inline]
720    #[must_use]
721    pub fn source_format(&self) -> &PixelFormat {
722        self.row_plan.source_format()
723    }
724
725    /// Active [`PlanarCaptureOptions`].
726    #[inline]
727    #[must_use]
728    pub const fn options(&self) -> PlanarCaptureOptions {
729        self.options
730    }
731
732    /// Effective [`ChromaSiting`] applied during capture (reflecting `unknown_siting_fallback`
733    /// when `spec.chroma_siting` was [`ChromaSiting::Unknown`]).
734    #[inline]
735    #[must_use]
736    pub const fn resolved_siting(&self) -> ChromaSiting {
737        self.resolved_siting
738    }
739
740    /// Number of `f64` elements required in [`CaptureScratch`] for [`execute`](Self::execute).
741    #[inline]
742    #[must_use]
743    pub fn required_scratch_f64s(&self) -> usize {
744        (self.spec.visible_rect.width as usize)
745            .saturating_mul(self.inter_channels)
746            .saturating_mul(self.ring_rows)
747    }
748
749    /// Bytes required in [`CaptureScratch`] for [`execute`](Self::execute).
750    #[inline]
751    #[must_use]
752    pub fn required_scratch_bytes(&self) -> usize {
753        self.required_scratch_f64s()
754            .saturating_mul(core::mem::size_of::<f64>())
755    }
756
757    /// Execute the capture plan into a caller-provided strided [`PlanarViewMut`] using
758    /// caller-owned [`CaptureScratch`] (zero heap allocation on native routes when `scratch`
759    /// is pre-sized or borrowed via [`CaptureScratch::from_f64_slice`]).
760    ///
761    /// For subsampled targets, `dst.chroma_siting()` must match [`resolved_siting`](Self::resolved_siting)
762    /// so borrowed destinations never report an inconsistent or missing chroma siting.
763    pub fn execute(
764        &self,
765        src: PixelView<'_>,
766        dst: &mut PlanarViewMut<'_>,
767        scratch: &mut CaptureScratch<'_>,
768    ) -> Result<(), At<ConvertError>> {
769        self.execute_with_pulse(src, dst, scratch, None)
770    }
771
772    /// Execute the capture plan with optional cooperative cancellation and row progress via
773    /// `pulse` (pass `None` when not needed).
774    pub fn execute_with_pulse(
775        &self,
776        src: PixelView<'_>,
777        dst: &mut PlanarViewMut<'_>,
778        scratch: &mut CaptureScratch<'_>,
779        pulse: Option<&dyn Pulse>,
780    ) -> Result<(), At<ConvertError>> {
781        let pulse = live_pulse(pulse);
782        check_pulse(pulse)?;
783        let vis = self.spec.visible_rect;
784        if src.width() != vis.width || src.height() != vis.height {
785            return Err(err_at(ConvertError::DimensionMismatch));
786        }
787        if src.format() != self.row_plan.source_format() {
788            return Err(err_at(ConvertError::UnsupportedRoute));
789        }
790        if dst.width() != vis.width
791            || dst.height() != vis.height
792            || dst.crop_origin() != (vis.x, vis.y)
793        {
794            return Err(err_at(ConvertError::DimensionMismatch));
795        }
796        if self.any_subsampled {
797            if dst.chroma_siting() != self.resolved_siting {
798                return Err(err_at(ConvertError::UnsupportedRoute));
799            }
800        } else if dst.chroma_siting() != ChromaSiting::Unknown
801            && self.resolved_siting != ChromaSiting::Unknown
802            && dst.chroma_siting() != self.resolved_siting
803        {
804            return Err(err_at(ConvertError::UnsupportedRoute));
805        }
806        if dst.planes().len() != self.spec.planes.len() {
807            return Err(err_at(ConvertError::DimensionMismatch));
808        }
809        for (actual, expected) in dst.planes().iter().zip(self.spec.planes.iter()) {
810            if actual.format() != *expected {
811                return Err(err_at(ConvertError::UnsupportedRoute));
812            }
813            let (ew, eh) = expected
814                .cropped_plane_dimensions(vis)
815                .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
816            if actual.width() != ew || actual.height() != eh {
817                return Err(err_at(ConvertError::DimensionMismatch));
818            }
819        }
820        // Validate any explicitly declared destination metadata BEFORE touching scratch or planes.
821        // Untagged borrowed destinations (`None`) and separate authoritative overrides remain valid.
822        if let Some(mc) = dst.matrix_coefficients() {
823            let matrix_ok = match self.layout {
824                TargetLayout::Monochrome { .. } => {
825                    mc == self.spec.signal.matrix()
826                        || mc == zenpixels::MatrixCoefficients::UNSPECIFIED
827                }
828                TargetLayout::PlanarRgb { .. } => mc == zenpixels::MatrixCoefficients::IDENTITY,
829                TargetLayout::YcbcrPlanar { .. } | TargetLayout::YcbcrSemi { .. } => {
830                    mc == self.spec.signal.matrix()
831                }
832            };
833            if !matrix_ok {
834                return Err(err_at(ConvertError::UnsupportedRoute));
835            }
836        }
837        if let Some(actual_range) = dst.effective_range()
838            && actual_range != self.range
839        {
840            return Err(err_at(ConvertError::UnsupportedRoute));
841        }
842        if let Some(actual_alpha) = dst.effective_alpha() {
843            let expected_alpha = self.dst_color.alpha();
844            if expected_alpha == AlphaMode::None || actual_alpha != expected_alpha {
845                return Err(err_at(ConvertError::UnsupportedRoute));
846            }
847        }
848        if let Some(actual_color) = dst.color()
849            && !crate::plan::same_photometry(actual_color, &self.dst_color)
850        {
851            return Err(err_at(ConvertError::UnsupportedRoute));
852        }
853
854        let w = vis.width as usize;
855        let row_floats = w
856            .checked_mul(self.inter_channels)
857            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
858        let needed = row_floats
859            .checked_mul(self.ring_rows)
860            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
861        let ring = scratch.acquire(needed)?;
862
863        match self.layout {
864            TargetLayout::Monochrome { y_idx, alpha_idx } => {
865                self.exec_monochrome(&src, dst, ring, row_floats, y_idx, alpha_idx, pulse)?;
866            }
867            TargetLayout::PlanarRgb {
868                r_idx,
869                g_idx,
870                b_idx,
871                alpha_idx,
872            } => {
873                self.exec_planar_rgb(
874                    &src, dst, ring, row_floats, r_idx, g_idx, b_idx, alpha_idx, pulse,
875                )?;
876            }
877            TargetLayout::YcbcrPlanar {
878                y_idx,
879                cb_idx,
880                cr_idx,
881                alpha_idx,
882            } => {
883                self.exec_ycbcr(
884                    &src,
885                    dst,
886                    ring,
887                    row_floats,
888                    y_idx,
889                    YcbcrDstIndices::Planar { cb_idx, cr_idx },
890                    alpha_idx,
891                    pulse,
892                )?;
893            }
894            TargetLayout::YcbcrSemi {
895                y_idx,
896                uv_idx,
897                swapped,
898                alpha_idx,
899            } => {
900                self.exec_ycbcr(
901                    &src,
902                    dst,
903                    ring,
904                    row_floats,
905                    y_idx,
906                    YcbcrDstIndices::Semi { uv_idx, swapped },
907                    alpha_idx,
908                    pulse,
909                )?;
910            }
911        }
912
913        dst.set_orientation(src.orientation());
914        Ok(())
915    }
916
917    /// Allocate a tagged [`PlanarBuf`] covering the zero-origin [`visible_rect`](PlanarCaptureSpec::visible_rect)
918    /// (does not allocate extra `coded_extent` right/bottom padding; requires `visible_rect.(x, y) == (0, 0)`).
919    ///
920    /// For non-zero crop origins or padded coded frames, construct a [`PlanarViewMut`] over your
921    /// own backing planes and call [`execute`](Self::execute).
922    pub fn capture_to_buf(
923        &self,
924        src: PixelView<'_>,
925        scratch: &mut CaptureScratch<'_>,
926    ) -> Result<PlanarBuf, At<ConvertError>> {
927        self.capture_to_buf_with_pulse(src, scratch, None)
928    }
929
930    /// Allocate a tagged [`PlanarBuf`] covering the zero-origin [`visible_rect`](PlanarCaptureSpec::visible_rect)
931    /// with optional cooperative cancellation and row progress via `pulse` (pass `None` when not needed).
932    pub fn capture_to_buf_with_pulse(
933        &self,
934        src: PixelView<'_>,
935        scratch: &mut CaptureScratch<'_>,
936        pulse: Option<&dyn Pulse>,
937    ) -> Result<PlanarBuf, At<ConvertError>> {
938        let pulse = live_pulse(pulse);
939        check_pulse(pulse)?;
940        let vis = self.spec.visible_rect;
941        if vis.x != 0 || vis.y != 0 {
942            return Err(err_at(ConvertError::UnsupportedRoute));
943        }
944        let hdr = if self.dst_can_represent_hdr {
945            src.hdr()
946        } else {
947            HdrMetadata::default()
948        };
949        let mut out = PlanarBuf::new(vis.width, vis.height, &self.spec.planes)
950            .map_err(|e| err_at((*e.error()).into()))?
951            .with_chroma_siting(self.resolved_siting)
952            .with_color(self.dst_color.clone())
953            .with_matrix_coefficients(self.spec.signal.matrix())
954            .with_range_override(self.range)
955            .with_hdr(hdr)
956            .with_orientation(src.orientation());
957        if self.dst_color.alpha() != AlphaMode::None {
958            out = out.with_alpha_override(self.dst_color.alpha());
959        }
960        if let Some(origin) = src.origin() {
961            out = out.with_origin(origin.clone());
962        }
963        {
964            let mut view_mut = out
965                .try_cow_view_mut()
966                .map_err(|e| err_at((*e.error()).into()))?;
967            self.execute_with_pulse(src, &mut view_mut, scratch, pulse)?;
968        }
969        Ok(out)
970    }
971
972    #[allow(clippy::too_many_arguments)]
973    fn exec_monochrome(
974        &self,
975        src: &PixelView<'_>,
976        dst: &mut PlanarViewMut<'_>,
977        ring: &mut [f64],
978        row_floats: usize,
979        y_idx: usize,
980        alpha_idx: Option<usize>,
981        pulse: Option<&dyn Pulse>,
982    ) -> Result<(), At<ConvertError>> {
983        let vis = self.spec.visible_rect;
984        let y_spec = self.spec.planes[y_idx];
985        let a_spec = alpha_idx.map(|i| self.spec.planes[i]);
986        let (y_off, y_span, y_lo, y_hi) = luma_encode_params(y_spec, self.range)?;
987        let a_params = a_spec.map(alpha_encode_params);
988        let inter_ch = self.inter_channels;
989        let f32_bytes = row_floats * core::mem::size_of::<f32>();
990
991        let row_buf = &mut ring[..row_floats];
992        for y in 0..vis.height {
993            self.row_plan.convert_row_at(
994                y,
995                src.row(y),
996                &mut bytemuck::cast_slice_mut::<f64, u8>(row_buf)[..f32_bytes],
997                vis.width,
998            )?;
999            let row_f32: &[f32] = &bytemuck::cast_slice::<f64, f32>(row_buf)[..row_floats];
1000            let planes = dst.planes_mut();
1001            let y_row = planes[y_idx].row_mut(y);
1002            for x in 0..vis.width as usize {
1003                let v = f64::from(row_f32[x * inter_ch]).clamp(0.0, 1.0);
1004                let code = quantize_code(
1005                    y_off + v * y_span,
1006                    y_lo,
1007                    y_hi,
1008                    self.depth_policy,
1009                    vis.x as usize + x,
1010                    vis.y as usize + y as usize,
1011                );
1012                write_plane_code(y_spec, y_row, x, 0, code);
1013            }
1014            if let (Some(ai), Some((a_s, a_max))) = (alpha_idx, a_params) {
1015                let a_row = planes[ai].row_mut(y);
1016                for x in 0..vis.width as usize {
1017                    let a = row_f32[x * inter_ch + 1];
1018                    write_alpha_sample(
1019                        a_s,
1020                        a_max,
1021                        a_row,
1022                        x,
1023                        a,
1024                        self.depth_policy,
1025                        vis.x as usize + x,
1026                        vis.y as usize + y as usize,
1027                    );
1028                }
1029            }
1030            step_pulse(pulse, 1)?;
1031        }
1032        Ok(())
1033    }
1034
1035    #[allow(clippy::too_many_arguments)]
1036    fn exec_planar_rgb(
1037        &self,
1038        src: &PixelView<'_>,
1039        dst: &mut PlanarViewMut<'_>,
1040        ring: &mut [f64],
1041        row_floats: usize,
1042        r_idx: usize,
1043        g_idx: usize,
1044        b_idx: usize,
1045        alpha_idx: Option<usize>,
1046        pulse: Option<&dyn Pulse>,
1047    ) -> Result<(), At<ConvertError>> {
1048        let vis = self.spec.visible_rect;
1049        let r_spec = self.spec.planes[r_idx];
1050        let g_spec = self.spec.planes[g_idx];
1051        let b_spec = self.spec.planes[b_idx];
1052        let a_spec = alpha_idx.map(|i| self.spec.planes[i]);
1053        let r_p = luma_encode_params(r_spec, self.range)?;
1054        let g_p = luma_encode_params(g_spec, self.range)?;
1055        let b_p = luma_encode_params(b_spec, self.range)?;
1056        let r_pi = luma_encode_params_int(r_spec, self.range)?;
1057        let g_pi = luma_encode_params_int(g_spec, self.range)?;
1058        let b_pi = luma_encode_params_int(b_spec, self.range)?;
1059        let a_p = a_spec.map(alpha_encode_params);
1060        let inter_ch = self.inter_channels;
1061        let f32_bytes = row_floats * core::mem::size_of::<f32>();
1062
1063        let row_buf = &mut ring[..row_floats];
1064        for y in 0..vis.height {
1065            let src_row = src.row(y);
1066            let gy = vis.y as usize + y as usize;
1067            if let Some(direct) = self.direct_int_rgb {
1068                let planes = dst.planes_mut();
1069                for x in 0..vis.width as usize {
1070                    let gx = vis.x as usize + x;
1071                    let (ri, gi, bi, ai_v, max_in) = read_direct_rgb_int(direct, src_row, x);
1072                    write_rgb_plane_sample_int(
1073                        r_spec,
1074                        r_pi,
1075                        planes[r_idx].row_mut(y),
1076                        x,
1077                        ri,
1078                        max_in,
1079                        self.depth_policy,
1080                        gx,
1081                        gy,
1082                    );
1083                    write_rgb_plane_sample_int(
1084                        g_spec,
1085                        g_pi,
1086                        planes[g_idx].row_mut(y),
1087                        x,
1088                        gi,
1089                        max_in,
1090                        self.depth_policy,
1091                        gx,
1092                        gy,
1093                    );
1094                    write_rgb_plane_sample_int(
1095                        b_spec,
1096                        b_pi,
1097                        planes[b_idx].row_mut(y),
1098                        x,
1099                        bi,
1100                        max_in,
1101                        self.depth_policy,
1102                        gx,
1103                        gy,
1104                    );
1105                    if let (Some(ai), Some((a_s, a_max))) = (alpha_idx, a_p) {
1106                        write_alpha_sample_int(
1107                            a_s,
1108                            a_max,
1109                            planes[ai].row_mut(y),
1110                            x,
1111                            ai_v,
1112                            max_in,
1113                            self.depth_policy,
1114                            gx,
1115                            gy,
1116                        );
1117                    }
1118                }
1119                step_pulse(pulse, 1)?;
1120                continue;
1121            }
1122
1123            self.row_plan.convert_row_at(
1124                y,
1125                src_row,
1126                &mut bytemuck::cast_slice_mut::<f64, u8>(row_buf)[..f32_bytes],
1127                vis.width,
1128            )?;
1129            let row_f32: &[f32] = &bytemuck::cast_slice::<f64, f32>(row_buf)[..row_floats];
1130            let planes = dst.planes_mut();
1131            {
1132                let r_row = planes[r_idx].row_mut(y);
1133                for x in 0..vis.width as usize {
1134                    write_rgb_plane_sample(
1135                        r_spec,
1136                        r_p,
1137                        r_row,
1138                        x,
1139                        row_f32[x * inter_ch],
1140                        self.depth_policy,
1141                        vis.x as usize + x,
1142                        gy,
1143                    );
1144                }
1145            }
1146            {
1147                let g_row = planes[g_idx].row_mut(y);
1148                for x in 0..vis.width as usize {
1149                    write_rgb_plane_sample(
1150                        g_spec,
1151                        g_p,
1152                        g_row,
1153                        x,
1154                        row_f32[x * inter_ch + 1],
1155                        self.depth_policy,
1156                        vis.x as usize + x,
1157                        gy,
1158                    );
1159                }
1160            }
1161            {
1162                let b_row = planes[b_idx].row_mut(y);
1163                for x in 0..vis.width as usize {
1164                    write_rgb_plane_sample(
1165                        b_spec,
1166                        b_p,
1167                        b_row,
1168                        x,
1169                        row_f32[x * inter_ch + 2],
1170                        self.depth_policy,
1171                        vis.x as usize + x,
1172                        gy,
1173                    );
1174                }
1175            }
1176            if let (Some(ai), Some((a_s, a_max))) = (alpha_idx, a_p) {
1177                let a_row = planes[ai].row_mut(y);
1178                for x in 0..vis.width as usize {
1179                    write_alpha_sample(
1180                        a_s,
1181                        a_max,
1182                        a_row,
1183                        x,
1184                        row_f32[x * inter_ch + 3],
1185                        self.depth_policy,
1186                        vis.x as usize + x,
1187                        gy,
1188                    );
1189                }
1190            }
1191            step_pulse(pulse, 1)?;
1192        }
1193        Ok(())
1194    }
1195
1196    #[allow(clippy::too_many_arguments)]
1197    fn exec_ycbcr(
1198        &self,
1199        src: &PixelView<'_>,
1200        dst: &mut PlanarViewMut<'_>,
1201        ring: &mut [f64],
1202        row_floats: usize,
1203        y_idx: usize,
1204        chroma_dst: YcbcrDstIndices,
1205        alpha_idx: Option<usize>,
1206        pulse: Option<&dyn Pulse>,
1207    ) -> Result<(), At<ConvertError>> {
1208        let vis = self.spec.visible_rect;
1209        let y_spec = self.spec.planes[y_idx];
1210        let (cb_spec, cr_spec, cb_comp, cr_comp) = match chroma_dst {
1211            YcbcrDstIndices::Planar { cb_idx, cr_idx } => (
1212                self.spec.planes[cb_idx],
1213                self.spec.planes[cr_idx],
1214                0usize,
1215                0usize,
1216            ),
1217            YcbcrDstIndices::Semi { uv_idx, swapped } => {
1218                let s = self.spec.planes[uv_idx];
1219                (s, s, usize::from(swapped), usize::from(!swapped))
1220            }
1221        };
1222
1223        let (y_off, y_span, y_lo, y_hi) = luma_encode_params(y_spec, self.range)?;
1224        let (cb_mid, cb_span, cb_lo, cb_hi) = match self.matrix {
1225            ForwardMatrix::Identity => luma_encode_params(cb_spec, self.range)?,
1226            _ => chroma_encode_params(cb_spec, cb_comp, self.range)?,
1227        };
1228        let (cr_mid, cr_span, cr_lo, cr_hi) = match self.matrix {
1229            ForwardMatrix::Identity => luma_encode_params(cr_spec, self.range)?,
1230            _ => chroma_encode_params(cr_spec, cr_comp, self.range)?,
1231        };
1232        let (y_off_i, y_span_i, _, _) = luma_encode_params_int(y_spec, self.range)?;
1233        let (cb_mid_i, cb_span_i, _, _) = match self.matrix {
1234            ForwardMatrix::Identity => luma_encode_params_int(cb_spec, self.range)?,
1235            _ => chroma_encode_params_int(cb_spec, cb_comp, self.range)?,
1236        };
1237        let (cr_mid_i, cr_span_i, _, _) = match self.matrix {
1238            ForwardMatrix::Identity => luma_encode_params_int(cr_spec, self.range)?,
1239            _ => chroma_encode_params_int(cr_spec, cr_comp, self.range)?,
1240        };
1241        let a_params = alpha_idx.map(|i| alpha_encode_params(self.spec.planes[i]));
1242
1243        let (cb_hx, cb_vy) = cb_spec.subsampling_divisors();
1244        let (cr_hx, cr_vy) = cr_spec.subsampling_divisors();
1245        let full_res_chroma = cb_hx == 1 && cb_vy == 1 && cr_hx == 1 && cr_vy == 1;
1246
1247        let (cb_w, cb_h) = cb_spec
1248            .cropped_plane_dimensions(vis)
1249            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1250        let (cr_w, cr_h) = cr_spec
1251            .cropped_plane_dimensions(vis)
1252            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1253
1254        let cb_ox0 = vis.x / u32::from(cb_hx);
1255        let cb_oy0 = vis.y / u32::from(cb_vy);
1256        let cr_ox0 = vis.x / u32::from(cr_hx);
1257        let cr_oy0 = vis.y / u32::from(cr_vy);
1258
1259        let (cb_dx, cb_dy) = self
1260            .resolved_siting
1261            .offset_in_luma_pixels_for_divisors(cb_hx, cb_vy)
1262            .unwrap_or((0.0, 0.0));
1263        let (cr_dx, cr_dy) = self
1264            .resolved_siting
1265            .offset_in_luma_pixels_for_divisors(cr_hx, cr_vy)
1266            .unwrap_or((0.0, 0.0));
1267
1268        let inter_ch = self.inter_channels;
1269        let f32_bytes = row_floats * core::mem::size_of::<f32>();
1270        let ring_rows = self.ring_rows;
1271        let mut next_cb_y = 0u32;
1272        let mut next_cr_y = 0u32;
1273        let semi_shared = matches!(chroma_dst, YcbcrDstIndices::Semi { .. });
1274
1275        let exact_chroma_denoms = self
1276            .direct_int_rgb
1277            .and_then(|d| chroma_int_denoms(self.matrix, if d.is_u16 { 65_535 } else { 255 }));
1278
1279        for y in 0..vis.height {
1280            let slot = (y as usize) % ring_rows;
1281            let slot_slice = &mut ring[slot * row_floats..(slot + 1) * row_floats];
1282            let src_row = src.row(y);
1283            if self.direct_int_rgb.is_none() {
1284                self.row_plan.convert_row_at(
1285                    y,
1286                    src_row,
1287                    &mut bytemuck::cast_slice_mut::<f64, u8>(slot_slice)[..f32_bytes],
1288                    vis.width,
1289                )?;
1290            }
1291
1292            let planes = dst.planes_mut();
1293            let gy = vis.y as usize + y as usize;
1294
1295            if full_res_chroma {
1296                if let Some(direct) = self.direct_int_rgb {
1297                    for x in 0..vis.width as usize {
1298                        let gx = vis.x as usize + x;
1299                        let (ri, gi, bi, ai_v, max_in) = read_direct_rgb_int(direct, src_row, x);
1300                        let (y_code, cb_code, cr_code) = match encode_ycbcr_exact_int(
1301                            self.matrix,
1302                            ri,
1303                            gi,
1304                            bi,
1305                            max_in,
1306                            (y_off_i, y_span_i, y_lo, y_hi),
1307                            (cb_mid_i, cb_span_i, cb_lo, cb_hi),
1308                            (cr_mid_i, cr_span_i, cr_lo, cr_hi),
1309                            self.depth_policy,
1310                            gx,
1311                            gy,
1312                        ) {
1313                            Some(codes) => codes,
1314                            None => {
1315                                let inv = 1.0 / (max_in as f64);
1316                                let (yn, cbn, crn) = apply_forward_matrix_f64(
1317                                    self.matrix,
1318                                    (ri as f64) * inv,
1319                                    (gi as f64) * inv,
1320                                    (bi as f64) * inv,
1321                                );
1322                                (
1323                                    quantize_code(
1324                                        y_off + yn * y_span,
1325                                        y_lo,
1326                                        y_hi,
1327                                        self.depth_policy,
1328                                        gx,
1329                                        gy,
1330                                    ),
1331                                    quantize_code(
1332                                        cb_mid + cbn * cb_span,
1333                                        cb_lo,
1334                                        cb_hi,
1335                                        self.depth_policy,
1336                                        gx,
1337                                        gy,
1338                                    ),
1339                                    quantize_code(
1340                                        cr_mid + crn * cr_span,
1341                                        cr_lo,
1342                                        cr_hi,
1343                                        self.depth_policy,
1344                                        gx,
1345                                        gy,
1346                                    ),
1347                                )
1348                            }
1349                        };
1350                        write_plane_code(y_spec, planes[y_idx].row_mut(y), x, 0, y_code);
1351                        match chroma_dst {
1352                            YcbcrDstIndices::Planar { cb_idx, cr_idx } => {
1353                                write_plane_code(cb_spec, planes[cb_idx].row_mut(y), x, 0, cb_code);
1354                                write_plane_code(cr_spec, planes[cr_idx].row_mut(y), x, 0, cr_code);
1355                            }
1356                            YcbcrDstIndices::Semi { uv_idx, swapped } => {
1357                                let (c0, c1) = if swapped {
1358                                    (cr_code, cb_code)
1359                                } else {
1360                                    (cb_code, cr_code)
1361                                };
1362                                write_semi_plane_pair(
1363                                    cb_spec,
1364                                    planes[uv_idx].row_mut(y),
1365                                    x,
1366                                    c0,
1367                                    c1,
1368                                );
1369                            }
1370                        }
1371                        if let (Some(ai), Some((a_s, a_max))) = (alpha_idx, a_params) {
1372                            write_alpha_sample_int(
1373                                a_s,
1374                                a_max,
1375                                planes[ai].row_mut(y),
1376                                x,
1377                                ai_v,
1378                                max_in,
1379                                self.depth_policy,
1380                                gx,
1381                                gy,
1382                            );
1383                        }
1384                    }
1385                } else {
1386                    let row_f32: &[f32] =
1387                        &bytemuck::cast_slice::<f64, f32>(slot_slice)[..row_floats];
1388                    for x in 0..vis.width as usize {
1389                        let base = x * inter_ch;
1390                        let r = f64::from(row_f32[base]).clamp(0.0, 1.0);
1391                        let g = f64::from(row_f32[base + 1]).clamp(0.0, 1.0);
1392                        let b = f64::from(row_f32[base + 2]).clamp(0.0, 1.0);
1393                        let (yn, cbn, crn) = apply_forward_matrix_f64(self.matrix, r, g, b);
1394                        let gx = vis.x as usize + x;
1395                        let y_code = quantize_code(
1396                            y_off + yn * y_span,
1397                            y_lo,
1398                            y_hi,
1399                            self.depth_policy,
1400                            gx,
1401                            gy,
1402                        );
1403                        let cb_code = quantize_code(
1404                            cb_mid + cbn * cb_span,
1405                            cb_lo,
1406                            cb_hi,
1407                            self.depth_policy,
1408                            gx,
1409                            gy,
1410                        );
1411                        let cr_code = quantize_code(
1412                            cr_mid + crn * cr_span,
1413                            cr_lo,
1414                            cr_hi,
1415                            self.depth_policy,
1416                            gx,
1417                            gy,
1418                        );
1419                        write_plane_code(y_spec, planes[y_idx].row_mut(y), x, 0, y_code);
1420                        match chroma_dst {
1421                            YcbcrDstIndices::Planar { cb_idx, cr_idx } => {
1422                                write_plane_code(cb_spec, planes[cb_idx].row_mut(y), x, 0, cb_code);
1423                                write_plane_code(cr_spec, planes[cr_idx].row_mut(y), x, 0, cr_code);
1424                            }
1425                            YcbcrDstIndices::Semi { uv_idx, swapped } => {
1426                                let (c0, c1) = if swapped {
1427                                    (cr_code, cb_code)
1428                                } else {
1429                                    (cb_code, cr_code)
1430                                };
1431                                write_semi_plane_pair(
1432                                    cb_spec,
1433                                    planes[uv_idx].row_mut(y),
1434                                    x,
1435                                    c0,
1436                                    c1,
1437                                );
1438                            }
1439                        }
1440                        if let (Some(ai), Some((a_s, a_max))) = (alpha_idx, a_params) {
1441                            write_alpha_sample(
1442                                a_s,
1443                                a_max,
1444                                planes[ai].row_mut(y),
1445                                x,
1446                                row_f32[base + 3],
1447                                self.depth_policy,
1448                                gx,
1449                                gy,
1450                            );
1451                        }
1452                    }
1453                }
1454                step_pulse(pulse, 1)?;
1455                continue;
1456            }
1457
1458            // Subsampled chroma path: exact rational/f64 luma write + store full precision
1459            // in the f64 ring buffer. When `exact_chroma_denoms` is Some, store exact integer
1460            // chroma numerators (|numer| <= 6.55e8 << 2^53, 100% lossless in f64) so integer
1461            // tap kernels accumulate and quantize in exact i128 rational arithmetic with zero
1462            // tie drift!
1463            if let Some(direct) = self.direct_int_rgb {
1464                {
1465                    let y_row = planes[y_idx].row_mut(y);
1466                    for x in 0..vis.width as usize {
1467                        let base = x * inter_ch;
1468                        let gx = vis.x as usize + x;
1469                        let (ri, gi, bi, ai_v, max_in) = read_direct_rgb_int(direct, src_row, x);
1470                        if let Some((cb_n, cr_n)) = exact_chroma_numerators(self.matrix, ri, gi, bi)
1471                        {
1472                            slot_slice[base] = 0.0;
1473                            slot_slice[base + 1] = cb_n as f64;
1474                            slot_slice[base + 2] = cr_n as f64;
1475                        } else {
1476                            let (yn, cbn, crn) =
1477                                apply_forward_matrix_int_to_f64(self.matrix, ri, gi, bi, max_in);
1478                            slot_slice[base] = yn;
1479                            slot_slice[base + 1] = cbn;
1480                            slot_slice[base + 2] = crn;
1481                        }
1482                        if inter_ch > 3 {
1483                            slot_slice[base + 3] = (ai_v as f64) / (max_in as f64);
1484                        }
1485                        let y_code = match encode_luma_exact_int(
1486                            self.matrix,
1487                            ri,
1488                            gi,
1489                            bi,
1490                            max_in,
1491                            (y_off_i, y_span_i, y_lo, y_hi),
1492                            self.depth_policy,
1493                            gx,
1494                            gy,
1495                        ) {
1496                            Some(code) => code,
1497                            None => quantize_code(
1498                                y_off + slot_slice[base] * y_span,
1499                                y_lo,
1500                                y_hi,
1501                                self.depth_policy,
1502                                gx,
1503                                gy,
1504                            ),
1505                        };
1506                        write_plane_code(y_spec, y_row, x, 0, y_code);
1507                    }
1508                }
1509                if let (Some(ai), Some((a_s, a_max))) = (alpha_idx, a_params) {
1510                    let a_row = planes[ai].row_mut(y);
1511                    for x in 0..vis.width as usize {
1512                        let (_, _, _, ai_v, max_in) = read_direct_rgb_int(direct, src_row, x);
1513                        write_alpha_sample_int(
1514                            a_s,
1515                            a_max,
1516                            a_row,
1517                            x,
1518                            ai_v,
1519                            max_in,
1520                            self.depth_policy,
1521                            vis.x as usize + x,
1522                            gy,
1523                        );
1524                    }
1525                }
1526            } else {
1527                // In-place reverse widening from Stage 1's f32 prefix [0..row_floats*4B]
1528                // into full f64 [0..row_floats*8B].
1529                let y_row = planes[y_idx].row_mut(y);
1530                for x in (0..vis.width as usize).rev() {
1531                    let base = x * inter_ch;
1532                    let (r, g, b, a_f) = {
1533                        let f32s = bytemuck::cast_slice::<f64, f32>(slot_slice);
1534                        let r = f64::from(f32s[base]).clamp(0.0, 1.0);
1535                        let g = f64::from(f32s[base + 1]).clamp(0.0, 1.0);
1536                        let b = f64::from(f32s[base + 2]).clamp(0.0, 1.0);
1537                        let a_f = if inter_ch > 3 {
1538                            f64::from(f32s[base + 3])
1539                        } else {
1540                            1.0
1541                        };
1542                        (r, g, b, a_f)
1543                    };
1544                    let (yn, cbn, crn) = apply_forward_matrix_f64(self.matrix, r, g, b);
1545                    slot_slice[base] = yn;
1546                    slot_slice[base + 1] = cbn;
1547                    slot_slice[base + 2] = crn;
1548                    if inter_ch > 3 {
1549                        slot_slice[base + 3] = a_f;
1550                    }
1551                    let y_code = quantize_code(
1552                        y_off + yn * y_span,
1553                        y_lo,
1554                        y_hi,
1555                        self.depth_policy,
1556                        vis.x as usize + x,
1557                        gy,
1558                    );
1559                    write_plane_code(y_spec, y_row, x, 0, y_code);
1560                }
1561                if let (Some(ai), Some((a_s, a_max))) = (alpha_idx, a_params) {
1562                    let a_row = planes[ai].row_mut(y);
1563                    for x in 0..vis.width as usize {
1564                        write_alpha_sample_f64(
1565                            a_s,
1566                            a_max,
1567                            a_row,
1568                            x,
1569                            slot_slice[x * inter_ch + 3],
1570                            self.depth_policy,
1571                            vis.x as usize + x,
1572                            gy,
1573                        );
1574                    }
1575                }
1576            }
1577
1578            let is_last_row = y + 1 == vis.height;
1579
1580            if semi_shared {
1581                let YcbcrDstIndices::Semi { uv_idx, swapped } = chroma_dst else {
1582                    unreachable!()
1583                };
1584                while next_cb_y < cb_h {
1585                    let vtaps = axis_downsample_taps(
1586                        cb_oy0 + next_cb_y,
1587                        cb_vy,
1588                        cb_dy,
1589                        vis.y,
1590                        vis.height,
1591                        self.options.downsample,
1592                    );
1593                    if !is_last_row && vtaps.max_idx > y {
1594                        break;
1595                    }
1596                    let uv_row = planes[uv_idx].row_mut(next_cb_y);
1597                    let gcy = (cb_oy0 + next_cb_y) as usize;
1598                    for cx in 0..cb_w {
1599                        let htaps = axis_downsample_taps(
1600                            cb_ox0 + cx,
1601                            cb_hx,
1602                            cb_dx,
1603                            vis.x,
1604                            vis.width,
1605                            self.options.downsample,
1606                        );
1607                        let gcx = (cb_ox0 + cx) as usize;
1608                        let (cb_code, cr_code) = if let (
1609                            Some((cb_base_den, cr_base_den)),
1610                            Some((vw, vsum)),
1611                            Some((hw, hsum)),
1612                        ) =
1613                            (exact_chroma_denoms, vtaps.int_weights, htaps.int_weights)
1614                        {
1615                            let (acc_cb, acc_cr) = downsample_2ch_ring_int(
1616                                ring, ring_rows, row_floats, inter_ch, &vtaps, &vw, &htaps, &hw,
1617                            );
1618                            let w_den = i128::from(vsum) * i128::from(hsum);
1619                            let cb_den = cb_base_den * w_den;
1620                            let cr_den = cr_base_den * w_den;
1621                            let cb_code = quantize_rational(
1622                                cb_mid_i * cb_den + acc_cb * cb_span_i,
1623                                cb_den,
1624                                cb_lo,
1625                                cb_hi,
1626                                self.depth_policy,
1627                                gcx,
1628                                gcy,
1629                            );
1630                            let cr_code = quantize_rational(
1631                                cr_mid_i * cr_den + acc_cr * cr_span_i,
1632                                cr_den,
1633                                cr_lo,
1634                                cr_hi,
1635                                self.depth_policy,
1636                                gcx,
1637                                gcy,
1638                            );
1639                            (cb_code, cr_code)
1640                        } else {
1641                            let (mut cbv, mut crv) = downsample_2ch_ring(
1642                                ring, ring_rows, row_floats, inter_ch, &vtaps, &htaps,
1643                            );
1644                            if let Some((cb_base_den, cr_base_den)) = exact_chroma_denoms {
1645                                cbv /= cb_base_den as f64;
1646                                crv /= cr_base_den as f64;
1647                            }
1648                            (
1649                                quantize_code(
1650                                    cb_mid + cbv * cb_span,
1651                                    cb_lo,
1652                                    cb_hi,
1653                                    self.depth_policy,
1654                                    gcx,
1655                                    gcy,
1656                                ),
1657                                quantize_code(
1658                                    cr_mid + crv * cr_span,
1659                                    cr_lo,
1660                                    cr_hi,
1661                                    self.depth_policy,
1662                                    gcx,
1663                                    gcy,
1664                                ),
1665                            )
1666                        };
1667                        let (c0, c1) = if swapped {
1668                            (cr_code, cb_code)
1669                        } else {
1670                            (cb_code, cr_code)
1671                        };
1672                        write_semi_plane_pair(cb_spec, uv_row, cx as usize, c0, c1);
1673                    }
1674                    next_cb_y += 1;
1675                }
1676            } else {
1677                let YcbcrDstIndices::Planar { cb_idx, cr_idx } = chroma_dst else {
1678                    unreachable!()
1679                };
1680                while next_cb_y < cb_h {
1681                    let vtaps = axis_downsample_taps(
1682                        cb_oy0 + next_cb_y,
1683                        cb_vy,
1684                        cb_dy,
1685                        vis.y,
1686                        vis.height,
1687                        self.options.downsample,
1688                    );
1689                    if !is_last_row && vtaps.max_idx > y {
1690                        break;
1691                    }
1692                    let cb_row = planes[cb_idx].row_mut(next_cb_y);
1693                    let gcy = (cb_oy0 + next_cb_y) as usize;
1694                    for cx in 0..cb_w {
1695                        let htaps = axis_downsample_taps(
1696                            cb_ox0 + cx,
1697                            cb_hx,
1698                            cb_dx,
1699                            vis.x,
1700                            vis.width,
1701                            self.options.downsample,
1702                        );
1703                        let gcx = (cb_ox0 + cx) as usize;
1704                        let cb_code =
1705                            if let (Some((cb_base_den, _)), Some((vw, vsum)), Some((hw, hsum))) =
1706                                (exact_chroma_denoms, vtaps.int_weights, htaps.int_weights)
1707                            {
1708                                let acc_cb = downsample_1ch_ring_int(
1709                                    ring, ring_rows, row_floats, inter_ch, 1, &vtaps, &vw, &htaps,
1710                                    &hw,
1711                                );
1712                                let cb_den = cb_base_den * i128::from(vsum) * i128::from(hsum);
1713                                quantize_rational(
1714                                    cb_mid_i * cb_den + acc_cb * cb_span_i,
1715                                    cb_den,
1716                                    cb_lo,
1717                                    cb_hi,
1718                                    self.depth_policy,
1719                                    gcx,
1720                                    gcy,
1721                                )
1722                            } else {
1723                                let mut cbv = downsample_1ch_ring(
1724                                    ring, ring_rows, row_floats, inter_ch, 1, &vtaps, &htaps,
1725                                );
1726                                if let Some((cb_base_den, _)) = exact_chroma_denoms {
1727                                    cbv /= cb_base_den as f64;
1728                                }
1729                                quantize_code(
1730                                    cb_mid + cbv * cb_span,
1731                                    cb_lo,
1732                                    cb_hi,
1733                                    self.depth_policy,
1734                                    gcx,
1735                                    gcy,
1736                                )
1737                            };
1738                        write_plane_code(cb_spec, cb_row, cx as usize, 0, cb_code);
1739                    }
1740                    next_cb_y += 1;
1741                }
1742                while next_cr_y < cr_h {
1743                    let vtaps = axis_downsample_taps(
1744                        cr_oy0 + next_cr_y,
1745                        cr_vy,
1746                        cr_dy,
1747                        vis.y,
1748                        vis.height,
1749                        self.options.downsample,
1750                    );
1751                    if !is_last_row && vtaps.max_idx > y {
1752                        break;
1753                    }
1754                    let cr_row = planes[cr_idx].row_mut(next_cr_y);
1755                    let gcy = (cr_oy0 + next_cr_y) as usize;
1756                    for cx in 0..cr_w {
1757                        let htaps = axis_downsample_taps(
1758                            cr_ox0 + cx,
1759                            cr_hx,
1760                            cr_dx,
1761                            vis.x,
1762                            vis.width,
1763                            self.options.downsample,
1764                        );
1765                        let gcx = (cr_ox0 + cx) as usize;
1766                        let cr_code =
1767                            if let (Some((_, cr_base_den)), Some((vw, vsum)), Some((hw, hsum))) =
1768                                (exact_chroma_denoms, vtaps.int_weights, htaps.int_weights)
1769                            {
1770                                let acc_cr = downsample_1ch_ring_int(
1771                                    ring, ring_rows, row_floats, inter_ch, 2, &vtaps, &vw, &htaps,
1772                                    &hw,
1773                                );
1774                                let cr_den = cr_base_den * i128::from(vsum) * i128::from(hsum);
1775                                quantize_rational(
1776                                    cr_mid_i * cr_den + acc_cr * cr_span_i,
1777                                    cr_den,
1778                                    cr_lo,
1779                                    cr_hi,
1780                                    self.depth_policy,
1781                                    gcx,
1782                                    gcy,
1783                                )
1784                            } else {
1785                                let mut crv = downsample_1ch_ring(
1786                                    ring, ring_rows, row_floats, inter_ch, 2, &vtaps, &htaps,
1787                                );
1788                                if let Some((_, cr_base_den)) = exact_chroma_denoms {
1789                                    crv /= cr_base_den as f64;
1790                                }
1791                                quantize_code(
1792                                    cr_mid + crv * cr_span,
1793                                    cr_lo,
1794                                    cr_hi,
1795                                    self.depth_policy,
1796                                    gcx,
1797                                    gcy,
1798                                )
1799                            };
1800                        write_plane_code(cr_spec, cr_row, cx as usize, 0, cr_code);
1801                    }
1802                    next_cr_y += 1;
1803                }
1804            }
1805            step_pulse(pulse, 1)?;
1806        }
1807
1808        Ok(())
1809    }
1810}
1811
1812#[inline(always)]
1813fn apply_forward_matrix_f64(matrix: ForwardMatrix, r: f64, g: f64, b: f64) -> (f64, f64, f64) {
1814    match matrix {
1815        ForwardMatrix::Identity => (g, b, r),
1816        ForwardMatrix::YCgCo => {
1817            let co = 0.5 * (r - b);
1818            let t = b + co;
1819            let cg = 0.5 * (g - t);
1820            let yv = t + cg;
1821            (yv, cg, co)
1822        }
1823        ForwardMatrix::Ncl {
1824            kr,
1825            kg,
1826            kb,
1827            inv_2_1_minus_kb,
1828            inv_2_1_minus_kr,
1829            ..
1830        } => {
1831            let yv = kr * r + kg * g + kb * b;
1832            let cbv = ((b - yv) * inv_2_1_minus_kb).clamp(-0.5, 0.5);
1833            let crv = ((r - yv) * inv_2_1_minus_kr).clamp(-0.5, 0.5);
1834            (yv, cbv, crv)
1835        }
1836    }
1837}
1838
1839#[derive(Clone, Copy)]
1840enum YcbcrDstIndices {
1841    Planar { cb_idx: usize, cr_idx: usize },
1842    Semi { uv_idx: usize, swapped: bool },
1843}
1844
1845/// Up to 8 taps for 1D downsampling (covers factors 1, 2, and 4 with triangle/box kernels).
1846#[derive(Clone, Copy)]
1847struct AxisTaps {
1848    indices: [u32; 8],
1849    weights: [f64; 8],
1850    /// Exact integer `(weights, weight_sum)` when kernel weights are exact rational fractions
1851    /// (all standard half-integer H.273 chroma sitings, `BoxAverage`, `Nearest`, and `1×`).
1852    int_weights: Option<([i64; 8], i64)>,
1853    len: usize,
1854    max_idx: u32,
1855}
1856
1857#[inline]
1858fn axis_downsample_taps(
1859    global_chroma_idx: u32,
1860    factor: u8,
1861    offset_in_cell: f32,
1862    vis_origin: u32,
1863    vis_len: u32,
1864    mode: ChromaDownsample,
1865) -> AxisTaps {
1866    let f = u32::from(factor.max(1));
1867    let max_local = vis_len.saturating_sub(1);
1868    if f == 1 {
1869        let idx = global_chroma_idx.saturating_sub(vis_origin).min(max_local);
1870        return AxisTaps {
1871            indices: [idx, 0, 0, 0, 0, 0, 0, 0],
1872            weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
1873            int_weights: Some(([1, 0, 0, 0, 0, 0, 0, 0], 1)),
1874            len: 1,
1875            max_idx: idx,
1876        };
1877    }
1878
1879    // Compute sample center in *local* visible coordinates using exact i64 integer difference
1880    // BEFORE adding the fractional siting offset in f64 — immune to f32 precision loss even
1881    // at coded crop origins >= 2^24!
1882    let base_local: i64 = i64::from(global_chroma_idx) * i64::from(f) - i64::from(vis_origin);
1883    let clamp_local = |rel: i64| -> u32 {
1884        if rel <= 0 {
1885            0
1886        } else if rel >= i64::from(max_local) {
1887            max_local
1888        } else {
1889            rel as u32
1890        }
1891    };
1892
1893    match mode {
1894        ChromaDownsample::Nearest => {
1895            let center_local = (base_local as f64) + f64::from(offset_in_cell);
1896            let rel = libm::floor(center_local + 0.5) as i64;
1897            let idx = clamp_local(rel);
1898            AxisTaps {
1899                indices: [idx, 0, 0, 0, 0, 0, 0, 0],
1900                weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
1901                int_weights: Some(([1, 0, 0, 0, 0, 0, 0, 0], 1)),
1902                len: 1,
1903                max_idx: idx,
1904            }
1905        }
1906        ChromaDownsample::BoxAverage => {
1907            let mut indices = [0u32; 8];
1908            let mut weights = [0.0f64; 8];
1909            let mut iw = [0i64; 8];
1910            let count = (f as usize).min(8);
1911            let w = 1.0 / (count as f64);
1912            let mut max_idx = 0u32;
1913            for i in 0..count {
1914                let idx = clamp_local(base_local + i as i64);
1915                indices[i] = idx;
1916                weights[i] = w;
1917                iw[i] = 1;
1918                if idx > max_idx {
1919                    max_idx = idx;
1920                }
1921            }
1922            AxisTaps {
1923                indices,
1924                weights,
1925                int_weights: Some((iw, count as i64)),
1926                len: count,
1927                max_idx,
1928            }
1929        }
1930        ChromaDownsample::SitingAware => {
1931            // Continuous triangle kernel of half-width `f` centered at `base_local + offset`.
1932            // Exact `[1, 2, 1]/4` for co-sited 2×, `[1, 3, 3, 1]/8` for centered 2×,
1933            // `[1, 2, 3, 4, 3, 2, 1]/16` for co-sited 4×, `[1, 3, 5, 7, 7, 5, 3, 1]/32` for centered 4×.
1934            let offset_2x = f64::from(offset_in_cell) * 2.0;
1935            let offset_2x_round = libm::round(offset_2x);
1936            let is_half_int = libm::fabs(offset_2x - offset_2x_round) == 0.0;
1937            let center_2x: i64 = base_local * 2 + (offset_2x_round as i64);
1938            let radius_2x: i64 = i64::from(f) * 2;
1939
1940            let center_local = (base_local as f64) + f64::from(offset_in_cell);
1941            let radius = f64::from(f);
1942            let k_start = libm::floor(center_local - radius) as i64 + 1;
1943            let k_end = libm::ceil(center_local + radius) as i64 - 1;
1944            let mut indices = [0u32; 8];
1945            let mut weights = [0.0f64; 8];
1946            let mut iw = [0i64; 8];
1947            let mut iw_sum = 0i64;
1948            let mut len = 0usize;
1949            let mut sum = 0.0f64;
1950            let mut max_idx = 0u32;
1951            let mut k = k_start;
1952            while k <= k_end && len < 8 {
1953                let dist = libm::fabs((k as f64) - center_local);
1954                let w = 1.0 - dist / radius;
1955                if w > 0.0 {
1956                    let idx = clamp_local(k);
1957                    indices[len] = idx;
1958                    weights[len] = w;
1959                    sum += w;
1960                    if is_half_int {
1961                        let wi = radius_2x - (2 * k - center_2x).abs();
1962                        iw[len] = wi;
1963                        iw_sum += wi;
1964                    }
1965                    if idx > max_idx {
1966                        max_idx = idx;
1967                    }
1968                    len += 1;
1969                }
1970                k += 1;
1971            }
1972            if len == 0 || sum <= 0.0 {
1973                let idx = clamp_local(libm::floor(center_local + 0.5) as i64);
1974                return AxisTaps {
1975                    indices: [idx, 0, 0, 0, 0, 0, 0, 0],
1976                    weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
1977                    int_weights: Some(([1, 0, 0, 0, 0, 0, 0, 0], 1)),
1978                    len: 1,
1979                    max_idx: idx,
1980                };
1981            }
1982            let inv_sum = 1.0 / sum;
1983            for w in &mut weights[..len] {
1984                *w *= inv_sum;
1985            }
1986            AxisTaps {
1987                indices,
1988                weights,
1989                int_weights: if is_half_int && iw_sum > 0 {
1990                    Some((iw, iw_sum))
1991                } else {
1992                    None
1993                },
1994                len,
1995                max_idx,
1996            }
1997        }
1998    }
1999}
2000
2001#[inline(always)]
2002fn chroma_int_denoms(matrix: ForwardMatrix, max_in: i128) -> Option<(i128, i128)> {
2003    match matrix {
2004        ForwardMatrix::YCgCo => Some((4 * max_in, 2 * max_in)),
2005        ForwardMatrix::Ncl {
2006            exact_rational: Some((kr, _, kb, k_den)),
2007            ..
2008        } => Some((2 * (k_den - kb) * max_in, 2 * (k_den - kr) * max_in)),
2009        _ => None,
2010    }
2011}
2012
2013#[inline(always)]
2014fn exact_chroma_numerators(
2015    matrix: ForwardMatrix,
2016    r: i128,
2017    g: i128,
2018    b: i128,
2019) -> Option<(i128, i128)> {
2020    match matrix {
2021        ForwardMatrix::YCgCo => Some((2 * g - r - b, r - b)),
2022        ForwardMatrix::Ncl {
2023            exact_rational: Some((kr, kg, kb, k_den)),
2024            ..
2025        } => {
2026            let y_sum = kr * r + kg * g + kb * b;
2027            Some((k_den * b - y_sum, k_den * r - y_sum))
2028        }
2029        _ => None,
2030    }
2031}
2032
2033#[inline]
2034#[allow(clippy::too_many_arguments)]
2035fn downsample_1ch_ring_int(
2036    ring: &[f64],
2037    ring_rows: usize,
2038    row_floats: usize,
2039    inter_ch: usize,
2040    ch_offset: usize,
2041    vtaps: &AxisTaps,
2042    vw: &[i64; 8],
2043    htaps: &AxisTaps,
2044    hw: &[i64; 8],
2045) -> i128 {
2046    let mut acc = 0i128;
2047    for (&vidx, &w_v) in vtaps.indices[..vtaps.len].iter().zip(&vw[..vtaps.len]) {
2048        let wy = i128::from(w_v);
2049        let row_slot = (vidx as usize) % ring_rows;
2050        let row_base = row_slot * row_floats + ch_offset;
2051        let mut h_acc = 0i128;
2052        for (&hidx, &w_h) in htaps.indices[..htaps.len].iter().zip(&hw[..htaps.len]) {
2053            let x = hidx as usize;
2054            h_acc += (ring[row_base + x * inter_ch] as i128) * i128::from(w_h);
2055        }
2056        acc += h_acc * wy;
2057    }
2058    acc
2059}
2060
2061#[inline]
2062#[allow(clippy::too_many_arguments)]
2063fn downsample_2ch_ring_int(
2064    ring: &[f64],
2065    ring_rows: usize,
2066    row_floats: usize,
2067    inter_ch: usize,
2068    vtaps: &AxisTaps,
2069    vw: &[i64; 8],
2070    htaps: &AxisTaps,
2071    hw: &[i64; 8],
2072) -> (i128, i128) {
2073    let mut acc_cb = 0i128;
2074    let mut acc_cr = 0i128;
2075    for (&vidx, &w_v) in vtaps.indices[..vtaps.len].iter().zip(&vw[..vtaps.len]) {
2076        let wy = i128::from(w_v);
2077        let row_slot = (vidx as usize) % ring_rows;
2078        let row_base = row_slot * row_floats;
2079        let mut h_cb = 0i128;
2080        let mut h_cr = 0i128;
2081        for (&hidx, &w_h) in htaps.indices[..htaps.len].iter().zip(&hw[..htaps.len]) {
2082            let off = row_base + (hidx as usize) * inter_ch;
2083            let wx = i128::from(w_h);
2084            h_cb += (ring[off + 1] as i128) * wx;
2085            h_cr += (ring[off + 2] as i128) * wx;
2086        }
2087        acc_cb += h_cb * wy;
2088        acc_cr += h_cr * wy;
2089    }
2090    (acc_cb, acc_cr)
2091}
2092
2093#[inline]
2094fn downsample_1ch_ring(
2095    ring: &[f64],
2096    ring_rows: usize,
2097    row_floats: usize,
2098    inter_ch: usize,
2099    ch_offset: usize,
2100    vtaps: &AxisTaps,
2101    htaps: &AxisTaps,
2102) -> f64 {
2103    let mut acc = 0.0f64;
2104    for vi in 0..vtaps.len {
2105        let wy = vtaps.weights[vi];
2106        let row_slot = (vtaps.indices[vi] as usize) % ring_rows;
2107        let row_base = row_slot * row_floats + ch_offset;
2108        let mut h_acc = 0.0f64;
2109        for hi in 0..htaps.len {
2110            let x = htaps.indices[hi] as usize;
2111            h_acc += ring[row_base + x * inter_ch] * htaps.weights[hi];
2112        }
2113        acc += h_acc * wy;
2114    }
2115    acc
2116}
2117
2118#[inline]
2119fn downsample_2ch_ring(
2120    ring: &[f64],
2121    ring_rows: usize,
2122    row_floats: usize,
2123    inter_ch: usize,
2124    vtaps: &AxisTaps,
2125    htaps: &AxisTaps,
2126) -> (f64, f64) {
2127    let mut acc_cb = 0.0f64;
2128    let mut acc_cr = 0.0f64;
2129    for vi in 0..vtaps.len {
2130        let wy = vtaps.weights[vi];
2131        let row_slot = (vtaps.indices[vi] as usize) % ring_rows;
2132        let row_base = row_slot * row_floats;
2133        let mut h_cb = 0.0f64;
2134        let mut h_cr = 0.0f64;
2135        for hi in 0..htaps.len {
2136            let off = row_base + (htaps.indices[hi] as usize) * inter_ch;
2137            let wx = htaps.weights[hi];
2138            h_cb += ring[off + 1] * wx;
2139            h_cr += ring[off + 2] * wx;
2140        }
2141        acc_cb += h_cb * wy;
2142        acc_cr += h_cr * wy;
2143    }
2144    (acc_cb, acc_cr)
2145}
2146
2147#[allow(clippy::type_complexity)]
2148fn parse_target_planes(
2149    planes: &[PlaneFormat],
2150    vis: PixelRect,
2151) -> Result<(TargetLayout, bool, bool, bool, bool, u8, u8), At<ConvertError>> {
2152    let mut y_idx = None;
2153    let mut cb_idx = None;
2154    let mut cr_idx = None;
2155    let mut semi_idx = None;
2156    let mut r_idx = None;
2157    let mut g_idx = None;
2158    let mut b_idx = None;
2159    let mut alpha_idx = None;
2160
2161    for (i, &pf) in planes.iter().enumerate() {
2162        let (pw, ph) = pf
2163            .cropped_plane_dimensions(vis)
2164            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
2165        if pw == 0 || ph == 0 {
2166            return Err(err_at(ConvertError::DimensionMismatch));
2167        }
2168        let (hx, vy) = pf.subsampling_divisors();
2169        if hx > 4 || vy > 4 {
2170            return Err(err_at(ConvertError::UnsupportedRoute));
2171        }
2172        match pf.role() {
2173            PlaneRole::Y => {
2174                if y_idx.replace(i).is_some() {
2175                    return Err(err_at(ConvertError::UnsupportedRoute));
2176                }
2177            }
2178            PlaneRole::Cb => {
2179                if cb_idx.replace(i).is_some() {
2180                    return Err(err_at(ConvertError::UnsupportedRoute));
2181                }
2182            }
2183            PlaneRole::Cr => {
2184                if cr_idx.replace(i).is_some() {
2185                    return Err(err_at(ConvertError::UnsupportedRoute));
2186                }
2187            }
2188            PlaneRole::CbCr | PlaneRole::CrCb => {
2189                if semi_idx.replace(i).is_some() {
2190                    return Err(err_at(ConvertError::UnsupportedRoute));
2191                }
2192            }
2193            PlaneRole::R => {
2194                if r_idx.replace(i).is_some() {
2195                    return Err(err_at(ConvertError::UnsupportedRoute));
2196                }
2197            }
2198            PlaneRole::G => {
2199                if g_idx.replace(i).is_some() {
2200                    return Err(err_at(ConvertError::UnsupportedRoute));
2201                }
2202            }
2203            PlaneRole::B => {
2204                if b_idx.replace(i).is_some() {
2205                    return Err(err_at(ConvertError::UnsupportedRoute));
2206                }
2207            }
2208            PlaneRole::Alpha => {
2209                if alpha_idx.replace(i).is_some() {
2210                    return Err(err_at(ConvertError::UnsupportedRoute));
2211                }
2212            }
2213            _ => return Err(err_at(ConvertError::UnsupportedRoute)),
2214        }
2215    }
2216
2217    let check_plane = |pf: PlaneFormat,
2218                       expected_comp: u8,
2219                       full_res: bool,
2220                       allow_f32: bool|
2221     -> Result<u8, At<ConvertError>> {
2222        let sample_ok =
2223            matches!(
2224                pf.sample(),
2225                SampleType::U8 | SampleType::U16 | SampleType::U32
2226            ) || (allow_f32 && pf.sample() == SampleType::F32 && pf.packing().is_full());
2227        if !sample_ok || pf.components() != expected_comp {
2228            return Err(err_at(ConvertError::UnsupportedRoute));
2229        }
2230        if full_res && pf.subsampling_divisors() != (1, 1) {
2231            return Err(err_at(ConvertError::UnsupportedRoute));
2232        }
2233        if pf.sample() == SampleType::F32 {
2234            Ok(32)
2235        } else {
2236            let max_code = pf.packing().max_code(pf.sample(), 0);
2237            if max_code == 0 {
2238                return Err(err_at(ConvertError::UnsupportedRoute));
2239            }
2240            Ok((32 - max_code.leading_zeros()) as u8)
2241        }
2242    };
2243
2244    if let (Some(ri), Some(gi), Some(bi)) = (r_idx, g_idx, b_idx) {
2245        if y_idx.is_some() || cb_idx.is_some() || cr_idx.is_some() || semi_idx.is_some() {
2246            return Err(err_at(ConvertError::UnsupportedRoute));
2247        }
2248        let mut min_bits = check_plane(planes[ri], 1, true, true)?;
2249        min_bits = min_bits.min(check_plane(planes[gi], 1, true, true)?);
2250        min_bits = min_bits.min(check_plane(planes[bi], 1, true, true)?);
2251        if let Some(ai) = alpha_idx {
2252            min_bits = min_bits.min(check_plane(planes[ai], 1, true, true)?);
2253        }
2254        return Ok((
2255            TargetLayout::PlanarRgb {
2256                r_idx: ri,
2257                g_idx: gi,
2258                b_idx: bi,
2259                alpha_idx,
2260            },
2261            alpha_idx.is_some(),
2262            false,
2263            true,
2264            false,
2265            1,
2266            min_bits,
2267        ));
2268    }
2269    if r_idx.is_some() || g_idx.is_some() || b_idx.is_some() {
2270        return Err(err_at(ConvertError::UnsupportedRoute));
2271    }
2272
2273    let yi = y_idx.ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
2274    let mut min_bits = check_plane(planes[yi], 1, true, false)?;
2275    if let Some(ai) = alpha_idx {
2276        min_bits = min_bits.min(check_plane(planes[ai], 1, true, false)?);
2277    }
2278
2279    if let Some(si) = semi_idx {
2280        if cb_idx.is_some() || cr_idx.is_some() {
2281            return Err(err_at(ConvertError::UnsupportedRoute));
2282        }
2283        let pf = planes[si];
2284        min_bits = min_bits.min(check_plane(pf, 2, false, false)?);
2285        let (hx, vy) = pf.subsampling_divisors();
2286        let any_sub = hx > 1 || vy > 1;
2287        Ok((
2288            TargetLayout::YcbcrSemi {
2289                y_idx: yi,
2290                uv_idx: si,
2291                swapped: pf.role() == PlaneRole::CrCb,
2292                alpha_idx,
2293            },
2294            alpha_idx.is_some(),
2295            false,
2296            false,
2297            any_sub,
2298            vy,
2299            min_bits,
2300        ))
2301    } else if cb_idx.is_none() && cr_idx.is_none() {
2302        Ok((
2303            TargetLayout::Monochrome {
2304                y_idx: yi,
2305                alpha_idx,
2306            },
2307            alpha_idx.is_some(),
2308            true,
2309            false,
2310            false,
2311            1,
2312            min_bits,
2313        ))
2314    } else {
2315        let cbi = cb_idx.ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
2316        let cri = cr_idx.ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
2317        min_bits = min_bits.min(check_plane(planes[cbi], 1, false, false)?);
2318        min_bits = min_bits.min(check_plane(planes[cri], 1, false, false)?);
2319        let cb_sub = planes[cbi].subsampling_divisors();
2320        let cr_sub = planes[cri].subsampling_divisors();
2321        let any_sub = cb_sub.0 > 1 || cb_sub.1 > 1 || cr_sub.0 > 1 || cr_sub.1 > 1;
2322        let max_vy = cb_sub.1.max(cr_sub.1);
2323        Ok((
2324            TargetLayout::YcbcrPlanar {
2325                y_idx: yi,
2326                cb_idx: cbi,
2327                cr_idx: cri,
2328                alpha_idx,
2329            },
2330            alpha_idx.is_some(),
2331            false,
2332            false,
2333            any_sub,
2334            max_vy,
2335            min_bits,
2336        ))
2337    }
2338}
2339
2340fn src_effective_bits(src: &PixelFormat) -> u8 {
2341    if !src.layout().packing().is_full() {
2342        let mc = src.layout().packing().max_code(src.layout().sample(), 0);
2343        return (32 - mc.leading_zeros()) as u8;
2344    }
2345    src.layout().sample().bits()
2346}
2347
2348/// Returns `(offset, span, min_code, max_code)` in exact `f64` for luma / planar-RGB / Identity-GBR.
2349fn luma_encode_params(
2350    spec: PlaneFormat,
2351    range: SignalRange,
2352) -> Result<(f64, f64, u32, u32), At<ConvertError>> {
2353    if spec.sample() == SampleType::F32 {
2354        if range != SignalRange::Full {
2355            return Err(err_at(ConvertError::UnsupportedRoute));
2356        }
2357        return Ok((0.0, 1.0, 0, 1));
2358    }
2359    let max_u32 = spec.packing().max_code(spec.sample(), 0).max(1);
2360    let bits = (32 - max_u32.leading_zeros()) as i32;
2361    match range {
2362        SignalRange::Full => Ok((0.0, f64::from(max_u32), 0, max_u32)),
2363        SignalRange::Narrow => {
2364            if bits < 8 {
2365                return Err(err_at(ConvertError::UnsupportedRoute));
2366            }
2367            let shift = (bits - 8) as u32;
2368            let lo = 16u32 << shift;
2369            let span = 219u32 << shift;
2370            let hi = (lo + span).min(max_u32);
2371            Ok((f64::from(lo), f64::from(span), lo, hi))
2372        }
2373        _ => Err(err_at(ConvertError::UnsupportedRoute)),
2374    }
2375}
2376
2377/// Returns `(mid, span, min_code, max_code)` in exact `f64` for Cb/Cr/Cg/Co chroma encoding.
2378fn chroma_encode_params(
2379    spec: PlaneFormat,
2380    comp: usize,
2381    range: SignalRange,
2382) -> Result<(f64, f64, u32, u32), At<ConvertError>> {
2383    let max_u32 = spec.packing().max_code(spec.sample(), comp).max(1);
2384    let bits = (32 - max_u32.leading_zeros()) as i32;
2385    match range {
2386        SignalRange::Full => {
2387            let mid = f64::from(1u32 << (bits - 1).max(0));
2388            Ok((mid, f64::from(max_u32), 0, max_u32))
2389        }
2390        SignalRange::Narrow => {
2391            if bits < 8 {
2392                return Err(err_at(ConvertError::UnsupportedRoute));
2393            }
2394            let shift = (bits - 8) as u32;
2395            let mid = f64::from(128u32 << shift);
2396            let span = f64::from(224u32 << shift);
2397            let lo = 16u32 << shift;
2398            let hi = (240u32 << shift).min(max_u32);
2399            Ok((mid, span, lo, hi))
2400        }
2401        _ => Err(err_at(ConvertError::UnsupportedRoute)),
2402    }
2403}
2404
2405fn alpha_encode_params(spec: PlaneFormat) -> (PlaneFormat, u32) {
2406    if spec.sample() == SampleType::F32 {
2407        (spec, 1)
2408    } else {
2409        (spec, spec.packing().max_code(spec.sample(), 0).max(1))
2410    }
2411}
2412
2413#[inline(always)]
2414fn quantize_code(
2415    val: f64,
2416    lo: u32,
2417    hi: u32,
2418    depth_policy: DepthPolicy,
2419    gx: usize,
2420    gy: usize,
2421) -> u32 {
2422    let clamped = val.clamp(f64::from(lo), f64::from(hi));
2423    let q = match depth_policy {
2424        DepthPolicy::Truncate => libm::floor(clamped) as u32,
2425        DepthPolicy::OrderedDither => {
2426            let t = BAYER_4X4[((gy & 3) << 2) | (gx & 3)];
2427            libm::floor(clamped + t) as u32
2428        }
2429        _ => libm::floor(clamped + 0.5) as u32,
2430    };
2431    q.clamp(lo, hi)
2432}
2433
2434#[inline(always)]
2435#[allow(clippy::too_many_arguments)]
2436fn write_rgb_plane_sample(
2437    spec: PlaneFormat,
2438    params: (f64, f64, u32, u32),
2439    row: &mut [u8],
2440    x: usize,
2441    v: f32,
2442    depth_policy: DepthPolicy,
2443    gx: usize,
2444    gy: usize,
2445) {
2446    if spec.sample() == SampleType::F32 {
2447        let off = x * 4;
2448        row[off..off + 4].copy_from_slice(&v.to_ne_bytes());
2449    } else {
2450        let (off, span, lo, hi) = params;
2451        let code = quantize_code(
2452            off + f64::from(v).clamp(0.0, 1.0) * span,
2453            lo,
2454            hi,
2455            depth_policy,
2456            gx,
2457            gy,
2458        );
2459        write_plane_code(spec, row, x, 0, code);
2460    }
2461}
2462
2463fn detect_direct_int_rgb(
2464    src: &PixelFormat,
2465    inter_fmt: &PixelFormat,
2466    has_alpha: bool,
2467) -> Option<DirectIntRgb> {
2468    if !src.layout().packing().is_full() {
2469        return None;
2470    }
2471    let is_u16 = match src.layout().sample() {
2472        SampleType::U8 => false,
2473        SampleType::U16 => true,
2474        _ => return None,
2475    };
2476    let (
2477        ColorSpace::Rgb {
2478            transfer: st,
2479            alpha: sa,
2480            range: SignalRange::Full,
2481            diffuse_white: sw,
2482            ..
2483        }
2484        | ColorSpace::RgbCustom {
2485            transfer: st,
2486            alpha: sa,
2487            range: SignalRange::Full,
2488            diffuse_white: sw,
2489            ..
2490        },
2491        ColorSpace::Rgb {
2492            transfer: dt,
2493            alpha: da,
2494            range: SignalRange::Full,
2495            diffuse_white: dw,
2496            ..
2497        }
2498        | ColorSpace::RgbCustom {
2499            transfer: dt,
2500            alpha: da,
2501            range: SignalRange::Full,
2502            diffuse_white: dw,
2503            ..
2504        },
2505    ) = (&src.color(), &inter_fmt.color())
2506    else {
2507        return None;
2508    };
2509    if !src.color().same_rgb_chromaticity(inter_fmt.color()) || st != dt || sw != dw {
2510        return None;
2511    }
2512    if has_alpha {
2513        if sa != da {
2514            return None;
2515        }
2516    } else if !matches!(
2517        sa,
2518        AlphaMode::None | AlphaMode::Opaque | AlphaMode::Undefined
2519    ) {
2520        return None;
2521    }
2522    let (channels, r_idx, g_idx, b_idx, a_idx) = match src.layout().order() {
2523        zenpixels::ChannelOrder::Rgb => (3, 0, 1, 2, None),
2524        zenpixels::ChannelOrder::Bgr => (3, 2, 1, 0, None),
2525        zenpixels::ChannelOrder::Rgba => (4, 0, 1, 2, Some(3)),
2526        zenpixels::ChannelOrder::Bgra => (4, 2, 1, 0, Some(3)),
2527        zenpixels::ChannelOrder::Rgbx => (4, 0, 1, 2, None),
2528        zenpixels::ChannelOrder::Bgrx => (4, 2, 1, 0, None),
2529        _ => return None,
2530    };
2531    if has_alpha && a_idx.is_none() {
2532        return None;
2533    }
2534    Some(DirectIntRgb {
2535        is_u16,
2536        channels,
2537        r_idx,
2538        g_idx,
2539        b_idx,
2540        a_idx,
2541    })
2542}
2543
2544#[inline(always)]
2545fn read_direct_rgb_int(d: DirectIntRgb, row: &[u8], x: usize) -> (i128, i128, i128, i128, i128) {
2546    let base = x * d.channels;
2547    if d.is_u16 {
2548        let read_ch = |ch: usize| -> i128 {
2549            let off = (base + ch) * 2;
2550            i128::from(u16::from_ne_bytes([row[off], row[off + 1]]))
2551        };
2552        let a = d.a_idx.map_or(65_535, read_ch);
2553        (
2554            read_ch(d.r_idx),
2555            read_ch(d.g_idx),
2556            read_ch(d.b_idx),
2557            a,
2558            65_535,
2559        )
2560    } else {
2561        let read_ch = |ch: usize| -> i128 { i128::from(row[base + ch]) };
2562        let a = d.a_idx.map_or(255, read_ch);
2563        (read_ch(d.r_idx), read_ch(d.g_idx), read_ch(d.b_idx), a, 255)
2564    }
2565}
2566
2567/// Exact integer `(offset, span, min_code, max_code)` for luma / planar-RGB / Identity-GBR.
2568fn luma_encode_params_int(
2569    spec: PlaneFormat,
2570    range: SignalRange,
2571) -> Result<(i128, i128, u32, u32), At<ConvertError>> {
2572    if spec.sample() == SampleType::F32 {
2573        if range != SignalRange::Full {
2574            return Err(err_at(ConvertError::UnsupportedRoute));
2575        }
2576        return Ok((0, 1, 0, 1));
2577    }
2578    let max_u32 = spec.packing().max_code(spec.sample(), 0).max(1);
2579    let bits = (32 - max_u32.leading_zeros()) as i32;
2580    match range {
2581        SignalRange::Full => Ok((0, i128::from(max_u32), 0, max_u32)),
2582        SignalRange::Narrow => {
2583            if bits < 8 {
2584                return Err(err_at(ConvertError::UnsupportedRoute));
2585            }
2586            let shift = (bits - 8) as u32;
2587            let lo = 16u32 << shift;
2588            let span = 219u32 << shift;
2589            let hi = (lo + span).min(max_u32);
2590            Ok((i128::from(lo), i128::from(span), lo, hi))
2591        }
2592        _ => Err(err_at(ConvertError::UnsupportedRoute)),
2593    }
2594}
2595
2596/// Exact integer `(mid, span, min_code, max_code)` for Cb/Cr/Cg/Co chroma encoding.
2597fn chroma_encode_params_int(
2598    spec: PlaneFormat,
2599    comp: usize,
2600    range: SignalRange,
2601) -> Result<(i128, i128, u32, u32), At<ConvertError>> {
2602    let max_u32 = spec.packing().max_code(spec.sample(), comp).max(1);
2603    let bits = (32 - max_u32.leading_zeros()) as i32;
2604    match range {
2605        SignalRange::Full => {
2606            let mid = 1u32 << (bits - 1).max(0);
2607            Ok((i128::from(mid), i128::from(max_u32), 0, max_u32))
2608        }
2609        SignalRange::Narrow => {
2610            if bits < 8 {
2611                return Err(err_at(ConvertError::UnsupportedRoute));
2612            }
2613            let shift = (bits - 8) as u32;
2614            let mid = 128u32 << shift;
2615            let span = 224u32 << shift;
2616            let lo = 16u32 << shift;
2617            let hi = (240u32 << shift).min(max_u32);
2618            Ok((i128::from(mid), i128::from(span), lo, hi))
2619        }
2620        _ => Err(err_at(ConvertError::UnsupportedRoute)),
2621    }
2622}
2623
2624/// Quantize exact rational `num / den` (`den > 0`) under `depth_policy`, clamped to `[lo, hi]`.
2625#[inline(always)]
2626fn quantize_rational(
2627    num: i128,
2628    den: i128,
2629    lo: u32,
2630    hi: u32,
2631    depth_policy: DepthPolicy,
2632    gx: usize,
2633    gy: usize,
2634) -> u32 {
2635    let lo_i = i128::from(lo);
2636    let hi_i = i128::from(hi);
2637    // Clamp rational before rounding so values outside [lo, hi] never shift dither/round results.
2638    let clamped_num = num.clamp(lo_i * den, hi_i * den);
2639    let q = match depth_policy {
2640        DepthPolicy::Truncate => clamped_num.div_euclid(den),
2641        DepthPolicy::OrderedDither => {
2642            let b = BAYER_4X4_INT[((gy & 3) << 2) | (gx & 3)];
2643            (32 * clamped_num + (2 * b + 1) * den).div_euclid(32 * den)
2644        }
2645        _ => (2 * clamped_num + den).div_euclid(2 * den),
2646    };
2647    q.clamp(lo_i, hi_i) as u32
2648}
2649
2650#[inline(always)]
2651#[allow(clippy::too_many_arguments)]
2652fn encode_luma_exact_int(
2653    matrix: ForwardMatrix,
2654    r: i128,
2655    g: i128,
2656    b: i128,
2657    max_in: i128,
2658    (y_off, y_span, y_lo, y_hi): (i128, i128, u32, u32),
2659    depth_policy: DepthPolicy,
2660    gx: usize,
2661    gy: usize,
2662) -> Option<u32> {
2663    match matrix {
2664        ForwardMatrix::Identity => Some(quantize_rational(
2665            y_off * max_in + g * y_span,
2666            max_in,
2667            y_lo,
2668            y_hi,
2669            depth_policy,
2670            gx,
2671            gy,
2672        )),
2673        ForwardMatrix::YCgCo => {
2674            let den = 4 * max_in;
2675            let num = y_off * den + (r + 2 * g + b) * y_span;
2676            Some(quantize_rational(
2677                num,
2678                den,
2679                y_lo,
2680                y_hi,
2681                depth_policy,
2682                gx,
2683                gy,
2684            ))
2685        }
2686        ForwardMatrix::Ncl {
2687            exact_rational: Some((kr, kg, kb, k_den)),
2688            ..
2689        } => {
2690            let y_sum = kr * r + kg * g + kb * b;
2691            let den = k_den * max_in;
2692            let num = y_off * den + y_sum * y_span;
2693            Some(quantize_rational(
2694                num,
2695                den,
2696                y_lo,
2697                y_hi,
2698                depth_policy,
2699                gx,
2700                gy,
2701            ))
2702        }
2703        ForwardMatrix::Ncl {
2704            exact_rational: None,
2705            ..
2706        } => None,
2707    }
2708}
2709
2710#[inline(always)]
2711#[allow(clippy::too_many_arguments)]
2712fn encode_ycbcr_exact_int(
2713    matrix: ForwardMatrix,
2714    r: i128,
2715    g: i128,
2716    b: i128,
2717    max_in: i128,
2718    (y_off, y_span, y_lo, y_hi): (i128, i128, u32, u32),
2719    (cb_mid, cb_span, cb_lo, cb_hi): (i128, i128, u32, u32),
2720    (cr_mid, cr_span, cr_lo, cr_hi): (i128, i128, u32, u32),
2721    depth_policy: DepthPolicy,
2722    gx: usize,
2723    gy: usize,
2724) -> Option<(u32, u32, u32)> {
2725    match matrix {
2726        ForwardMatrix::Identity => Some((
2727            quantize_rational(
2728                y_off * max_in + g * y_span,
2729                max_in,
2730                y_lo,
2731                y_hi,
2732                depth_policy,
2733                gx,
2734                gy,
2735            ),
2736            quantize_rational(
2737                cb_mid * max_in + b * cb_span,
2738                max_in,
2739                cb_lo,
2740                cb_hi,
2741                depth_policy,
2742                gx,
2743                gy,
2744            ),
2745            quantize_rational(
2746                cr_mid * max_in + r * cr_span,
2747                max_in,
2748                cr_lo,
2749                cr_hi,
2750                depth_policy,
2751                gx,
2752                gy,
2753            ),
2754        )),
2755        ForwardMatrix::YCgCo => {
2756            let den4 = 4 * max_in;
2757            let den2 = 2 * max_in;
2758            let y_code = quantize_rational(
2759                y_off * den4 + (r + 2 * g + b) * y_span,
2760                den4,
2761                y_lo,
2762                y_hi,
2763                depth_policy,
2764                gx,
2765                gy,
2766            );
2767            let cg_code = quantize_rational(
2768                cb_mid * den4 + (2 * g - r - b) * cb_span,
2769                den4,
2770                cb_lo,
2771                cb_hi,
2772                depth_policy,
2773                gx,
2774                gy,
2775            );
2776            let co_code = quantize_rational(
2777                cr_mid * den2 + (r - b) * cr_span,
2778                den2,
2779                cr_lo,
2780                cr_hi,
2781                depth_policy,
2782                gx,
2783                gy,
2784            );
2785            Some((y_code, cg_code, co_code))
2786        }
2787        ForwardMatrix::Ncl {
2788            exact_rational: Some((kr, kg, kb, k_den)),
2789            ..
2790        } => {
2791            let y_sum = kr * r + kg * g + kb * b;
2792            let y_den = k_den * max_in;
2793            let y_code = quantize_rational(
2794                y_off * y_den + y_sum * y_span,
2795                y_den,
2796                y_lo,
2797                y_hi,
2798                depth_policy,
2799                gx,
2800                gy,
2801            );
2802            let cb_den = 2 * (k_den - kb) * max_in;
2803            let cb_code = quantize_rational(
2804                cb_mid * cb_den + (k_den * b - y_sum) * cb_span,
2805                cb_den,
2806                cb_lo,
2807                cb_hi,
2808                depth_policy,
2809                gx,
2810                gy,
2811            );
2812            let cr_den = 2 * (k_den - kr) * max_in;
2813            let cr_code = quantize_rational(
2814                cr_mid * cr_den + (k_den * r - y_sum) * cr_span,
2815                cr_den,
2816                cr_lo,
2817                cr_hi,
2818                depth_policy,
2819                gx,
2820                gy,
2821            );
2822            Some((y_code, cb_code, cr_code))
2823        }
2824        ForwardMatrix::Ncl {
2825            exact_rational: None,
2826            ..
2827        } => None,
2828    }
2829}
2830
2831#[inline(always)]
2832fn apply_forward_matrix_int_to_f64(
2833    matrix: ForwardMatrix,
2834    r: i128,
2835    g: i128,
2836    b: i128,
2837    max_in: i128,
2838) -> (f64, f64, f64) {
2839    match matrix {
2840        ForwardMatrix::Identity => {
2841            let inv = 1.0 / (max_in as f64);
2842            ((g as f64) * inv, (b as f64) * inv, (r as f64) * inv)
2843        }
2844        ForwardMatrix::YCgCo => {
2845            let inv4 = 1.0 / ((4 * max_in) as f64);
2846            let inv2 = 1.0 / ((2 * max_in) as f64);
2847            (
2848                ((r + 2 * g + b) as f64) * inv4,
2849                ((2 * g - r - b) as f64) * inv4,
2850                ((r - b) as f64) * inv2,
2851            )
2852        }
2853        ForwardMatrix::Ncl {
2854            exact_rational: Some((kr, kg, kb, k_den)),
2855            ..
2856        } => {
2857            let y_sum = kr * r + kg * g + kb * b;
2858            let yn = (y_sum as f64) / ((k_den * max_in) as f64);
2859            let cbn = ((k_den * b - y_sum) as f64) / ((2 * (k_den - kb) * max_in) as f64);
2860            let crn = ((k_den * r - y_sum) as f64) / ((2 * (k_den - kr) * max_in) as f64);
2861            (yn, cbn.clamp(-0.5, 0.5), crn.clamp(-0.5, 0.5))
2862        }
2863        ForwardMatrix::Ncl {
2864            exact_rational: None,
2865            ..
2866        } => {
2867            let inv = 1.0 / (max_in as f64);
2868            apply_forward_matrix_f64(matrix, (r as f64) * inv, (g as f64) * inv, (b as f64) * inv)
2869        }
2870    }
2871}
2872
2873#[inline(always)]
2874#[allow(clippy::too_many_arguments)]
2875fn write_rgb_plane_sample_int(
2876    spec: PlaneFormat,
2877    params: (i128, i128, u32, u32),
2878    row: &mut [u8],
2879    x: usize,
2880    v: i128,
2881    max_in: i128,
2882    depth_policy: DepthPolicy,
2883    gx: usize,
2884    gy: usize,
2885) {
2886    if spec.sample() == SampleType::F32 {
2887        let off = x * 4;
2888        let f = ((v as f64) / (max_in as f64)) as f32;
2889        row[off..off + 4].copy_from_slice(&f.to_ne_bytes());
2890    } else {
2891        let (off, span, lo, hi) = params;
2892        let code = quantize_rational(
2893            off * max_in + v * span,
2894            max_in,
2895            lo,
2896            hi,
2897            depth_policy,
2898            gx,
2899            gy,
2900        );
2901        write_plane_code(spec, row, x, 0, code);
2902    }
2903}
2904
2905#[inline(always)]
2906#[allow(clippy::too_many_arguments)]
2907fn write_alpha_sample_int(
2908    spec: PlaneFormat,
2909    max_code: u32,
2910    row: &mut [u8],
2911    x: usize,
2912    a: i128,
2913    max_in: i128,
2914    depth_policy: DepthPolicy,
2915    gx: usize,
2916    gy: usize,
2917) {
2918    if spec.sample() == SampleType::F32 {
2919        let off = x * 4;
2920        let f = ((a as f64) / (max_in as f64)) as f32;
2921        row[off..off + 4].copy_from_slice(&f.to_ne_bytes());
2922    } else {
2923        let code = quantize_rational(
2924            a * i128::from(max_code),
2925            max_in,
2926            0,
2927            max_code,
2928            depth_policy,
2929            gx,
2930            gy,
2931        );
2932        write_plane_code(spec, row, x, 0, code);
2933    }
2934}
2935
2936#[inline(always)]
2937#[allow(clippy::too_many_arguments)]
2938fn write_alpha_sample_f64(
2939    spec: PlaneFormat,
2940    max_code: u32,
2941    row: &mut [u8],
2942    x: usize,
2943    a: f64,
2944    depth_policy: DepthPolicy,
2945    gx: usize,
2946    gy: usize,
2947) {
2948    if spec.sample() == SampleType::F32 {
2949        let off = x * 4;
2950        row[off..off + 4].copy_from_slice(&(a as f32).to_ne_bytes());
2951    } else {
2952        let code = quantize_code(
2953            a.clamp(0.0, 1.0) * f64::from(max_code),
2954            0,
2955            max_code,
2956            depth_policy,
2957            gx,
2958            gy,
2959        );
2960        write_plane_code(spec, row, x, 0, code);
2961    }
2962}
2963
2964#[inline(always)]
2965#[allow(clippy::too_many_arguments)]
2966fn write_alpha_sample(
2967    spec: PlaneFormat,
2968    max_code: u32,
2969    row: &mut [u8],
2970    x: usize,
2971    a: f32,
2972    depth_policy: DepthPolicy,
2973    gx: usize,
2974    gy: usize,
2975) {
2976    if spec.sample() == SampleType::F32 {
2977        let off = x * 4;
2978        row[off..off + 4].copy_from_slice(&a.to_ne_bytes());
2979    } else {
2980        let code = quantize_code(
2981            f64::from(a).clamp(0.0, 1.0) * f64::from(max_code),
2982            0,
2983            max_code,
2984            depth_policy,
2985            gx,
2986            gy,
2987        );
2988        write_plane_code(spec, row, x, 0, code);
2989    }
2990}
2991
2992#[inline(always)]
2993fn write_plane_code(spec: PlaneFormat, row: &mut [u8], x: usize, comp: usize, code: u32) {
2994    let sz = spec.sample().byte_size();
2995    let elem = spec.bytes_per_element();
2996    let off = if spec.packing().is_packed_word() {
2997        x * elem
2998    } else {
2999        x * elem + comp * sz
3000    };
3001    let word = spec.packing().pack_code(spec.sample(), comp, code);
3002    match spec.sample() {
3003        SampleType::U8 => row[off] = word as u8,
3004        SampleType::U16 => row[off..off + 2].copy_from_slice(&(word as u16).to_ne_bytes()),
3005        SampleType::U32 => row[off..off + 4].copy_from_slice(&word.to_ne_bytes()),
3006        _ => {}
3007    }
3008}
3009
3010#[inline(always)]
3011fn write_semi_plane_pair(spec: PlaneFormat, row: &mut [u8], x: usize, c0: u32, c1: u32) {
3012    let elem = spec.bytes_per_element();
3013    if spec.packing().is_packed_word() {
3014        let off = x * elem;
3015        let word = spec.packing().pack_code(spec.sample(), 0, c0)
3016            | spec.packing().pack_code(spec.sample(), 1, c1);
3017        match spec.sample() {
3018            SampleType::U8 => row[off] = word as u8,
3019            SampleType::U16 => row[off..off + 2].copy_from_slice(&(word as u16).to_ne_bytes()),
3020            SampleType::U32 => row[off..off + 4].copy_from_slice(&word.to_ne_bytes()),
3021            _ => {}
3022        }
3023    } else {
3024        write_plane_code(spec, row, x, 0, c0);
3025        write_plane_code(spec, row, x, 1, c1);
3026    }
3027}