Skip to main content

zenpixels_convert/
planar.rs

1//! Native multi-plane YCbCr / GBR / planar RGB / monochrome (`PlanarView` / `PlanarBuf`,
2//! including 8/10/12-bit `BitPacking::P010` and `U10_LSB`, 4:4:4 / 4:2:2 / 4:2:0 / 4:4:0 / 4:1:1)
3//! → strided interleaved `U8` / `U16` / `F32` (`RGB`, `RGBA`, `BGR`, `BGRA`, `RGBX`, `BGRX`,
4//! `Gray`, `GrayAlpha`).
5//!
6//! All three entry points read source color interpretation identically from the [`PlanarView`]
7//! (`color()`, `effective_range()`, `matrix_coefficients()`, `effective_alpha()`,
8//! `chroma_siting()`, `crop_origin()`, `hdr()`, `origin()`, and `orientation()`):
9//! - [`reconstruct_planar_to_buf`] allocates a tightly packed interleaved [`PixelBuf`] with
10//!   caller-chosen [`SampleLayout`], deriving output [`ColorSpace`] and propagating `hdr()`,
11//!   `origin()`, and `orientation()`.
12//! - [`reconstruct_planar_into`] writes directly into a caller-provided strided
13//!   [`PixelViewMut`] with **zero heap allocation**, validating that the destination's
14//!   [`ColorSpace`] matches the source's derived color interpretation (no silent color
15//!   conversion) and propagating `src.orientation()` onto `dst`.
16//! - [`reconstruct_planar_f32`] allocates a full-range `RGBF32` / `RGBAF32` [`PixelBuf`]
17//!   with caller-chosen [`PlanarReconstructionOptions`].
18
19use how_far::Pulse;
20use whereat::At;
21use zenpixels::{
22    AlphaMode, ChannelOrder, ChromaSiting, ColorSpace, PixelBuf, PixelFormat, PixelRect,
23    PixelViewMut, PlanarView, PlaneFormat, PlaneRole, PlaneView, Primaries, SampleLayout,
24    SampleType, SignalRange,
25};
26
27use crate::error::{ConvertError, err_at};
28use crate::pulse::{check_pulse, live_pulse, step_pulse};
29use crate::ycbcr::YcbcrMatrix;
30
31/// Chroma upsampling kernel for subsampled YCbCr planes (`4:2:0`, `4:2:2`, `4:4:0`, `4:1:1`).
32///
33/// Ignored for full-resolution (`1×1`) planar RGB, 4:4:4 YCbCr, and monochrome sources.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
35#[non_exhaustive]
36pub enum ChromaUpsample {
37    /// Nearest-neighbor sample replication honoring [`PlanarView::crop_origin`] phase.
38    #[default]
39    Nearest,
40    /// Siting-exact separable bilinear / triangle interpolation honoring
41    /// [`PlanarView::chroma_siting`] and [`PlanarView::crop_origin`].
42    ///
43    /// Produces exact 9:3:3:1 ("fancy" triangle) weights for 4:2:0 [`ChromaSiting::Center`],
44    /// H.264/HEVC/AV1 `CSP_VERTICAL` weights for [`ChromaSiting::Left`], and BT.2020 co-sited
45    /// weights for [`ChromaSiting::TopLeft`].
46    Bilinear,
47}
48
49/// Configuration for planar reconstruction ([`reconstruct_planar_to_buf`],
50/// [`reconstruct_planar_into`]).
51///
52/// Chroma resampling options apply only when a chroma axis is subsampled (`> 1`).
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub struct PlanarReconstructionOptions {
56    /// Chroma upsampling kernel (`Nearest` default; `Bilinear` for smooth siting-exact upsampling).
57    pub upsample: ChromaUpsample,
58    /// Optional fallback [`ChromaSiting`] used when `upsample == ChromaUpsample::Bilinear`,
59    /// a chroma axis is subsampled, and `src.chroma_siting() == ChromaSiting::Unknown`.
60    ///
61    /// When `None`, `Bilinear` refuses subsampled views with `ChromaSiting::Unknown` rather
62    /// than silently guessing a siting.
63    pub unknown_siting_fallback: Option<ChromaSiting>,
64}
65
66impl PlanarReconstructionOptions {
67    /// Nearest-neighbor upsampling (`ChromaUpsample::Nearest`).
68    #[inline]
69    #[must_use]
70    pub const fn nearest() -> Self {
71        Self {
72            upsample: ChromaUpsample::Nearest,
73            unknown_siting_fallback: None,
74        }
75    }
76
77    /// Siting-exact separable bilinear / triangle upsampling (`ChromaUpsample::Bilinear`).
78    ///
79    /// Refuses subsampled views with `ChromaSiting::Unknown` unless
80    /// [`with_unknown_siting_fallback`](Self::with_unknown_siting_fallback) is set.
81    #[inline]
82    #[must_use]
83    pub const fn bilinear() -> Self {
84        Self {
85            upsample: ChromaUpsample::Bilinear,
86            unknown_siting_fallback: None,
87        }
88    }
89
90    /// Select the chroma upsampling kernel.
91    #[inline]
92    #[must_use]
93    pub const fn with_upsample(mut self, upsample: ChromaUpsample) -> Self {
94        self.upsample = upsample;
95        self
96    }
97
98    /// Provide an explicit fallback [`ChromaSiting`] when the source declares `ChromaSiting::Unknown`.
99    #[inline]
100    #[must_use]
101    pub const fn with_unknown_siting_fallback(mut self, siting: ChromaSiting) -> Self {
102        self.unknown_siting_fallback = Some(siting);
103        self
104    }
105}
106
107#[allow(clippy::too_many_arguments)]
108fn validate_plane(
109    plane: &PlaneView<'_>,
110    crop_x: u32,
111    crop_y: u32,
112    frame_w: u32,
113    frame_h: u32,
114    expected_components: u8,
115    require_full_res: bool,
116    allow_f32: bool,
117) -> Result<(), At<ConvertError>> {
118    let spec = plane.format();
119    let sample_ok =
120        matches!(
121            spec.sample(),
122            SampleType::U8 | SampleType::U16 | SampleType::U32
123        ) || (allow_f32 && spec.sample() == SampleType::F32 && spec.packing().is_full());
124    if !sample_ok {
125        return Err(err_at(ConvertError::UnsupportedRoute));
126    }
127    if spec.components() != expected_components {
128        return Err(err_at(ConvertError::UnsupportedRoute));
129    }
130    if require_full_res && spec.subsampling_divisors() != (1, 1) {
131        return Err(err_at(ConvertError::UnsupportedRoute));
132    }
133    let (ew, eh) = spec
134        .cropped_plane_dimensions(PixelRect::new(crop_x, crop_y, frame_w, frame_h))
135        .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
136    if plane.width() != ew || plane.height() != eh || plane.width() == 0 || plane.height() == 0 {
137        return Err(err_at(ConvertError::DimensionMismatch));
138    }
139    Ok(())
140}
141
142fn luma_scale_params(
143    spec: PlaneFormat,
144    range: SignalRange,
145) -> Result<(f32, f32), At<ConvertError>> {
146    if spec.sample() == SampleType::F32 {
147        return Ok((0.0, 1.0));
148    }
149    let max_u32 = spec.packing().max_code(spec.sample(), 0).max(1);
150    let max_f = max_u32 as f32;
151    let bits = (32 - max_u32.leading_zeros()) as i32;
152    match range {
153        SignalRange::Full => Ok((0.0, max_f)),
154        SignalRange::Narrow => {
155            let shift = (bits - 8).max(0);
156            let lo = (16u32 << shift) as f32;
157            let span = (219u32 << shift) as f32;
158            Ok((lo, span))
159        }
160        _ => Err(err_at(ConvertError::UnsupportedRoute)),
161    }
162}
163
164fn chroma_scale_params(
165    spec: PlaneFormat,
166    comp: usize,
167    range: SignalRange,
168) -> Result<(f32, f32), At<ConvertError>> {
169    let max_u32 = spec.packing().max_code(spec.sample(), comp).max(1);
170    let max_f = max_u32 as f32;
171    let bits = (32 - max_u32.leading_zeros()) as i32;
172    match range {
173        SignalRange::Full => {
174            let mid = (1u32 << (bits - 1).max(0)) as f32;
175            Ok((mid, max_f))
176        }
177        SignalRange::Narrow => {
178            let shift = (bits - 8).max(0);
179            let mid = (128u32 << shift) as f32;
180            let span = (224u32 << shift) as f32;
181            Ok((mid, span))
182        }
183        _ => Err(err_at(ConvertError::UnsupportedRoute)),
184    }
185}
186
187enum ParsedPlanar<'a> {
188    Monochrome {
189        y: &'a PlaneView<'a>,
190        alpha: Option<&'a PlaneView<'a>>,
191    },
192    YcbcrPlanar {
193        y: &'a PlaneView<'a>,
194        cb: &'a PlaneView<'a>,
195        cr: &'a PlaneView<'a>,
196        alpha: Option<&'a PlaneView<'a>>,
197    },
198    YcbcrSemi {
199        y: &'a PlaneView<'a>,
200        uv: &'a PlaneView<'a>,
201        swapped: bool,
202        alpha: Option<&'a PlaneView<'a>>,
203    },
204    PlanarRgb {
205        r: &'a PlaneView<'a>,
206        g: &'a PlaneView<'a>,
207        b: &'a PlaneView<'a>,
208        alpha: Option<&'a PlaneView<'a>>,
209    },
210}
211
212impl<'a> ParsedPlanar<'a> {
213    fn alpha_plane(&self) -> Option<&'a PlaneView<'a>> {
214        match *self {
215            Self::Monochrome { alpha, .. }
216            | Self::YcbcrPlanar { alpha, .. }
217            | Self::YcbcrSemi { alpha, .. }
218            | Self::PlanarRgb { alpha, .. } => alpha,
219        }
220    }
221
222    fn is_monochrome(&self) -> bool {
223        matches!(self, Self::Monochrome { .. })
224    }
225}
226
227fn parse_planar<'a>(src: &'a PlanarView<'a>) -> Result<ParsedPlanar<'a>, At<ConvertError>> {
228    let w = src.width();
229    let h = src.height();
230    let (ox, oy) = src.crop_origin();
231    let planes = src.planes();
232    if w == 0 || h == 0 || planes.is_empty() {
233        return Err(err_at(ConvertError::DimensionMismatch));
234    }
235
236    let mut y_plane: Option<&PlaneView<'_>> = None;
237    let mut cb_plane: Option<&PlaneView<'_>> = None;
238    let mut cr_plane: Option<&PlaneView<'_>> = None;
239    let mut semi_plane: Option<&PlaneView<'_>> = None;
240    let mut r_plane: Option<&PlaneView<'_>> = None;
241    let mut g_plane: Option<&PlaneView<'_>> = None;
242    let mut b_plane: Option<&PlaneView<'_>> = None;
243    let mut alpha_plane: Option<&PlaneView<'_>> = None;
244
245    for p in planes {
246        match p.format().role() {
247            PlaneRole::Y => {
248                if y_plane.replace(p).is_some() {
249                    return Err(err_at(ConvertError::UnsupportedRoute));
250                }
251            }
252            PlaneRole::Cb => {
253                if cb_plane.replace(p).is_some() {
254                    return Err(err_at(ConvertError::UnsupportedRoute));
255                }
256            }
257            PlaneRole::Cr => {
258                if cr_plane.replace(p).is_some() {
259                    return Err(err_at(ConvertError::UnsupportedRoute));
260                }
261            }
262            PlaneRole::CbCr | PlaneRole::CrCb => {
263                if semi_plane.replace(p).is_some() {
264                    return Err(err_at(ConvertError::UnsupportedRoute));
265                }
266            }
267            PlaneRole::R => {
268                if r_plane.replace(p).is_some() {
269                    return Err(err_at(ConvertError::UnsupportedRoute));
270                }
271            }
272            PlaneRole::G => {
273                if g_plane.replace(p).is_some() {
274                    return Err(err_at(ConvertError::UnsupportedRoute));
275                }
276            }
277            PlaneRole::B => {
278                if b_plane.replace(p).is_some() {
279                    return Err(err_at(ConvertError::UnsupportedRoute));
280                }
281            }
282            PlaneRole::Alpha => {
283                if alpha_plane.replace(p).is_some() {
284                    return Err(err_at(ConvertError::UnsupportedRoute));
285                }
286            }
287            // Refuse unrecognized/auxiliary roles (including GainMap, Depth, Extra) instead of silently dropping them.
288            _ => return Err(err_at(ConvertError::UnsupportedRoute)),
289        }
290    }
291
292    if let (Some(r), Some(g), Some(b)) = (r_plane, g_plane, b_plane) {
293        if y_plane.is_some() || cb_plane.is_some() || cr_plane.is_some() || semi_plane.is_some() {
294            return Err(err_at(ConvertError::UnsupportedRoute));
295        }
296        validate_plane(r, ox, oy, w, h, 1, true, true)?;
297        validate_plane(g, ox, oy, w, h, 1, true, true)?;
298        validate_plane(b, ox, oy, w, h, 1, true, true)?;
299        if let Some(ap) = alpha_plane {
300            validate_plane(ap, ox, oy, w, h, 1, true, true)?;
301        }
302        return Ok(ParsedPlanar::PlanarRgb {
303            r,
304            g,
305            b,
306            alpha: alpha_plane,
307        });
308    }
309    if r_plane.is_some() || g_plane.is_some() || b_plane.is_some() {
310        return Err(err_at(ConvertError::UnsupportedRoute));
311    }
312
313    let y = y_plane.ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
314    validate_plane(y, ox, oy, w, h, 1, true, false)?;
315    if let Some(ap) = alpha_plane {
316        validate_plane(ap, ox, oy, w, h, 1, true, false)?;
317    }
318
319    if let Some(uv) = semi_plane {
320        if cb_plane.is_some() || cr_plane.is_some() {
321            return Err(err_at(ConvertError::UnsupportedRoute));
322        }
323        validate_plane(uv, ox, oy, w, h, 2, false, false)?;
324        Ok(ParsedPlanar::YcbcrSemi {
325            y,
326            uv,
327            swapped: uv.format().role() == PlaneRole::CrCb,
328            alpha: alpha_plane,
329        })
330    } else if cb_plane.is_none() && cr_plane.is_none() {
331        Ok(ParsedPlanar::Monochrome {
332            y,
333            alpha: alpha_plane,
334        })
335    } else {
336        let cb = cb_plane.ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
337        let cr = cr_plane.ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
338        validate_plane(cb, ox, oy, w, h, 1, false, false)?;
339        validate_plane(cr, ox, oy, w, h, 1, false, false)?;
340        Ok(ParsedPlanar::YcbcrPlanar {
341            y,
342            cb,
343            cr,
344            alpha: alpha_plane,
345        })
346    }
347}
348
349struct ResolvedPlanarSource {
350    dst_color: ColorSpace,
351    range: SignalRange,
352    matrix: YcbcrMatrix,
353    has_alpha: bool,
354}
355
356fn resolve_planar_source(
357    src: &PlanarView<'_>,
358    parsed: &ParsedPlanar<'_>,
359    dst_layout: SampleLayout,
360) -> Result<ResolvedPlanarSource, At<ConvertError>> {
361    let has_alpha = parsed.alpha_plane().is_some();
362    if !dst_layout.packing().is_full()
363        || !matches!(
364            dst_layout.sample(),
365            SampleType::U8 | SampleType::U16 | SampleType::F32
366        )
367    {
368        return Err(err_at(ConvertError::UnsupportedRoute));
369    }
370
371    let is_gray_dst = dst_layout.order().is_gray_family();
372    if is_gray_dst && !parsed.is_monochrome() {
373        return Err(err_at(ConvertError::UnsupportedRoute));
374    }
375    if has_alpha && !dst_layout.order().has_alpha_slot() {
376        return Err(err_at(ConvertError::AlphaLossForbidden));
377    }
378
379    let dst_alpha = if dst_layout.order().has_padding_slot() {
380        AlphaMode::Undefined
381    } else if dst_layout.order().has_alpha_slot() {
382        if has_alpha {
383            match src.effective_alpha() {
384                Some(AlphaMode::Premultiplied) => AlphaMode::Premultiplied,
385                Some(AlphaMode::Opaque) => AlphaMode::Opaque,
386                _ => AlphaMode::Straight,
387            }
388        } else {
389            AlphaMode::Opaque
390        }
391    } else {
392        AlphaMode::None
393    };
394
395    let (dst_color, is_planar_f32_rgb) = match (parsed, src.color()) {
396        (
397            ParsedPlanar::Monochrome { .. },
398            Some(ColorSpace::Gray {
399                transfer,
400                diffuse_white,
401                ..
402            }),
403        ) if is_gray_dst => (
404            ColorSpace::Gray {
405                transfer: *transfer,
406                range: SignalRange::Full,
407                alpha: dst_alpha,
408                diffuse_white: *diffuse_white,
409            },
410            false,
411        ),
412        (
413            ParsedPlanar::Monochrome { .. },
414            Some(ColorSpace::Gray {
415                transfer,
416                diffuse_white,
417                ..
418            }),
419        ) => (
420            ColorSpace::Rgb {
421                primaries: Primaries::Bt709,
422                transfer: *transfer,
423                range: SignalRange::Full,
424                alpha: dst_alpha,
425                diffuse_white: *diffuse_white,
426            },
427            false,
428        ),
429        (
430            _,
431            Some(ColorSpace::Rgb {
432                primaries,
433                transfer,
434                diffuse_white,
435                ..
436            }),
437        ) => {
438            let color = if is_gray_dst {
439                ColorSpace::Gray {
440                    transfer: *transfer,
441                    range: SignalRange::Full,
442                    alpha: dst_alpha,
443                    diffuse_white: *diffuse_white,
444                }
445            } else {
446                ColorSpace::Rgb {
447                    primaries: *primaries,
448                    transfer: *transfer,
449                    range: SignalRange::Full,
450                    alpha: dst_alpha,
451                    diffuse_white: *diffuse_white,
452                }
453            };
454            let planar_f32 = matches!(
455                parsed,
456                ParsedPlanar::PlanarRgb { r, g, b, .. }
457                    if r.format().sample() == SampleType::F32
458                        && g.format().sample() == SampleType::F32
459                        && b.format().sample() == SampleType::F32
460            );
461            (color, planar_f32)
462        }
463        (
464            _,
465            Some(ColorSpace::RgbCustom {
466                primaries,
467                transfer,
468                diffuse_white,
469                ..
470            }),
471        ) => {
472            let color = if is_gray_dst {
473                ColorSpace::Gray {
474                    transfer: *transfer,
475                    range: SignalRange::Full,
476                    alpha: dst_alpha,
477                    diffuse_white: *diffuse_white,
478                }
479            } else {
480                ColorSpace::RgbCustom {
481                    primaries: alloc::sync::Arc::clone(primaries),
482                    transfer: *transfer,
483                    range: SignalRange::Full,
484                    alpha: dst_alpha,
485                    diffuse_white: *diffuse_white,
486                }
487            };
488            let planar_f32 = matches!(
489                parsed,
490                ParsedPlanar::PlanarRgb { r, g, b, .. }
491                    if r.format().sample() == SampleType::F32
492                        && g.format().sample() == SampleType::F32
493                        && b.format().sample() == SampleType::F32
494            );
495            (color, planar_f32)
496        }
497        _ => return Err(err_at(ConvertError::UnsupportedRoute)),
498    };
499
500    let range = match src.effective_range() {
501        Some(r) => r,
502        None if is_planar_f32_rgb => SignalRange::Full,
503        None => return Err(err_at(ConvertError::UnsupportedRoute)),
504    };
505
506    let matrix = match parsed {
507        ParsedPlanar::Monochrome { .. } | ParsedPlanar::PlanarRgb { .. } => YcbcrMatrix::Bt709,
508        ParsedPlanar::YcbcrPlanar { .. } | ParsedPlanar::YcbcrSemi { .. } => src
509            .matrix_coefficients()
510            .and_then(YcbcrMatrix::from_matrix_coefficients)
511            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?,
512    };
513
514    Ok(ResolvedPlanarSource {
515        dst_color,
516        range,
517        matrix,
518        has_alpha,
519    })
520}
521
522fn alpha_compatible(
523    expected: AlphaMode,
524    actual: AlphaMode,
525    has_alpha: bool,
526    dst_layout: SampleLayout,
527) -> bool {
528    if !has_alpha && dst_layout.order().has_alpha_slot() {
529        // Constant 1.0 alpha written into RGBA/BGRA/GrayAlpha is valid under Opaque,
530        // Straight, or Premultiplied tags (e.g., callers writing into `PixelFormat::RGBA8_SRGB`).
531        matches!(
532            actual,
533            AlphaMode::Opaque | AlphaMode::Straight | AlphaMode::Premultiplied
534        )
535    } else {
536        actual == expected
537    }
538}
539
540fn validate_dst_color_compatible(
541    expected: &ColorSpace,
542    actual: &ColorSpace,
543    has_alpha: bool,
544    dst_layout: SampleLayout,
545) -> Result<(), At<ConvertError>> {
546    let ok = match (expected, actual) {
547        (
548            ColorSpace::Rgb {
549                primaries: ep,
550                transfer: et,
551                range: er,
552                alpha: ea,
553                diffuse_white: ew,
554            },
555            ColorSpace::Rgb {
556                primaries: ap,
557                transfer: at,
558                range: ar,
559                alpha: aa,
560                diffuse_white: aw,
561            },
562        ) => {
563            ep == ap
564                && et == at
565                && er == ar
566                && ew == aw
567                && alpha_compatible(*ea, *aa, has_alpha, dst_layout)
568        }
569        (
570            ColorSpace::RgbCustom {
571                primaries: ep,
572                transfer: et,
573                range: er,
574                alpha: ea,
575                diffuse_white: ew,
576            },
577            ColorSpace::RgbCustom {
578                primaries: ap,
579                transfer: at,
580                range: ar,
581                alpha: aa,
582                diffuse_white: aw,
583            },
584        ) => {
585            ep == ap
586                && et == at
587                && er == ar
588                && ew == aw
589                && alpha_compatible(*ea, *aa, has_alpha, dst_layout)
590        }
591        (
592            ColorSpace::Gray {
593                transfer: et,
594                range: er,
595                alpha: ea,
596                diffuse_white: ew,
597            },
598            ColorSpace::Gray {
599                transfer: at,
600                range: ar,
601                alpha: aa,
602                diffuse_white: aw,
603            },
604        ) => et == at && er == ar && ew == aw && alpha_compatible(*ea, *aa, has_alpha, dst_layout),
605        _ => false,
606    };
607    if !ok {
608        return Err(err_at(ConvertError::UnsupportedRoute));
609    }
610    Ok(())
611}
612
613fn attach_planar_metadata(mut out: PixelBuf, src: &PlanarView<'_>) -> PixelBuf {
614    out = out.with_hdr(src.hdr()).with_orientation(src.orientation());
615    if let Some(origin) = src.origin() {
616        out = out.with_origin(origin.clone());
617    }
618    out
619}
620
621mod sealed {
622    pub trait Sealed {}
623
624    impl Sealed for zenpixels::PlanarView<'_> {}
625}
626
627/// Reconstruct interleaved pixels from a tagged [`PlanarView`].
628pub trait PlanarConvertExt: sealed::Sealed {
629    /// Reconstruct a full-range `RGBF32` / `RGBAF32` [`PixelBuf`] directly from a tagged
630    /// [`PlanarView`] (`color()`, `effective_range()`, `matrix_coefficients()`,
631    /// `effective_alpha()`, `hdr()`, `origin()`, and `orientation()`).
632    ///
633    /// Handles 3-plane YCbCr (`Y`, `Cb`, `Cr`), 2-plane semi-planar YCbCr (`Y`, `CbCr` / `CrCb`,
634    /// e.g. NV12 / P010), 3-plane RGB (`R`, `G`, `B`), and 1-plane monochrome (`Y`), each with
635    /// optional `Alpha` plane, using caller-chosen [`PlanarReconstructionOptions`] (e.g.
636    /// [`PlanarReconstructionOptions::bilinear()`] or [`PlanarReconstructionOptions::nearest()`]).
637    ///
638    /// Refuses views missing required range, color space (`Rgb` / `Gray`), or (for YCbCr chroma
639    /// views) recognized ITU-T H.273 [`MatrixCoefficients`](zenpixels::MatrixCoefficients) with
640    /// [`ConvertError::UnsupportedRoute`].
641    fn reconstruct_f32(
642        &self,
643        options: &PlanarReconstructionOptions,
644    ) -> Result<PixelBuf, At<ConvertError>>;
645
646    /// Reconstruct an interleaved [`PixelBuf`] with caller-chosen [`SampleLayout`] (`RGB8`, `RGBA8`,
647    /// `BGR8`, `BGRA8`, `RGBX8`, `BGRX8`, `RGB16`, `RGBA16`, `RGBF32`, `RGBAF32`, `GRAY8`, `GRAYA8`,
648    /// `GRAY16`, `GRAYA16`, `GRAYF32`, `GRAYAF32`) directly from a tagged [`PlanarView`] using
649    /// explicit [`PlanarReconstructionOptions`] (e.g. siting-exact [`ChromaUpsample::Bilinear`]).
650    ///
651    /// Reads source interpretation (`color()`, `effective_range()`, `matrix_coefficients()`,
652    /// `effective_alpha()`) from `self`, derives the output [`ColorSpace`], and propagates
653    /// `self.hdr()`, `self.origin()`, and `self.orientation()` onto the returned [`PixelBuf`].
654    #[doc(alias = "ycbcr_to_rgb")]
655    #[doc(alias = "yuv_to_rgb")]
656    #[doc(alias = "interleave")]
657    fn reconstruct_to_buf(
658        &self,
659        dst_layout: SampleLayout,
660        options: &PlanarReconstructionOptions,
661    ) -> Result<PixelBuf, At<ConvertError>>;
662
663    /// Reconstruct a tagged [`PlanarView`] (YCbCr, GBR, planar RGB/RGBA, or monochrome) directly
664    /// into a caller-provided strided `U8`, `U16`, or `F32` [`PixelViewMut`] (`RGB`, `RGBA`, `BGR`,
665    /// `BGRA`, `RGBX`, `BGRX`, `Gray`, `GrayAlpha`) with **zero heap allocation**.
666    ///
667    /// Uses the exact same source interpretation metadata as [`Self::reconstruct_to_buf`]
668    /// (`color()`, `effective_range()`, `matrix_coefficients()`, `effective_alpha()`), and
669    /// validates that `dst.format().color` matches the derived full-range destination color space
670    /// (refusing mismatched primaries, transfer, white point, narrow range, or conflicting alpha
671    /// semantics rather than silently converting). Sets `dst.set_orientation(src.orientation())`;
672    /// `hdr()` and `origin()` remain caller-managed on the destination storage.
673    #[doc(alias = "ycbcr_to_rgb_into")]
674    #[doc(alias = "yuv_to_rgb")]
675    #[doc(alias = "interleave")]
676    fn reconstruct_into(
677        &self,
678        dst: &mut PixelViewMut<'_>,
679        options: &PlanarReconstructionOptions,
680    ) -> Result<(), At<ConvertError>>;
681}
682
683impl PlanarConvertExt for PlanarView<'_> {
684    fn reconstruct_f32(
685        &self,
686        options: &PlanarReconstructionOptions,
687    ) -> Result<PixelBuf, At<ConvertError>> {
688        reconstruct_planar_f32_with_pulse(self, options, None)
689    }
690
691    fn reconstruct_to_buf(
692        &self,
693        dst_layout: SampleLayout,
694        options: &PlanarReconstructionOptions,
695    ) -> Result<PixelBuf, At<ConvertError>> {
696        reconstruct_planar_to_buf_with_pulse(self, dst_layout, options, None)
697    }
698
699    fn reconstruct_into(
700        &self,
701        dst: &mut PixelViewMut<'_>,
702        options: &PlanarReconstructionOptions,
703    ) -> Result<(), At<ConvertError>> {
704        reconstruct_planar_into_with_pulse(self, dst, options, None)
705    }
706}
707
708/// Reconstruct an RGB or RGBA float buffer. See [`PlanarConvertExt::reconstruct_f32`].
709#[inline]
710pub fn reconstruct_planar_f32(
711    src: &PlanarView<'_>,
712    options: &PlanarReconstructionOptions,
713) -> Result<PixelBuf, At<ConvertError>> {
714    reconstruct_planar_f32_with_pulse(src, options, None)
715}
716
717/// Reconstruct an RGB or RGBA float buffer with optional cooperative cancellation and row
718/// progress via `pulse` (pass `None` when not needed).
719pub fn reconstruct_planar_f32_with_pulse(
720    src: &PlanarView<'_>,
721    options: &PlanarReconstructionOptions,
722    pulse: Option<&dyn Pulse>,
723) -> Result<PixelBuf, At<ConvertError>> {
724    let pulse = live_pulse(pulse);
725    check_pulse(pulse)?;
726    let parsed = parse_planar(src)?;
727    let layout = if parsed.alpha_plane().is_some() {
728        SampleLayout::RGBAF32
729    } else {
730        SampleLayout::RGBF32
731    };
732    reconstruct_planar_to_buf_with_pulse(src, layout, options, pulse)
733}
734
735/// Reconstruct into a new interleaved buffer. See [`PlanarConvertExt::reconstruct_to_buf`].
736#[inline]
737pub fn reconstruct_planar_to_buf(
738    src: &PlanarView<'_>,
739    dst_layout: SampleLayout,
740    options: &PlanarReconstructionOptions,
741) -> Result<PixelBuf, At<ConvertError>> {
742    reconstruct_planar_to_buf_with_pulse(src, dst_layout, options, None)
743}
744
745/// Reconstruct into a new interleaved buffer with optional cooperative cancellation and row
746/// progress via `pulse` (pass `None` when not needed).
747pub fn reconstruct_planar_to_buf_with_pulse(
748    src: &PlanarView<'_>,
749    dst_layout: SampleLayout,
750    options: &PlanarReconstructionOptions,
751    pulse: Option<&dyn Pulse>,
752) -> Result<PixelBuf, At<ConvertError>> {
753    let pulse = live_pulse(pulse);
754    check_pulse(pulse)?;
755    let parsed = parse_planar(src)?;
756    let resolved = resolve_planar_source(src, &parsed, dst_layout)?;
757    let destination_format = PixelFormat::new(dst_layout, resolved.dst_color.clone())
758        .map_err(|e| err_at((*e.error()).into()))?;
759    let mut out = PixelBuf::new(src.width(), src.height(), destination_format)
760        .map_err(|e| err_at((*e.error()).into()))?;
761    reconstruct_parsed_into(
762        src,
763        &parsed,
764        &resolved,
765        options,
766        &mut out.as_view_mut(),
767        pulse,
768    )?;
769    Ok(attach_planar_metadata(out, src))
770}
771
772/// Reconstruct into an existing view. See [`PlanarConvertExt::reconstruct_into`].
773#[inline]
774pub fn reconstruct_planar_into(
775    src: &PlanarView<'_>,
776    dst: &mut PixelViewMut<'_>,
777    options: &PlanarReconstructionOptions,
778) -> Result<(), At<ConvertError>> {
779    reconstruct_planar_into_with_pulse(src, dst, options, None)
780}
781
782/// Reconstruct into an existing view with optional cooperative cancellation and row progress
783/// via `pulse` (pass `None` when not needed).
784pub fn reconstruct_planar_into_with_pulse(
785    src: &PlanarView<'_>,
786    dst: &mut PixelViewMut<'_>,
787    options: &PlanarReconstructionOptions,
788    pulse: Option<&dyn Pulse>,
789) -> Result<(), At<ConvertError>> {
790    let pulse = live_pulse(pulse);
791    check_pulse(pulse)?;
792    let parsed = parse_planar(src)?;
793    let w = src.width();
794    let h = src.height();
795    let dst_layout = dst.format().layout();
796    if dst.width() != w || dst.height() != h {
797        return Err(err_at(ConvertError::DimensionMismatch));
798    }
799    let resolved = resolve_planar_source(src, &parsed, dst_layout)?;
800    validate_dst_color_compatible(
801        &resolved.dst_color,
802        dst.format().color(),
803        resolved.has_alpha,
804        dst_layout,
805    )?;
806    reconstruct_parsed_into(src, &parsed, &resolved, options, dst, pulse)
807}
808
809fn reconstruct_parsed_into(
810    src: &PlanarView<'_>,
811    parsed: &ParsedPlanar<'_>,
812    resolved: &ResolvedPlanarSource,
813    options: &PlanarReconstructionOptions,
814    dst: &mut PixelViewMut<'_>,
815    pulse: Option<&dyn Pulse>,
816) -> Result<(), At<ConvertError>> {
817    let w = src.width();
818    let h = src.height();
819    let (ox, oy) = src.crop_origin();
820    let dst_layout = dst.format().layout();
821    let writer = DstWriter::from_layout(dst_layout, resolved.has_alpha, parsed.is_monochrome())?;
822    let alpha_max = parsed.alpha_plane().map(|ap| {
823        let s = ap.format();
824        if s.sample() == SampleType::F32 {
825            1.0_f32
826        } else {
827            s.packing().max_code(s.sample(), 0).max(1) as f32
828        }
829    });
830
831    match *parsed {
832        ParsedPlanar::Monochrome { y: y_plane, alpha } => {
833            let y_spec = y_plane.format();
834            let (y_off, y_span) = luma_scale_params(y_spec, resolved.range)?;
835            for y in 0..h {
836                let y_row = y_plane.row(y);
837                let alpha_row = alpha.map(|ap| (ap.format(), ap.row(y)));
838                let dst_row = dst.row_mut(y);
839                for x in 0..w {
840                    let yn = (read_plane_f32(y_spec, y_row, x as usize, 0) - y_off) / y_span;
841                    let a = read_alpha(alpha_row, alpha_max, x as usize);
842                    writer.write_pixel(dst_row, x as usize, yn, yn, yn, a);
843                }
844                step_pulse(pulse, 1)?;
845            }
846        }
847        ParsedPlanar::PlanarRgb { r, g, b, alpha } => {
848            let r_spec = r.format();
849            let g_spec = g.format();
850            let b_spec = b.format();
851            let (r_off, r_span) = luma_scale_params(r_spec, resolved.range)?;
852            let (g_off, g_span) = luma_scale_params(g_spec, resolved.range)?;
853            let (b_off, b_span) = luma_scale_params(b_spec, resolved.range)?;
854            for y in 0..h {
855                let r_row = r.row(y);
856                let g_row = g.row(y);
857                let b_row = b.row(y);
858                let alpha_row = alpha.map(|ap| (ap.format(), ap.row(y)));
859                let dst_row = dst.row_mut(y);
860                for x in 0..w {
861                    let xu = x as usize;
862                    let rv = (read_plane_f32(r_spec, r_row, xu, 0) - r_off) / r_span;
863                    let gv = (read_plane_f32(g_spec, g_row, xu, 0) - g_off) / g_span;
864                    let bv = (read_plane_f32(b_spec, b_row, xu, 0) - b_off) / b_span;
865                    let a = read_alpha(alpha_row, alpha_max, xu);
866                    writer.write_pixel(dst_row, xu, rv, gv, bv, a);
867                }
868                step_pulse(pulse, 1)?;
869            }
870        }
871        ParsedPlanar::YcbcrPlanar {
872            y: y_plane,
873            cb: cb_plane,
874            cr: cr_plane,
875            alpha,
876        } => {
877            let primaries = extract_primaries(src.color(), dst.format().color());
878            reconstruct_ycbcr_planes(
879                y_plane,
880                cb_plane,
881                cr_plane,
882                false,
883                false,
884                alpha,
885                alpha_max,
886                w,
887                h,
888                ox,
889                oy,
890                src.chroma_siting(),
891                resolved.matrix,
892                primaries,
893                resolved.range,
894                options,
895                writer,
896                dst,
897                pulse,
898            )?;
899        }
900        ParsedPlanar::YcbcrSemi {
901            y: y_plane,
902            uv,
903            swapped,
904            alpha,
905        } => {
906            let primaries = extract_primaries(src.color(), dst.format().color());
907            reconstruct_ycbcr_planes(
908                y_plane,
909                uv,
910                uv,
911                true,
912                swapped,
913                alpha,
914                alpha_max,
915                w,
916                h,
917                ox,
918                oy,
919                src.chroma_siting(),
920                resolved.matrix,
921                primaries,
922                resolved.range,
923                options,
924                writer,
925                dst,
926                pulse,
927            )?;
928        }
929    }
930
931    dst.set_orientation(src.orientation());
932    Ok(())
933}
934
935fn extract_primaries(src_color: Option<&ColorSpace>, dst_color: &ColorSpace) -> Option<Primaries> {
936    if let Some(ColorSpace::Rgb { primaries, .. }) = src_color
937        && *primaries != Primaries::Unknown
938    {
939        return Some(*primaries);
940    }
941    if let ColorSpace::Rgb { primaries, .. } = dst_color
942        && *primaries != Primaries::Unknown
943    {
944        return Some(*primaries);
945    }
946    None
947}
948
949#[allow(clippy::too_many_arguments)]
950fn reconstruct_ycbcr_planes(
951    y_plane: &PlaneView<'_>,
952    cb_plane: &PlaneView<'_>,
953    cr_plane: &PlaneView<'_>,
954    semi: bool,
955    swapped: bool,
956    alpha: Option<&PlaneView<'_>>,
957    alpha_max: Option<f32>,
958    w: u32,
959    h: u32,
960    ox: u32,
961    oy: u32,
962    declared_siting: ChromaSiting,
963    matrix: YcbcrMatrix,
964    primaries: Option<Primaries>,
965    range: SignalRange,
966    options: &PlanarReconstructionOptions,
967    writer: DstWriter,
968    dst: &mut PixelViewMut<'_>,
969    pulse: Option<&dyn Pulse>,
970) -> Result<(), At<ConvertError>> {
971    let y_spec = y_plane.format();
972    let cb_spec = cb_plane.format();
973    let cr_spec = cr_plane.format();
974    let (y_off, y_span) = luma_scale_params(y_spec, range)?;
975
976    let (cb_hx, cb_vy) = cb_spec.subsampling_divisors();
977    let (cr_hx, cr_vy) = cr_spec.subsampling_divisors();
978    let any_subsampled = cb_hx > 1 || cb_vy > 1 || cr_hx > 1 || cr_vy > 1;
979
980    let effective_siting = if options.upsample == ChromaUpsample::Bilinear && any_subsampled {
981        let s = if declared_siting != ChromaSiting::Unknown {
982            declared_siting
983        } else if let Some(fb) = options.unknown_siting_fallback
984            && fb != ChromaSiting::Unknown
985        {
986            fb
987        } else {
988            return Err(err_at(ConvertError::UnsupportedRoute));
989        };
990        Some(s)
991    } else {
992        None
993    };
994
995    let cb_comp = usize::from(semi && swapped);
996    let cr_comp = usize::from(semi && !swapped);
997
998    let cb_ox0 = ox / u32::from(cb_hx);
999    let cb_oy0 = oy / u32::from(cb_vy);
1000    let cr_ox0 = ox / u32::from(cr_hx);
1001    let cr_oy0 = oy / u32::from(cr_vy);
1002
1003    let (cb_dx, cb_dy) = effective_siting
1004        .and_then(|s| s.offset_in_luma_pixels_for_divisors(cb_hx, cb_vy))
1005        .unwrap_or((0.0, 0.0));
1006    let (cr_dx, cr_dy) = effective_siting
1007        .and_then(|s| s.offset_in_luma_pixels_for_divisors(cr_hx, cr_vy))
1008        .unwrap_or((0.0, 0.0));
1009
1010    let bilinear = options.upsample == ChromaUpsample::Bilinear && any_subsampled;
1011
1012    enum MatrixOp {
1013        Identity {
1014            b_off: f32,
1015            b_span: f32,
1016            r_off: f32,
1017            r_span: f32,
1018        },
1019        YCgCo {
1020            cb_mid: f32,
1021            cb_span: f32,
1022            cr_mid: f32,
1023            cr_span: f32,
1024        },
1025        Ncl {
1026            cb_mid: f32,
1027            cb_span: f32,
1028            cr_mid: f32,
1029            cr_span: f32,
1030            cr_to_r: f32,
1031            cb_to_b: f32,
1032            cr_to_g: f32,
1033            cb_to_g: f32,
1034        },
1035    }
1036
1037    let op = match matrix {
1038        YcbcrMatrix::Identity => {
1039            let (b_off, b_span) = luma_scale_params(cb_spec, range)?;
1040            let (r_off, r_span) = luma_scale_params(cr_spec, range)?;
1041            MatrixOp::Identity {
1042                b_off,
1043                b_span,
1044                r_off,
1045                r_span,
1046            }
1047        }
1048        YcbcrMatrix::YCgCo => {
1049            let (cb_mid, cb_span) = chroma_scale_params(cb_spec, cb_comp, range)?;
1050            let (cr_mid, cr_span) = chroma_scale_params(cr_spec, cr_comp, range)?;
1051            MatrixOp::YCgCo {
1052                cb_mid,
1053                cb_span,
1054                cr_mid,
1055                cr_span,
1056            }
1057        }
1058        _ => {
1059            let (kr, kb) = matrix
1060                .kr_kb_for(primaries)
1061                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
1062            let kg = 1.0 - kr - kb;
1063            let (cb_mid, cb_span) = chroma_scale_params(cb_spec, cb_comp, range)?;
1064            let (cr_mid, cr_span) = chroma_scale_params(cr_spec, cr_comp, range)?;
1065            MatrixOp::Ncl {
1066                cb_mid,
1067                cb_span,
1068                cr_mid,
1069                cr_span,
1070                cr_to_r: 2.0 * (1.0 - kr),
1071                cb_to_b: 2.0 * (1.0 - kb),
1072                cr_to_g: -2.0 * kr * (1.0 - kr) / kg,
1073                cb_to_g: -2.0 * kb * (1.0 - kb) / kg,
1074            }
1075        }
1076    };
1077
1078    let cb_w_max = cb_plane.width() - 1;
1079    let cb_h_max = cb_plane.height() - 1;
1080    let cr_w_max = cr_plane.width() - 1;
1081    let cr_h_max = cr_plane.height() - 1;
1082
1083    for y in 0..h {
1084        let y_row = y_plane.row(y);
1085        let gy = oy + y;
1086        let alpha_row = alpha.map(|ap| (ap.format(), ap.row(y)));
1087        let dst_row = dst.row_mut(y);
1088
1089        let (cby0, cby1, cb_ty) = if bilinear && cb_vy > 1 {
1090            axis_bilinear_taps(gy, cb_vy, cb_dy, cb_oy0, cb_h_max)
1091        } else {
1092            let iy = (gy / u32::from(cb_vy) - cb_oy0).min(cb_h_max);
1093            (iy, iy, 0.0)
1094        };
1095        let (cry0, cry1, cr_ty) = if bilinear && cr_vy > 1 {
1096            axis_bilinear_taps(gy, cr_vy, cr_dy, cr_oy0, cr_h_max)
1097        } else {
1098            let iy = (gy / u32::from(cr_vy) - cr_oy0).min(cr_h_max);
1099            (iy, iy, 0.0)
1100        };
1101
1102        let cb_row0 = cb_plane.row(cby0);
1103        let cb_row1 = if cby1 == cby0 {
1104            cb_row0
1105        } else {
1106            cb_plane.row(cby1)
1107        };
1108        let cr_row0 = cr_plane.row(cry0);
1109        let cr_row1 = if cry1 == cry0 {
1110            cr_row0
1111        } else {
1112            cr_plane.row(cry1)
1113        };
1114
1115        for x in 0..w {
1116            let gx = ox + x;
1117            let xu = x as usize;
1118            let y_code = read_plane_code(y_spec, y_row, xu, 0) as f32;
1119            let yn = (y_code - y_off) / y_span;
1120
1121            let (cb_code, cr_code) = if bilinear {
1122                let cb_v = sample_chroma_bilinear(
1123                    cb_spec, cb_row0, cb_row1, cb_ty, gx, cb_hx, cb_dx, cb_ox0, cb_w_max, cb_comp,
1124                );
1125                let cr_v = sample_chroma_bilinear(
1126                    cr_spec, cr_row0, cr_row1, cr_ty, gx, cr_hx, cr_dx, cr_ox0, cr_w_max, cr_comp,
1127                );
1128                (cb_v, cr_v)
1129            } else {
1130                let cbx = ((gx / u32::from(cb_hx) - cb_ox0).min(cb_w_max)) as usize;
1131                let crx = if semi {
1132                    cbx
1133                } else {
1134                    ((gx / u32::from(cr_hx) - cr_ox0).min(cr_w_max)) as usize
1135                };
1136                (
1137                    read_plane_code(cb_spec, cb_row0, cbx, cb_comp) as f32,
1138                    read_plane_code(cr_spec, cr_row0, crx, cr_comp) as f32,
1139                )
1140            };
1141
1142            let (r, g, b) = match op {
1143                MatrixOp::Identity {
1144                    b_off,
1145                    b_span,
1146                    r_off,
1147                    r_span,
1148                } => ((cr_code - r_off) / r_span, yn, (cb_code - b_off) / b_span),
1149                MatrixOp::YCgCo {
1150                    cb_mid,
1151                    cb_span,
1152                    cr_mid,
1153                    cr_span,
1154                } => {
1155                    let cg = (cb_code - cb_mid) / cb_span;
1156                    let co = (cr_code - cr_mid) / cr_span;
1157                    let t = yn - cg;
1158                    (t + co, yn + cg, t - co)
1159                }
1160                MatrixOp::Ncl {
1161                    cb_mid,
1162                    cb_span,
1163                    cr_mid,
1164                    cr_span,
1165                    cr_to_r,
1166                    cb_to_b,
1167                    cr_to_g,
1168                    cb_to_g,
1169                } => {
1170                    // Exact IEEE division so narrow white (235/940/3760) yields exact 1.0f32.
1171                    let cb = (cb_code - cb_mid) / cb_span;
1172                    let cr = (cr_code - cr_mid) / cr_span;
1173                    (
1174                        yn + cr_to_r * cr,
1175                        yn + cr_to_g * cr + cb_to_g * cb,
1176                        yn + cb_to_b * cb,
1177                    )
1178                }
1179            };
1180
1181            let a = read_alpha(alpha_row, alpha_max, xu);
1182            writer.write_pixel(dst_row, xu, r, g, b, a);
1183        }
1184        step_pulse(pulse, 1)?;
1185    }
1186
1187    Ok(())
1188}
1189
1190#[inline(always)]
1191fn axis_bilinear_taps(
1192    global_pos: u32,
1193    factor: u8,
1194    offset_in_cell: f32,
1195    plane_origin: u32,
1196    max_idx: u32,
1197) -> (u32, u32, f32) {
1198    let u_global = (global_pos as f32 - offset_in_cell) / f32::from(factor);
1199    let u_rel = (u_global - plane_origin as f32).clamp(0.0, max_idx as f32);
1200    let i0 = (libm::floorf(u_rel) as u32).min(max_idx);
1201    let i1 = (i0 + 1).min(max_idx);
1202    let t = u_rel - (i0 as f32);
1203    (i0, i1, t)
1204}
1205
1206#[inline(always)]
1207#[allow(clippy::too_many_arguments)]
1208fn sample_chroma_bilinear(
1209    spec: PlaneFormat,
1210    row0: &[u8],
1211    row1: &[u8],
1212    ty: f32,
1213    gx: u32,
1214    hx: u8,
1215    dx: f32,
1216    ox0: u32,
1217    w_max: u32,
1218    comp: usize,
1219) -> f32 {
1220    let (x0, x1, tx) = if hx > 1 {
1221        axis_bilinear_taps(gx, hx, dx, ox0, w_max)
1222    } else {
1223        let ix = (gx - ox0).min(w_max);
1224        (ix, ix, 0.0)
1225    };
1226    let s00 = read_plane_code(spec, row0, x0 as usize, comp) as f32;
1227    let top = if x1 == x0 {
1228        s00
1229    } else {
1230        let s01 = read_plane_code(spec, row0, x1 as usize, comp) as f32;
1231        s00 + (s01 - s00) * tx
1232    };
1233    if ty == 0.0 {
1234        return top;
1235    }
1236    let s10 = read_plane_code(spec, row1, x0 as usize, comp) as f32;
1237    let bot = if x1 == x0 {
1238        s10
1239    } else {
1240        let s11 = read_plane_code(spec, row1, x1 as usize, comp) as f32;
1241        s10 + (s11 - s10) * tx
1242    };
1243    top + (bot - top) * ty
1244}
1245
1246#[derive(Clone, Copy)]
1247struct DstWriter {
1248    sample: SampleType,
1249    order: ChannelOrder,
1250}
1251
1252impl DstWriter {
1253    fn from_layout(
1254        layout: SampleLayout,
1255        src_has_alpha: bool,
1256        src_is_mono: bool,
1257    ) -> Result<Self, At<ConvertError>> {
1258        let supported_order = matches!(
1259            layout.order(),
1260            ChannelOrder::Rgb
1261                | ChannelOrder::Rgba
1262                | ChannelOrder::Bgr
1263                | ChannelOrder::Bgra
1264                | ChannelOrder::Rgbx
1265                | ChannelOrder::Bgrx
1266                | ChannelOrder::Gray
1267                | ChannelOrder::GrayAlpha
1268        );
1269        if !supported_order {
1270            return Err(err_at(ConvertError::UnsupportedRoute));
1271        }
1272        if layout.order().is_gray_family() && !src_is_mono {
1273            return Err(err_at(ConvertError::UnsupportedRoute));
1274        }
1275        if src_has_alpha && !layout.order().has_alpha_slot() {
1276            return Err(err_at(ConvertError::AlphaLossForbidden));
1277        }
1278        Ok(Self {
1279            sample: layout.sample(),
1280            order: layout.order(),
1281        })
1282    }
1283
1284    #[inline(always)]
1285    fn write_pixel(self, row: &mut [u8], x: usize, r: f32, g: f32, b: f32, a: f32) {
1286        match self.sample {
1287            SampleType::U8 => {
1288                let to_u8 = |v: f32| -> u8 { (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 };
1289                match self.order {
1290                    ChannelOrder::Rgb => {
1291                        let o = x * 3;
1292                        row[o] = to_u8(r);
1293                        row[o + 1] = to_u8(g);
1294                        row[o + 2] = to_u8(b);
1295                    }
1296                    ChannelOrder::Bgr => {
1297                        let o = x * 3;
1298                        row[o] = to_u8(b);
1299                        row[o + 1] = to_u8(g);
1300                        row[o + 2] = to_u8(r);
1301                    }
1302                    ChannelOrder::Rgba | ChannelOrder::Rgbx => {
1303                        let o = x * 4;
1304                        row[o] = to_u8(r);
1305                        row[o + 1] = to_u8(g);
1306                        row[o + 2] = to_u8(b);
1307                        row[o + 3] = to_u8(a);
1308                    }
1309                    ChannelOrder::Bgra | ChannelOrder::Bgrx => {
1310                        let o = x * 4;
1311                        row[o] = to_u8(b);
1312                        row[o + 1] = to_u8(g);
1313                        row[o + 2] = to_u8(r);
1314                        row[o + 3] = to_u8(a);
1315                    }
1316                    ChannelOrder::Gray => {
1317                        row[x] = to_u8(r);
1318                    }
1319                    ChannelOrder::GrayAlpha => {
1320                        let o = x * 2;
1321                        row[o] = to_u8(r);
1322                        row[o + 1] = to_u8(a);
1323                    }
1324                    _ => {}
1325                }
1326            }
1327            SampleType::U16 => {
1328                let to_u16 = |v: f32| -> [u8; 2] {
1329                    ((v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).to_ne_bytes()
1330                };
1331                match self.order {
1332                    ChannelOrder::Rgb => {
1333                        let o = x * 6;
1334                        row[o..o + 2].copy_from_slice(&to_u16(r));
1335                        row[o + 2..o + 4].copy_from_slice(&to_u16(g));
1336                        row[o + 4..o + 6].copy_from_slice(&to_u16(b));
1337                    }
1338                    ChannelOrder::Bgr => {
1339                        let o = x * 6;
1340                        row[o..o + 2].copy_from_slice(&to_u16(b));
1341                        row[o + 2..o + 4].copy_from_slice(&to_u16(g));
1342                        row[o + 4..o + 6].copy_from_slice(&to_u16(r));
1343                    }
1344                    ChannelOrder::Rgba | ChannelOrder::Rgbx => {
1345                        let o = x * 8;
1346                        row[o..o + 2].copy_from_slice(&to_u16(r));
1347                        row[o + 2..o + 4].copy_from_slice(&to_u16(g));
1348                        row[o + 4..o + 6].copy_from_slice(&to_u16(b));
1349                        row[o + 6..o + 8].copy_from_slice(&to_u16(a));
1350                    }
1351                    ChannelOrder::Bgra | ChannelOrder::Bgrx => {
1352                        let o = x * 8;
1353                        row[o..o + 2].copy_from_slice(&to_u16(b));
1354                        row[o + 2..o + 4].copy_from_slice(&to_u16(g));
1355                        row[o + 4..o + 6].copy_from_slice(&to_u16(r));
1356                        row[o + 6..o + 8].copy_from_slice(&to_u16(a));
1357                    }
1358                    ChannelOrder::Gray => {
1359                        let o = x * 2;
1360                        row[o..o + 2].copy_from_slice(&to_u16(r));
1361                    }
1362                    ChannelOrder::GrayAlpha => {
1363                        let o = x * 4;
1364                        row[o..o + 2].copy_from_slice(&to_u16(r));
1365                        row[o + 2..o + 4].copy_from_slice(&to_u16(a));
1366                    }
1367                    _ => {}
1368                }
1369            }
1370            SampleType::F32 => match self.order {
1371                ChannelOrder::Rgb => {
1372                    let o = x * 12;
1373                    row[o..o + 4].copy_from_slice(&r.to_ne_bytes());
1374                    row[o + 4..o + 8].copy_from_slice(&g.to_ne_bytes());
1375                    row[o + 8..o + 12].copy_from_slice(&b.to_ne_bytes());
1376                }
1377                ChannelOrder::Bgr => {
1378                    let o = x * 12;
1379                    row[o..o + 4].copy_from_slice(&b.to_ne_bytes());
1380                    row[o + 4..o + 8].copy_from_slice(&g.to_ne_bytes());
1381                    row[o + 8..o + 12].copy_from_slice(&r.to_ne_bytes());
1382                }
1383                ChannelOrder::Rgba | ChannelOrder::Rgbx => {
1384                    let o = x * 16;
1385                    row[o..o + 4].copy_from_slice(&r.to_ne_bytes());
1386                    row[o + 4..o + 8].copy_from_slice(&g.to_ne_bytes());
1387                    row[o + 8..o + 12].copy_from_slice(&b.to_ne_bytes());
1388                    row[o + 12..o + 16].copy_from_slice(&a.to_ne_bytes());
1389                }
1390                ChannelOrder::Bgra | ChannelOrder::Bgrx => {
1391                    let o = x * 16;
1392                    row[o..o + 4].copy_from_slice(&b.to_ne_bytes());
1393                    row[o + 4..o + 8].copy_from_slice(&g.to_ne_bytes());
1394                    row[o + 8..o + 12].copy_from_slice(&r.to_ne_bytes());
1395                    row[o + 12..o + 16].copy_from_slice(&a.to_ne_bytes());
1396                }
1397                ChannelOrder::Gray => {
1398                    let o = x * 4;
1399                    row[o..o + 4].copy_from_slice(&r.to_ne_bytes());
1400                }
1401                ChannelOrder::GrayAlpha => {
1402                    let o = x * 8;
1403                    row[o..o + 4].copy_from_slice(&r.to_ne_bytes());
1404                    row[o + 4..o + 8].copy_from_slice(&a.to_ne_bytes());
1405                }
1406                _ => {}
1407            },
1408            _ => {}
1409        }
1410    }
1411}
1412
1413#[inline(always)]
1414fn read_alpha(alpha_row: Option<(PlaneFormat, &[u8])>, alpha_max: Option<f32>, x: usize) -> f32 {
1415    if let (Some((a_spec, a_row)), Some(a_max)) = (alpha_row, alpha_max) {
1416        read_plane_f32(a_spec, a_row, x, 0) / a_max
1417    } else {
1418        1.0
1419    }
1420}
1421
1422#[inline(always)]
1423fn read_plane_f32(spec: PlaneFormat, row: &[u8], x: usize, comp: usize) -> f32 {
1424    if spec.sample() == SampleType::F32 {
1425        let elem = spec.bytes_per_element();
1426        let off = x * elem + comp * 4;
1427        f32::from_ne_bytes([row[off], row[off + 1], row[off + 2], row[off + 3]])
1428    } else {
1429        read_plane_code(spec, row, x, comp) as f32
1430    }
1431}
1432
1433#[inline(always)]
1434fn read_plane_code(spec: PlaneFormat, row: &[u8], x: usize, comp: usize) -> u32 {
1435    let sz = spec.sample().byte_size();
1436    let elem = spec.bytes_per_element();
1437    // Packed bitfield words store all components inside one word at `x * elem`;
1438    // unpacked multi-component planes store component `comp` at `x * elem + comp * sz`.
1439    let off = if spec.packing().is_packed_word() {
1440        x * elem
1441    } else {
1442        x * elem + comp * sz
1443    };
1444    let w = match spec.sample() {
1445        SampleType::U8 => u32::from(row[off]),
1446        SampleType::U16 => u32::from(u16::from_ne_bytes([row[off], row[off + 1]])),
1447        SampleType::U32 => u32::from_ne_bytes([row[off], row[off + 1], row[off + 2], row[off + 3]]),
1448        _ => 0,
1449    };
1450    spec.packing().extract_code(spec.sample(), comp, w)
1451}