Skip to main content

edgefirst_image/cpu/
mod.rs

1// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{
5    Error, Flip, FunctionTimer, ImageProcessorTrait, Rect, ResolvedCrop, Result, Rotation,
6};
7use edgefirst_tensor::{
8    DType, PixelFormat, Tensor, TensorDyn, TensorMapTrait, TensorMemory, TensorTrait,
9};
10use edgefirst_tensor::{DetectBox, ProtoData, Segmentation};
11
12mod convert;
13mod masks;
14mod normalize;
15mod resize;
16mod simd;
17mod tests;
18
19// bilinear_dot removed — masks.rs now uses slice-native bilinear_dot_slice
20// closure-based kernel, invoked through the local dtype dispatch below.
21
22/// Resolved colorimetry parameters for a format conversion, computed once at
23/// the dispatch site (`convert_impl`) from the appropriate tensor:
24/// - YUV→RGB conversions use the **source** tensor's colorimetry.
25/// - RGB→YUV conversions use the **destination** tensor's colorimetry.
26///
27/// `matrix`/`range` feed the `yuv` crate kernels; `src_full_range`/
28/// `dst_full_range` gate the hand-rolled luma (limited↔full) expansion in the
29/// grey/luma copy helpers.
30#[derive(Debug, Clone, Copy)]
31pub(crate) struct ColorParams {
32    /// Matrix resolved from the YUV side (src for decode, dst for encode).
33    pub matrix: yuv::YuvStandardMatrix,
34    /// Range resolved from the YUV side (src for decode, dst for encode).
35    pub range: yuv::YuvRange,
36    /// The same matrix/range in HAL's own terms, so the hand-rolled fixed-point
37    /// encoders draw their `(kr, kb)` weights and luma/chroma swings from the
38    /// canonical [`edgefirst_tensor::colorimetry`] source rather than a private
39    /// duplicate table.
40    pub encoding: edgefirst_tensor::ColorEncoding,
41    pub range_kind: edgefirst_tensor::ColorRange,
42    /// True when the **source** tensor's resolved range is full (decode-side
43    /// luma extraction: copy luma directly instead of limited→full expansion).
44    pub src_full_range: bool,
45    /// True when the **destination** tensor's resolved range is full
46    /// (encode-side luma copies).
47    pub dst_full_range: bool,
48}
49
50/// CPUConverter implements the ImageProcessor trait using the fallback CPU
51/// implementation for image processing.
52#[derive(Debug)]
53pub struct CPUProcessor {
54    resizer: fast_image_resize::Resizer,
55    options: fast_image_resize::ResizeOptions,
56    colors: [[u8; 4]; 20],
57    /// Reusable scratch tensor for the U8→float widen path.
58    ///
59    /// Holds a U8 image in the destination's pixel format and dimensions.
60    /// Reallocated only when the format or dimensions change, amortising
61    /// the heap allocation across repeated same-size conversions.
62    widen_scratch: Option<TensorDyn>,
63    /// Reusable scratch for de-striding a padded source before resize.
64    ///
65    /// `fast_image_resize` needs a tightly-packed input; a padded source
66    /// (64-aligned stride from codec decode / `create_image`) is copied here
67    /// row-by-row first. Kept on the processor so the steady-state resize loop
68    /// reuses the allocation instead of a fresh `Vec` per call (the stride
69    /// alignment in this release makes that de-stride copy fire far more often).
70    resize_destride_scratch: Vec<u8>,
71    /// Reusable scratch for de-striding a padded resize *destination* before
72    /// resize.
73    ///
74    /// `fast_image_resize` needs a tightly-packed output buffer; a padded
75    /// destination (a DMA pitch-aligned tensor, or a `view()` narrower than
76    /// its parent's row stride) is resized into this tight scratch first,
77    /// then copied back into the real destination row-by-row at its true
78    /// stride. Kept on the processor so the steady-state resize loop reuses
79    /// the allocation instead of a fresh `Vec` per call — mirrors
80    /// `resize_destride_scratch` on the source side.
81    resize_dst_destride_scratch: Vec<u8>,
82    /// Reusable cache-resident scratch for the strip-fused NV→planar path
83    /// (`convert_nv_to_planar_fused`): holds a single row strip of packed RGB
84    /// (`STRIP_ROWS * width * 3` bytes). Keeping it on the processor avoids a
85    /// per-frame allocation and lets each strip stay hot in L2 between the YUV
86    /// decode and the deinterleave. Grown on demand; never shrunk.
87    nv_strip_scratch: Vec<u8>,
88    /// Reusable cache-resident scratch for the fused NV→planar path's
89    /// **region** case: a tight (stride == width) copy of the current
90    /// strip's luma rows, starting at column 0. The `yuv` crate's row
91    /// iteration processes fixed-`stride`-sized chunks internally, using
92    /// only the first `width` bytes of each — feeding it a slice that starts
93    /// at a mid-row column offset (a source-crop `region` with a nonzero
94    /// `left`) reads past the *source* buffer's true end for the region's
95    /// last row when that row is also the source's last row (the unused
96    /// chunk tail has no next row to alias into there). Packing each row
97    /// into a `stride == width` buffer first sidesteps that read. Unused
98    /// (and zero-cost) for any row-aligned read (`region.left == 0`,
99    /// including the whole-frame `region: None` case): with no column
100    /// shift, every row chunk the crate sees is a real, fully-owned source
101    /// row, so those reads stay fully zero-copy. Grown on demand; never
102    /// shrunk.
103    nv_strip_y_pack: Vec<u8>,
104    /// Same as [`Self::nv_strip_y_pack`], for the chroma (UV) rows.
105    nv_strip_uv_pack: Vec<u8>,
106    /// Test-only counter of `convert` calls that took the fused NV→planar
107    /// strip path (`convert_nv_to_planar_fused`), incremented at the gate in
108    /// `convert_u8`. Exists only under `#[cfg(test)]` — a field that's
109    /// written but (outside tests) never read trips clippy's dead-code lint
110    /// on both OS lanes. Read via [`Self::fused_hits`] so path-selection
111    /// tests assert on the actual gate decision rather than on timing.
112    #[cfg(test)]
113    fused_hits: u64,
114    /// Test-only record of the dimensions of the pre-resize intermediate the
115    /// most recent `convert_u8` call allocated, or `None` when that call did
116    /// not need one. Lets the allocation-proportionality tests assert that a
117    /// cropped convert sizes its intermediate to the crop rather than to the
118    /// whole frame, without reaching into the allocator. Reset at the top of
119    /// every `convert_u8`.
120    #[cfg(test)]
121    last_tmp_dims: Option<(usize, usize)>,
122    /// Reusable intermediate buffers for the multi-step convert pipeline
123    /// (pre-resize format-convert and the resized-RGB scratch). Reused across
124    /// frames when the dimensions/format match so the steady-state
125    /// letterbox/resize loop does not reallocate — and `alloc_zeroed`-clear — a
126    /// full-frame buffer per call. The region each consumer reads is always
127    /// fully overwritten first, so reused (non-zeroed) contents are never read.
128    convert_tmp: Option<Tensor<u8>>,
129    convert_tmp2: Option<Tensor<u8>>,
130    /// Reusable crop-sized copy of the source's own pixel format, holding the
131    /// halo-grown crop rectangle extracted by [`Self::extract_nv_region`] for
132    /// the crop-sized pre-resize intermediate. Only allocated for a cropped
133    /// convert that takes that path; the whole-frame path never touches it.
134    convert_src_sub: Option<Tensor<u8>>,
135}
136
137// `CPUProcessor` was `#[derive(Clone)]` before the `widen_scratch` field was
138// added; `TensorDyn` is not `Clone`, so the derive no longer applies. Restore
139// the public `Clone` impl by hand to avoid a breaking API change. The scratch
140// cache is a private allocation amortiser, not part of the logical value, so a
141// clone starts empty rather than sharing or duplicating it.
142impl Clone for CPUProcessor {
143    fn clone(&self) -> Self {
144        Self {
145            resizer: self.resizer.clone(),
146            options: self.options,
147            colors: self.colors,
148            widen_scratch: None,
149            resize_destride_scratch: Vec::new(),
150            resize_dst_destride_scratch: Vec::new(),
151            nv_strip_scratch: Vec::new(),
152            nv_strip_y_pack: Vec::new(),
153            nv_strip_uv_pack: Vec::new(),
154            #[cfg(test)]
155            fused_hits: 0,
156            #[cfg(test)]
157            last_tmp_dims: None,
158            convert_tmp: None,
159            convert_tmp2: None,
160            convert_src_sub: None,
161        }
162    }
163}
164
165unsafe impl Send for CPUProcessor {}
166unsafe impl Sync for CPUProcessor {}
167
168impl Default for CPUProcessor {
169    fn default() -> Self {
170        Self::new_bilinear()
171    }
172}
173
174/// Write the base layer of `dst` before mask rendering.
175///
176/// This is the terminal fallback: on CPU we have no 2D hardware, so a
177/// direct buffer write is the appropriate primitive. The invariant is that
178/// every call to the CPU draw_* entry points fully initialises dst — we
179/// never rely on "whatever was in the buffer" from the caller.
180///
181/// - `background == Some(bg)` → byte-for-byte copy bg → dst (after shape /
182///   format validation).
183/// - `background == None` → fill dst with 0x00 (transparent black).
184fn prepare_dst_base_cpu(dst: &mut TensorDyn, background: Option<&TensorDyn>) -> Result<()> {
185    match background {
186        Some(bg) => {
187            if bg.shape() != dst.shape() {
188                return Err(Error::InvalidShape(
189                    "background shape does not match dst".into(),
190                ));
191            }
192            if bg.format() != dst.format() {
193                return Err(Error::InvalidShape(
194                    "background pixel format does not match dst".into(),
195                ));
196            }
197            let bg_u8 = bg.as_typed::<u8>().ok_or(Error::NotAnImage)?;
198            let dst_u8 = dst.as_typed_mut::<u8>().ok_or(Error::NotAnImage)?;
199            // Row-wise, not a flat copy_from_slice: `bg` and `dst` can each
200            // carry their own row_stride (a padded D3D11/GPU-pitch destination
201            // composited from a tight background, or vice versa), so a single
202            // equal-length check is wrong even when the logical shapes match.
203            // `CPUProcessor::copy_image` already walks both sides at their
204            // own pitch via `logical_surface`/`packed_row_pairs`.
205            CPUProcessor::copy_image(bg_u8, dst_u8)?;
206        }
207        None => {
208            let dst_u8 = dst.as_typed_mut::<u8>().ok_or(Error::NotAnImage)?;
209            let mut dst_map = dst_u8.map_mut()?;
210            dst_map.as_mut_slice().fill(0);
211        }
212    }
213    Ok(())
214}
215
216/// Whether a source-crop origin is safe for the fused NV→planar strip path
217/// (`convert_nv_to_planar_fused`'s `region` parameter). NV12 (4:2:0)
218/// subsamples chroma both directions, so an odd `top` would desync the
219/// luma/chroma row pairing; NV16 (4:2:2) subsamples only horizontally, so
220/// only `left` must be even; NV24 (4:4:4) carries full-resolution chroma and
221/// has no alignment constraint. Misaligned origins fall through to the
222/// general path rather than snapping or shifting.
223fn chroma_alignment_ok(fmt: PixelFormat, r: Rect) -> bool {
224    match fmt {
225        PixelFormat::Nv12 => r.left.is_multiple_of(2) && r.top.is_multiple_of(2),
226        PixelFormat::Nv16 => r.left.is_multiple_of(2),
227        PixelFormat::Nv24 => true,
228        _ => false,
229    }
230}
231
232/// Compute row stride for a packed-format Tensor<u8> image given its format.
233fn row_stride_for(width: usize, fmt: PixelFormat) -> usize {
234    use edgefirst_tensor::PixelLayout;
235    match fmt.layout() {
236        PixelLayout::Packed => width * fmt.channels(),
237        PixelLayout::Planar | PixelLayout::SemiPlanar => width,
238        _ => width, // fallback for non-exhaustive
239    }
240}
241
242/// Read the effective row stride from a tensor, falling back to the computed
243/// minimum stride if the tensor has no explicit stride set. This correctly
244/// handles tensors with GPU pitch-alignment padding (e.g., from
245/// `ImageProcessor::create_image()` or codec strided decode).
246fn tensor_row_stride(tensor: &Tensor<u8>) -> usize {
247    tensor.effective_row_stride().unwrap_or_else(|| {
248        let w = tensor.width().unwrap_or(0);
249        let fmt = tensor.format().unwrap_or(PixelFormat::Rgb);
250        row_stride_for(w, fmt)
251    })
252}
253
254/// The `(rows, row_bytes)` of an image tensor's **logical** pixel surface: how
255/// many rows a converter may write, and how many bytes of each row are pixels.
256///
257/// Everything between `row_bytes` and [`tensor_row_stride`] is off-limits. For
258/// an allocation-padded tensor those bytes are dead padding; for a
259/// [`Tensor::view`](edgefirst_tensor::Tensor::view) destination they are the
260/// **parent image's neighbouring columns**, so a writer that treats the mapped
261/// slice as one flat buffer both mis-places its own rows and corrupts pixels
262/// that are not its to write.
263fn logical_surface(tensor: &Tensor<u8>) -> Result<(usize, usize)> {
264    use edgefirst_tensor::PixelLayout;
265    let fmt = tensor.format().ok_or(Error::NotAnImage)?;
266    let w = tensor.width().ok_or(Error::NotAnImage)?;
267    let h = tensor.height().ok_or(Error::NotAnImage)?;
268    Ok(match fmt.layout() {
269        PixelLayout::Packed => (h, w * fmt.channels()),
270        PixelLayout::Planar => (fmt.channels() * h, w),
271        PixelLayout::SemiPlanar => (fmt.combined_plane_height(h).unwrap_or(h), w),
272        // `PixelLayout` is non-exhaustive; treat any future layout as one row
273        // per shape row at the tensor's own pitch (see `row_stride_for`).
274        _ => (h, row_stride_for(w, fmt)),
275    })
276}
277
278/// Iterate `(src_row, dst_row)` pairs over a pair of image surfaces, each row
279/// clipped to its own logical width so neither side's stride padding — nor a
280/// view destination's neighbouring parent pixels — is read or written.
281///
282/// Callers must have validated both surfaces with [`guard_plane`] first.
283fn packed_row_pairs<'s, 'd>(
284    src: &'s [u8],
285    src_stride: usize,
286    src_row_bytes: usize,
287    dst: &'d mut [u8],
288    dst_stride: usize,
289    dst_row_bytes: usize,
290    rows: usize,
291) -> impl Iterator<Item = (&'s [u8], &'d mut [u8])> {
292    src.chunks(src_stride)
293        .zip(dst.chunks_mut(dst_stride))
294        .take(rows)
295        .map(move |(s, d)| (&s[..src_row_bytes], &mut d[..dst_row_bytes]))
296}
297
298/// Split a contiguous semi-planar (NV12/NV16/NV24) tensor's mapped bytes into
299/// `(luma, chroma)` planes at the `stride * src_h` boundary, validating the map
300/// holds the full combined plane first. A bare `split_at` would panic if an
301/// imported tensor's caller-supplied dimensions/stride exceed its actual buffer
302/// (untrusted input), so this returns `Error::InvalidShape` instead.
303fn split_semi_planar(
304    bytes: &[u8],
305    stride: usize,
306    src_h: usize,
307    fmt: PixelFormat,
308) -> Result<(&[u8], &[u8])> {
309    let total_h = fmt.combined_plane_height(src_h).unwrap_or(src_h);
310    let need = stride.checked_mul(total_h).ok_or_else(|| {
311        Error::InvalidShape(format!(
312            "{fmt:?} plane size overflow (stride={stride}, h={src_h})"
313        ))
314    })?;
315    if bytes.len() < need {
316        return Err(Error::InvalidShape(format!(
317            "{fmt:?} source has {} bytes but needs {need} (stride={stride}, h={src_h})",
318            bytes.len()
319        )));
320    }
321    Ok(bytes.split_at(stride * src_h))
322}
323
324/// Mutable mirror of [`split_semi_planar`]: split a contiguous semi-planar
325/// destination's mapped bytes into `(luma, chroma)` planes at the
326/// `stride * dst_h` boundary, validating the map holds the full combined plane
327/// first. A bare `split_at_mut` would panic if a caller-supplied (untrusted)
328/// destination's declared dimensions/stride exceed its actual buffer, so this
329/// returns `Error::InvalidShape` instead.
330fn split_semi_planar_mut(
331    bytes: &mut [u8],
332    stride: usize,
333    dst_h: usize,
334    fmt: PixelFormat,
335) -> Result<(&mut [u8], &mut [u8])> {
336    let total_h = fmt.combined_plane_height(dst_h).unwrap_or(dst_h);
337    let need = stride.checked_mul(total_h).ok_or_else(|| {
338        Error::InvalidShape(format!(
339            "{fmt:?} plane size overflow (stride={stride}, combined_h={total_h})"
340        ))
341    })?;
342    if bytes.len() < need {
343        return Err(Error::InvalidShape(format!(
344            "{fmt:?} destination has {} bytes but needs {need} (stride={stride}, combined_h={total_h})",
345            bytes.len()
346        )));
347    }
348    Ok(bytes.split_at_mut(stride * dst_h))
349}
350
351/// Validate that a mapped plane buffer of `buf_len` bytes can hold `rows` rows
352/// of `stride` bytes each, with `row_bytes` valid bytes per row. Returns
353/// `Error::InvalidShape` (instead of letting a later row slice panic) when a
354/// caller-supplied stride/shape exceeds the actual allocation. `what` labels the
355/// buffer in the error message.
356fn guard_plane(
357    buf_len: usize,
358    stride: usize,
359    rows: usize,
360    row_bytes: usize,
361    what: &str,
362) -> Result<()> {
363    let need = stride.checked_mul(rows).ok_or_else(|| {
364        Error::InvalidShape(format!(
365            "{what} plane size overflow (stride={stride}, rows={rows})"
366        ))
367    })?;
368    if row_bytes > stride || buf_len < need {
369        return Err(Error::InvalidShape(format!(
370            "{what} buffer too small: {buf_len} bytes, need {need} (stride={stride}, rows={rows}, row_bytes={row_bytes})"
371        )));
372    }
373    Ok(())
374}
375
376/// Apply XOR 0x80 bias to color channels only, preserving alpha.
377///
378/// Matches GL int8 shader behavior: `vec4(int8_bias(c.rgb), c.a)`.
379/// For formats without alpha, XORs every byte (fast path).
380pub(crate) fn apply_int8_xor_bias(data: &mut [u8], fmt: PixelFormat) {
381    use edgefirst_tensor::PixelLayout;
382    if !fmt.has_alpha() {
383        for b in data.iter_mut() {
384            *b ^= 0x80;
385        }
386    } else if fmt.layout() == PixelLayout::Planar {
387        // Planar with alpha (e.g. PlanarRgba): XOR color planes, skip alpha plane.
388        let channels = fmt.channels();
389        let plane_size = data.len() / channels;
390        for b in data[..plane_size * (channels - 1)].iter_mut() {
391            *b ^= 0x80;
392        }
393    } else {
394        // Packed with alpha (Rgba, Bgra): XOR color bytes, skip alpha byte.
395        let channels = fmt.channels();
396        for pixel in data.chunks_exact_mut(channels) {
397            for b in &mut pixel[..channels - 1] {
398                *b ^= 0x80;
399            }
400        }
401    }
402}
403
404/// Row-confined [`apply_int8_xor_bias`] for a destination whose row pitch may
405/// exceed its pixel bytes — an allocation-padded tensor, or a `Tensor::view()`
406/// whose pitch is the parent's and whose trailing bytes are the parent's
407/// neighbouring pixels. The `I8` post-pass of the CPU convert and of the G2D
408/// blit alike.
409pub(crate) fn apply_int8_xor_bias_rows(tensor: &mut Tensor<u8>, fmt: PixelFormat) -> Result<()> {
410    use edgefirst_tensor::PixelLayout;
411    let (rows, row_bytes) = logical_surface(tensor)?;
412    let stride = tensor_row_stride(tensor);
413    // A planar alpha channel is a whole trailing plane, so the rows to bias are
414    // the leading `channels - 1` planes rather than a prefix of each row.
415    let color_rows = if fmt.has_alpha() && fmt.layout() == PixelLayout::Planar {
416        rows / fmt.channels() * (fmt.channels() - 1)
417    } else {
418        rows
419    };
420    // Within a colour row the packed-alpha skip still applies; a planar row is
421    // all colour, so bias it as a format without alpha.
422    let row_fmt = if fmt.layout() == PixelLayout::Planar {
423        PixelFormat::Grey
424    } else {
425        fmt
426    };
427    // Read-modify-write: a write-only map would not make device writes visible.
428    let mut map = tensor.map_mut()?;
429    let buf = map.as_mut_slice();
430    guard_plane(buf.len(), stride, rows, row_bytes, "int8 bias dst")?;
431    for row in buf.chunks_mut(stride).take(color_rows) {
432        apply_int8_xor_bias(&mut row[..row_bytes], row_fmt);
433    }
434    Ok(())
435}
436
437impl CPUProcessor {
438    /// Creates a new CPUConverter with bilinear resizing.
439    pub fn new() -> Self {
440        Self::new_bilinear()
441    }
442
443    /// The resampler for `mode`. Bilinear takes two taps per axis at every
444    /// scale, as the GL backend and OpenCV `INTER_LINEAR` sample.
445    fn resize_alg(mode: crate::Interpolation) -> fast_image_resize::ResizeAlg {
446        match mode {
447            crate::Interpolation::Nearest => fast_image_resize::ResizeAlg::Nearest,
448            crate::Interpolation::Bilinear => {
449                fast_image_resize::ResizeAlg::Interpolation(fast_image_resize::FilterType::Bilinear)
450            }
451        }
452    }
453
454    /// Creates a new CPUConverter with bilinear resizing.
455    fn new_bilinear() -> Self {
456        Self::with_interpolation(crate::Interpolation::Bilinear)
457    }
458
459    /// Creates a new CPUConverter resampling with `mode`.
460    fn with_interpolation(mode: crate::Interpolation) -> Self {
461        let resizer = fast_image_resize::Resizer::new();
462        let options = fast_image_resize::ResizeOptions::new()
463            .resize_alg(Self::resize_alg(mode))
464            .use_alpha(false);
465
466        log::debug!("CPUConverter created");
467        Self {
468            resizer,
469            options,
470            colors: crate::DEFAULT_COLORS_U8,
471            widen_scratch: None,
472            resize_destride_scratch: Vec::new(),
473            resize_dst_destride_scratch: Vec::new(),
474            nv_strip_scratch: Vec::new(),
475            nv_strip_y_pack: Vec::new(),
476            nv_strip_uv_pack: Vec::new(),
477            #[cfg(test)]
478            fused_hits: 0,
479            #[cfg(test)]
480            last_tmp_dims: None,
481            convert_tmp: None,
482            convert_tmp2: None,
483            convert_src_sub: None,
484        }
485    }
486
487    /// Sets how resizing converts resample (see [`crate::Interpolation`]):
488    /// nearest-neighbour, or the bilinear filter of [`Self::new`].
489    pub fn set_interpolation(&mut self, mode: crate::Interpolation) {
490        self.options = self.options.clone().resize_alg(Self::resize_alg(mode));
491    }
492
493    /// Creates a new CPUConverter with nearest neighbor resizing.
494    pub fn new_nearest() -> Self {
495        Self::with_interpolation(crate::Interpolation::Nearest)
496    }
497
498    /// Test-only accessor for the `fused_hits` counter (see the field doc).
499    #[cfg(test)]
500    pub(super) fn fused_hits(&self) -> u64 {
501        self.fused_hits
502    }
503
504    /// Test-only accessor for the dimensions of the pre-resize intermediate the
505    /// last `convert_u8` allocated (see the `last_tmp_dims` field doc).
506    #[cfg(test)]
507    pub(super) fn last_tmp_dims(&self) -> Option<(usize, usize)> {
508        self.last_tmp_dims
509    }
510
511    pub(crate) fn support_conversion_pf(src: PixelFormat, dst: PixelFormat) -> bool {
512        use PixelFormat::*;
513        matches!(
514            (src, dst),
515            (Nv12, Rgb)
516                | (Nv12, Rgba)
517                | (Nv12, Grey)
518                | (Nv16, Rgb)
519                | (Nv16, Rgba)
520                | (Nv16, Bgra)
521                | (Nv24, Rgb)
522                | (Nv24, Rgba)
523                | (Nv24, Grey)
524                | (Nv24, Bgra)
525                | (Yuyv, Rgb)
526                | (Yuyv, Rgba)
527                | (Yuyv, Grey)
528                | (Yuyv, Yuyv)
529                | (Yuyv, PlanarRgb)
530                | (Yuyv, PlanarRgba)
531                | (Yuyv, Nv16)
532                | (Vyuy, Rgb)
533                | (Vyuy, Rgba)
534                | (Vyuy, Grey)
535                | (Vyuy, Vyuy)
536                | (Vyuy, PlanarRgb)
537                | (Vyuy, PlanarRgba)
538                | (Vyuy, Nv16)
539                | (Rgba, Rgb)
540                | (Rgba, Rgba)
541                | (Rgba, Grey)
542                | (Rgba, Yuyv)
543                | (Rgba, PlanarRgb)
544                | (Rgba, PlanarRgba)
545                | (Rgba, Nv16)
546                | (Rgb, Rgb)
547                | (Rgb, Rgba)
548                | (Rgb, Grey)
549                | (Rgb, Yuyv)
550                | (Rgb, PlanarRgb)
551                | (Rgb, PlanarRgba)
552                | (Rgb, Nv16)
553                | (Grey, Rgb)
554                | (Grey, Rgba)
555                | (Grey, Grey)
556                | (Grey, Yuyv)
557                | (Grey, PlanarRgb)
558                | (Grey, PlanarRgba)
559                | (Grey, Nv16)
560                | (Nv12, Bgra)
561                | (Yuyv, Bgra)
562                | (Vyuy, Bgra)
563                | (Rgba, Bgra)
564                | (Rgb, Bgra)
565                | (Grey, Bgra)
566                | (Bgra, Bgra)
567                | (PlanarRgb, Rgb)
568                | (PlanarRgb, Rgba)
569                | (PlanarRgba, Rgb)
570                | (PlanarRgba, Rgba)
571                | (PlanarRgb, Bgra)
572                | (PlanarRgba, Bgra)
573        )
574    }
575
576    /// Format conversion dispatch for Tensor<u8> with PixelFormat metadata.
577    pub(crate) fn convert_format_pf(
578        src: &Tensor<u8>,
579        dst: &mut Tensor<u8>,
580        src_fmt: PixelFormat,
581        dst_fmt: PixelFormat,
582        cp: ColorParams,
583    ) -> Result<()> {
584        let _timer = FunctionTimer::new(format!(
585            "ImageProcessor::convert_format {} to {}",
586            src_fmt, dst_fmt,
587        ));
588
589        use PixelFormat::*;
590        match (src_fmt, dst_fmt) {
591            (Nv12, Rgb) => Self::convert_nv12_to_rgb(src, dst, cp),
592            (Nv12, Rgba) => Self::convert_nv12_to_rgba(src, dst, cp),
593            (Nv12, Grey) => Self::convert_nv12_to_grey(src, dst, cp),
594            (Yuyv, Rgb) => Self::convert_yuyv_to_rgb(src, dst, cp),
595            (Yuyv, Rgba) => Self::convert_yuyv_to_rgba(src, dst, cp),
596            (Yuyv, Grey) => Self::convert_yuyv_to_grey(src, dst, cp),
597            (Yuyv, Yuyv) => Self::copy_image(src, dst),
598            (Yuyv, PlanarRgb) => Self::convert_yuyv_to_8bps(src, dst, cp),
599            (Yuyv, PlanarRgba) => Self::convert_yuyv_to_prgba(src, dst, cp),
600            (Yuyv, Nv16) => Self::convert_yuyv_to_nv16(src, dst),
601            (Vyuy, Rgb) => Self::convert_vyuy_to_rgb(src, dst, cp),
602            (Vyuy, Rgba) => Self::convert_vyuy_to_rgba(src, dst, cp),
603            (Vyuy, Grey) => Self::convert_vyuy_to_grey(src, dst, cp),
604            (Vyuy, Vyuy) => Self::copy_image(src, dst),
605            (Vyuy, PlanarRgb) => Self::convert_vyuy_to_8bps(src, dst, cp),
606            (Vyuy, PlanarRgba) => Self::convert_vyuy_to_prgba(src, dst, cp),
607            (Vyuy, Nv16) => Self::convert_vyuy_to_nv16(src, dst),
608            (Rgba, Rgb) => Self::convert_rgba_to_rgb(src, dst),
609            (Rgba, Rgba) => Self::copy_image(src, dst),
610            (Rgba, Grey) => Self::convert_rgba_to_grey(src, dst),
611            (Rgba, Yuyv) => Self::convert_rgba_to_yuyv(src, dst, cp),
612            (Rgba, PlanarRgb) => Self::convert_rgba_to_8bps(src, dst),
613            (Rgba, PlanarRgba) => Self::convert_rgba_to_prgba(src, dst),
614            (Rgba, Nv16) => Self::convert_rgba_to_nv16(src, dst, cp),
615            (Rgb, Rgb) => Self::copy_image(src, dst),
616            (Rgb, Rgba) => Self::convert_rgb_to_rgba(src, dst),
617            (Rgb, Grey) => Self::convert_rgb_to_grey(src, dst),
618            (Rgb, Yuyv) => Self::convert_rgb_to_yuyv(src, dst, cp),
619            (Rgb, PlanarRgb) => Self::convert_rgb_to_8bps(src, dst),
620            (Rgb, PlanarRgba) => Self::convert_rgb_to_prgba(src, dst),
621            (Rgb, Nv16) => Self::convert_rgb_to_nv16(src, dst, cp),
622            (Grey, Rgb) => Self::convert_grey_to_rgb(src, dst),
623            (Grey, Rgba) => Self::convert_grey_to_rgba(src, dst),
624            (Grey, Grey) => Self::copy_image(src, dst),
625            (Grey, Yuyv) => Self::convert_grey_to_yuyv(src, dst, cp),
626            (Grey, PlanarRgb) => Self::convert_grey_to_8bps(src, dst),
627            (Grey, PlanarRgba) => Self::convert_grey_to_prgba(src, dst),
628            (Grey, Nv16) => Self::convert_grey_to_nv16(src, dst, cp),
629
630            // the following converts are added for use in testing
631            (Nv16, Rgb) => Self::convert_nv16_to_rgb(src, dst, cp),
632            (Nv16, Rgba) => Self::convert_nv16_to_rgba(src, dst, cp),
633            (Nv24, Rgb) => Self::convert_nv24_to_rgb(src, dst, cp),
634            (Nv24, Rgba) => Self::convert_nv24_to_rgba(src, dst, cp),
635            (Nv24, Grey) => Self::convert_nv24_to_grey(src, dst, cp),
636            (PlanarRgb, Rgb) => Self::convert_8bps_to_rgb(src, dst),
637            (PlanarRgb, Rgba) => Self::convert_8bps_to_rgba(src, dst),
638            (PlanarRgba, Rgb) => Self::convert_prgba_to_rgb(src, dst),
639            (PlanarRgba, Rgba) => Self::convert_prgba_to_rgba(src, dst),
640
641            // BGRA destination: convert to RGBA layout, then swap R and B
642            (Bgra, Bgra) => Self::copy_image(src, dst),
643            (Nv12, Bgra) => {
644                Self::convert_nv12_to_rgba(src, dst, cp)?;
645                Self::swizzle_rb_4chan(dst)
646            }
647            (Nv16, Bgra) => {
648                Self::convert_nv16_to_rgba(src, dst, cp)?;
649                Self::swizzle_rb_4chan(dst)
650            }
651            (Nv24, Bgra) => {
652                Self::convert_nv24_to_rgba(src, dst, cp)?;
653                Self::swizzle_rb_4chan(dst)
654            }
655            (Yuyv, Bgra) => {
656                Self::convert_yuyv_to_rgba(src, dst, cp)?;
657                Self::swizzle_rb_4chan(dst)
658            }
659            (Vyuy, Bgra) => {
660                Self::convert_vyuy_to_rgba(src, dst, cp)?;
661                Self::swizzle_rb_4chan(dst)
662            }
663            (Rgba, Bgra) => {
664                Self::copy_image(src, dst)?;
665                Self::swizzle_rb_4chan(dst)
666            }
667            (Rgb, Bgra) => {
668                Self::convert_rgb_to_rgba(src, dst)?;
669                Self::swizzle_rb_4chan(dst)
670            }
671            (Grey, Bgra) => {
672                Self::convert_grey_to_rgba(src, dst)?;
673                Self::swizzle_rb_4chan(dst)
674            }
675            (PlanarRgb, Bgra) => {
676                Self::convert_8bps_to_rgba(src, dst)?;
677                Self::swizzle_rb_4chan(dst)
678            }
679            (PlanarRgba, Bgra) => {
680                Self::convert_prgba_to_rgba(src, dst)?;
681                Self::swizzle_rb_4chan(dst)
682            }
683
684            (s, d) => Err(Error::NotSupported(format!("Conversion from {s} to {d}",))),
685        }
686    }
687
688    /// Tensor<u8>-based fill_image_outside_crop. `device_interior` marks an
689    /// interior a device rendered, which makes this border a partial write.
690    pub(crate) fn fill_image_outside_crop_u8(
691        dst: &mut Tensor<u8>,
692        rgba: [u8; 4],
693        crop: Rect,
694        device_interior: bool,
695    ) -> Result<()> {
696        let dst_fmt = dst.format().unwrap();
697        let dst_w = dst.width().unwrap();
698        let dst_h = dst.height().unwrap();
699        // Resolve the YUV fill encoding from the destination tensor so the
700        // border color matches the same matrix/range as a later YUV→RGB
701        // decode of this image. RGB/Grey fills ignore these params.
702        let cm = crate::colorimetry::resolve_colorimetry(dst.colorimetry(), dst.height());
703        let cp = ColorParams {
704            matrix: crate::colorimetry::yuv_matrix(cm.encoding.unwrap()),
705            range: crate::colorimetry::yuv_range(cm.range.unwrap()),
706            encoding: cm.encoding.unwrap(),
707            range_kind: cm.range.unwrap(),
708            src_full_range: cm.range == Some(edgefirst_tensor::ColorRange::Full),
709            dst_full_range: cm.range == Some(edgefirst_tensor::ColorRange::Full),
710        };
711        let dst_stride = tensor_row_stride(dst);
712        let mut dst_map = if device_interior {
713            dst.map_for_partial_write()?
714        } else {
715            dst.map_for_write()?
716        };
717        let dst_tup = (dst_map.as_mut_slice(), dst_w, dst_h, dst_stride);
718        Self::fill_outside_crop_dispatch(dst_tup, dst_fmt, rgba, crop, cp)
719    }
720
721    /// Common fill dispatch by format. The tuple is
722    /// `(bytes, logical_width, logical_height, row_stride)` — the stride is the
723    /// destination's real byte pitch, which for a `view()` destination is the
724    /// parent image's, not `width × bpp`.
725    fn fill_outside_crop_dispatch(
726        dst: (&mut [u8], usize, usize, usize),
727        fmt: PixelFormat,
728        rgba: [u8; 4],
729        crop: Rect,
730        cp: ColorParams,
731    ) -> Result<()> {
732        use PixelFormat::*;
733        match fmt {
734            Rgba | Bgra => Self::fill_image_outside_crop_(dst, rgba, crop),
735            Rgb => Self::fill_image_outside_crop_(dst, Self::rgba_to_rgb(rgba), crop),
736            Grey => Self::fill_image_outside_crop_(dst, Self::rgba_to_grey(rgba), crop),
737            Yuyv => {
738                let (bytes, w, h, stride) = dst;
739                let yuyv = Self::rgba_to_yuyv(rgba, cp);
740                // Bulk fill in 4-byte [Y0,U,Y1,V] macropixels; crop bounds in
741                // macropixel units so a shared chroma pair is never split.
742                Self::fill_image_outside_crop_(
743                    (&mut *bytes, w / 2, h, stride),
744                    yuyv,
745                    Rect::new(crop.left / 2, crop.top, crop.width.div_ceil(2), crop.height),
746                )?;
747                // An odd width leaves a trailing unpaired pixel that the
748                // macropixel walk above (w / 2 units) structurally never
749                // reaches — the same trailing-pixel class the odd-width YUYV
750                // encoders handle. Its 2 bytes are [Y, U] (a row is w × 2
751                // bytes, so there is no room for its V). Fill it on every row
752                // where the last column lies outside the crop, judged in
753                // pixel units against the original crop.
754                if w % 2 == 1 {
755                    let last = w - 1;
756                    let col_outside = last < crop.left || last >= crop.left + crop.width;
757                    for y in 0..h {
758                        let row_outside = y < crop.top || y >= crop.top + crop.height;
759                        if row_outside || col_outside {
760                            let off = y * stride + last * 2;
761                            bytes[off] = yuyv[0];
762                            bytes[off + 1] = yuyv[1];
763                        }
764                    }
765                }
766                Ok(())
767            }
768            PlanarRgb => Self::fill_image_outside_crop_planar(dst, Self::rgba_to_rgb(rgba), crop),
769            PlanarRgba => Self::fill_image_outside_crop_planar(dst, rgba, crop),
770            Nv16 => {
771                let yuyv = Self::rgba_to_yuyv(rgba, cp);
772                Self::fill_image_outside_crop_yuv_semiplanar(dst, yuyv[0], [yuyv[1], yuyv[3]], crop)
773            }
774            _ => Err(Error::Internal(format!(
775                "Found unexpected destination {fmt}",
776            ))),
777        }
778    }
779}
780
781/// Colour parameters for a convert from `src` to `dst`, resolved once from
782/// each tensor's effective colorimetry.
783fn color_params(src: &TensorDyn, dst: &TensorDyn) -> (ColorParams, ColorParams) {
784    // Resolve per-tensor colorimetry once, at the use site, without
785    // mutating either tensor. YUV→RGB conversions take their matrix/range
786    // from the source; RGB→YUV conversions from the destination. The grey/
787    // luma expansion is gated on the resolved range of the relevant side.
788    let src_cm = crate::colorimetry::effective_colorimetry(src);
789    let dst_cm = crate::colorimetry::effective_colorimetry(dst);
790    let src_full = src_cm.range == Some(edgefirst_tensor::ColorRange::Full);
791    let dst_full = dst_cm.range == Some(edgefirst_tensor::ColorRange::Full);
792    let src_params = ColorParams {
793        matrix: crate::colorimetry::yuv_matrix(src_cm.encoding.unwrap()),
794        range: crate::colorimetry::yuv_range(src_cm.range.unwrap()),
795        encoding: src_cm.encoding.unwrap(),
796        range_kind: src_cm.range.unwrap(),
797        src_full_range: src_full,
798        dst_full_range: dst_full,
799    };
800    let dst_params = ColorParams {
801        matrix: crate::colorimetry::yuv_matrix(dst_cm.encoding.unwrap()),
802        range: crate::colorimetry::yuv_range(dst_cm.range.unwrap()),
803        encoding: dst_cm.encoding.unwrap(),
804        range_kind: dst_cm.range.unwrap(),
805        src_full_range: src_full,
806        dst_full_range: dst_full,
807    };
808    (src_params, dst_params)
809}
810
811/// `ReadWrite` when a convert writes only part of `dst` and keeps the rest (a
812/// view, or a placement with no fill colour), else `None`: such a write needs
813/// a cache-invalidating map.
814fn partial_dst_access(dst: &TensorDyn, crop: &ResolvedCrop) -> edgefirst_tensor::CpuAccess {
815    let full = |r: &Rect| {
816        r.left == 0 && r.top == 0 && Some(r.width) == dst.width() && Some(r.height) == dst.height()
817    };
818    let keeps_outside = crop.dst_color.is_none() && crop.dst_rect.is_some_and(|r| !full(&r));
819    if dst.is_view() || keeps_outside {
820        edgefirst_tensor::CpuAccess::ReadWrite
821    } else {
822        edgefirst_tensor::CpuAccess::None
823    }
824}
825
826/// The CPU access a CPU convert from a `src` source needs on a `dst_fmt`/
827/// `dst_dtype` destination it writes directly (not through the normalization
828/// scratch): `ReadWrite` when a pass reads back what was written — the `I8`
829/// bias, the BGRA swizzle — else `Write`. `src: None` assumes any source.
830pub(crate) fn convert_dst_access(
831    src: Option<PixelFormat>,
832    dst_fmt: PixelFormat,
833    dst_dtype: DType,
834) -> edgefirst_tensor::CpuAccess {
835    use edgefirst_tensor::CpuAccess;
836    let swizzles = dst_fmt == PixelFormat::Bgra && src != Some(PixelFormat::Bgra);
837    match dst_dtype {
838        DType::I8 => CpuAccess::ReadWrite,
839        DType::U8 if swizzles => CpuAccess::ReadWrite,
840        _ => CpuAccess::Write,
841    }
842}
843
844/// Mask drawing blends into `dst`, so it needs both directions; the
845/// background is only read.
846fn require_draw_access(dst: &TensorDyn, background: Option<&TensorDyn>) -> Result<()> {
847    dst.cpu_access()
848        .require(edgefirst_tensor::CpuAccess::ReadWrite)?;
849    if let Some(bg) = background {
850        bg.cpu_access().require(edgefirst_tensor::CpuAccess::Read)?;
851    }
852    Ok(())
853}
854
855impl ImageProcessorTrait for CPUProcessor {
856    fn convert(
857        &mut self,
858        src: &TensorDyn,
859        dst: &mut TensorDyn,
860        options: Option<crate::ConvertOptions>,
861    ) -> Result<()> {
862        src.cpu_access()
863            .require(edgefirst_tensor::CpuAccess::Read)?;
864        dst.cpu_access()
865            .require(edgefirst_tensor::CpuAccess::Write)?;
866        let options = options.unwrap_or_default();
867        let (rotation, flip, crop) = (
868            options.get_rotation(),
869            options.get_flip(),
870            options.get_crop(),
871        );
872        let crop = crop.resolve(
873            src.width().unwrap_or(0),
874            src.height().unwrap_or(0),
875            dst.width().unwrap_or(0),
876            dst.height().unwrap_or(0),
877            options.get_placement(),
878        )?;
879        dst.cpu_access().require(partial_dst_access(dst, &crop))?;
880        match crate::options::output_map_for(&options, dst, crop.dst_rect.is_some())? {
881            None => {
882                if let Some(dst_fmt) = dst.format() {
883                    dst.cpu_access().require(convert_dst_access(
884                        src.format(),
885                        dst_fmt,
886                        dst.dtype(),
887                    ))?;
888                }
889                self.convert_impl(src, dst, rotation, flip, crop)
890            }
891            Some((map, pad_output)) => {
892                self.convert_mapped(src, dst, rotation, flip, crop, &map, pad_output)
893            }
894        }
895    }
896
897    fn draw_decoded_masks(
898        &mut self,
899        dst: &mut TensorDyn,
900        detect: &[DetectBox],
901        segmentation: &[Segmentation],
902        overlay: crate::MaskOverlay<'_>,
903    ) -> Result<()> {
904        // CPU is the terminal fallback — it must always produce the full
905        // output, never assume the caller cleared dst. Every call writes
906        // the base layer first (bg copy or zero fill) and then the masks.
907        require_draw_access(dst, overlay.background)?;
908        prepare_dst_base_cpu(dst, overlay.background)?;
909        let dst = dst.as_typed_mut::<u8>().ok_or(Error::NotAnImage)?;
910        self.draw_decoded_masks_impl(
911            dst,
912            detect,
913            segmentation,
914            overlay.opacity,
915            overlay.color_mode,
916        )
917    }
918
919    fn draw_proto_masks(
920        &mut self,
921        dst: &mut TensorDyn,
922        detect: &[DetectBox],
923        proto_data: &ProtoData,
924        overlay: crate::MaskOverlay<'_>,
925    ) -> Result<()> {
926        require_draw_access(dst, overlay.background)?;
927        prepare_dst_base_cpu(dst, overlay.background)?;
928        let dst = dst.as_typed_mut::<u8>().ok_or(Error::NotAnImage)?;
929        self.draw_proto_masks_impl(
930            dst,
931            detect,
932            proto_data,
933            overlay.opacity,
934            overlay.letterbox,
935            overlay.color_mode,
936        )
937    }
938
939    fn set_class_colors(&mut self, colors: &[[u8; 4]]) -> Result<()> {
940        for (c, new_c) in self.colors.iter_mut().zip(colors.iter()) {
941            *c = *new_c;
942        }
943        Ok(())
944    }
945}
946
947// Internal methods — dtype-aware dispatch layer.
948impl CPUProcessor {
949    /// Convert into a u8 scratch, then map it into `dst` with `map`, and
950    /// overwrite the letterbox band with `pad_output` when set.
951    #[allow(clippy::too_many_arguments)]
952    fn convert_mapped(
953        &mut self,
954        src: &TensorDyn,
955        dst: &mut TensorDyn,
956        rotation: Rotation,
957        flip: Flip,
958        crop: ResolvedCrop,
959        map: &crate::options::OutputMap,
960        pad_output: Option<[f32; 4]>,
961    ) -> Result<()> {
962        let src_u8 = src
963            .as_typed::<u8>()
964            .ok_or_else(|| Error::NotSupported(format!("dtype {} source", src.dtype())))?;
965        let src_fmt = src.format().ok_or(Error::NotAnImage)?;
966        let dst_fmt = dst.format().ok_or(Error::NotAnImage)?;
967        let dw = dst.width().ok_or(Error::NotAnImage)?;
968        let dh = dst.height().ok_or(Error::NotAnImage)?;
969        let mut tmp = self.take_scratch(dw, dh, dst_fmt)?;
970        let (src_params, dst_params) = color_params(src, dst);
971        let result = (|| {
972            let tmp_u8 = tmp.as_typed_mut::<u8>().unwrap();
973            self.convert_u8(
974                src_u8, tmp_u8, src_fmt, dst_fmt, rotation, flip, crop, src_params, dst_params,
975            )?;
976            normalize::write_mapped(tmp.as_typed::<u8>().unwrap(), dst, map)?;
977            if let (Some(pad), Some(rect)) = (pad_output, crop.dst_rect) {
978                let values = map.pad_values([0; 4], Some(pad));
979                normalize::fill_outside(dst, rect, values)?;
980            }
981            Ok(())
982        })();
983        self.widen_scratch = Some(tmp);
984        result
985    }
986
987    /// The cached u8 scratch when it matches, else a new one.
988    fn take_scratch(&mut self, w: usize, h: usize, fmt: PixelFormat) -> Result<TensorDyn> {
989        let matches = self.widen_scratch.as_ref().is_some_and(|t| {
990            t.width() == Some(w) && t.height() == Some(h) && t.format() == Some(fmt)
991        });
992        if matches {
993            return Ok(self.widen_scratch.take().unwrap());
994        }
995        Ok(TensorDyn::image(
996            w,
997            h,
998            fmt,
999            DType::U8,
1000            Some(TensorMemory::Mem),
1001            edgefirst_tensor::CpuAccess::ReadWrite,
1002        )?)
1003    }
1004
1005    /// Top-level conversion dispatcher: handles dtype combinations.
1006    pub(crate) fn convert_impl(
1007        &mut self,
1008        src: &TensorDyn,
1009        dst: &mut TensorDyn,
1010        rotation: Rotation,
1011        flip: Flip,
1012        crop: ResolvedCrop,
1013    ) -> Result<()> {
1014        let src_fmt = src.format().ok_or(Error::NotAnImage)?;
1015        let dst_fmt = dst.format().ok_or(Error::NotAnImage)?;
1016
1017        let (src_params, dst_params) = color_params(src, dst);
1018        match (src.dtype(), dst.dtype()) {
1019            (DType::U8, DType::U8) => {
1020                let src = src.as_typed::<u8>().unwrap();
1021                let dst = dst.as_typed_mut::<u8>().unwrap();
1022                self.convert_u8(
1023                    src, dst, src_fmt, dst_fmt, rotation, flip, crop, src_params, dst_params,
1024                )
1025            }
1026            (DType::U8, DType::I8) => {
1027                // Int8 output: reinterpret the i8 destination as u8 (layout-
1028                // identical), convert directly into it, then XOR 0x80 in-place.
1029                let src_u8 = src.as_typed::<u8>().unwrap();
1030                let dst_i8 = dst.as_typed_mut::<i8>().unwrap();
1031                // SAFETY: Tensor<i8> and Tensor<u8> are layout-identical
1032                // (same element size, no T-dependent drop glue). Same
1033                // rationale as gl::processor::tensor_i8_as_u8_mut.
1034                let dst_u8 = unsafe { &mut *(dst_i8 as *mut Tensor<i8> as *mut Tensor<u8>) };
1035                self.convert_u8(
1036                    src_u8, dst_u8, src_fmt, dst_fmt, rotation, flip, crop, src_params, dst_params,
1037                )?;
1038                // Apply XOR 0x80 bias in-place (u8 → i8 conversion)
1039                apply_int8_xor_bias_rows(dst_u8, dst_fmt)
1040            }
1041            (DType::U8, d @ (DType::F32 | DType::F16)) => {
1042                let src_u8 = src.as_typed::<u8>().unwrap();
1043                let dw = dst.width().ok_or(Error::NotAnImage)?;
1044                let dh = dst.height().ok_or(Error::NotAnImage)?;
1045                // Reuse the scratch tensor when format and dimensions match;
1046                // otherwise reallocate and cache the new scratch.  Take the
1047                // scratch out of `self` so that `convert_u8` can borrow `self`
1048                // exclusively, then restore it afterwards.
1049                let mut tmp = self.take_scratch(dw, dh, dst_fmt)?;
1050                {
1051                    let tmp_u8 = tmp.as_typed_mut::<u8>().unwrap();
1052                    self.convert_u8(
1053                        src_u8, tmp_u8, src_fmt, dst_fmt, rotation, flip, crop, src_params,
1054                        dst_params,
1055                    )?;
1056                }
1057                // Widen the u8 scratch into the float destination, then restore
1058                // the scratch for reuse on the next call.
1059                //
1060                // The scratch is tight, but `dst` need not be: an allocation-
1061                // padded float tensor, or a `Tensor::view()` whose pitch is the
1062                // parent's, has a wider row than its pixels. Widen row by row so
1063                // each output row lands at the destination's own pitch and the
1064                // bytes past it stay untouched. On a tight destination the two
1065                // pitches coincide and this is the previous flat widen.
1066                {
1067                    let tmp_u8 = tmp.as_typed::<u8>().unwrap();
1068                    let (rows, row_len) = logical_surface(tmp_u8)?;
1069                    let src_stride = tensor_row_stride(tmp_u8);
1070                    let dst_stride_bytes = dst.effective_row_stride().ok_or(Error::NotAnImage)?;
1071                    let src_map = tmp_u8.map_read()?;
1072                    guard_plane(
1073                        src_map.as_slice().len(),
1074                        src_stride,
1075                        rows,
1076                        row_len,
1077                        "widen src",
1078                    )?;
1079                    let src_rows = src_map.as_slice().chunks(src_stride).take(rows);
1080                    let elem = d.size();
1081                    if !dst_stride_bytes.is_multiple_of(elem) {
1082                        return Err(Error::InvalidShape(format!(
1083                            "{d} destination row stride {dst_stride_bytes} is not a multiple of \
1084                             the element size {elem}"
1085                        )));
1086                    }
1087                    let dst_stride = dst_stride_bytes / elem;
1088                    match d {
1089                        DType::F32 => {
1090                            let dst_t = dst.as_typed_mut::<f32>().unwrap();
1091                            let mut dst_map = dst_t.map_for_write()?;
1092                            // Counted in elements, not bytes — same invariant.
1093                            guard_plane(
1094                                dst_map.as_slice().len(),
1095                                dst_stride,
1096                                rows,
1097                                row_len,
1098                                "widen f32 dst",
1099                            )?;
1100                            // NEON-accelerated u8→f32 `/255` widen (bit-identical
1101                            // to the scalar `b as f32 / 255.0`); the scalar
1102                            // iterator form did not vectorise. See cpu::simd.
1103                            for (s, dr) in
1104                                src_rows.zip(dst_map.as_mut_slice().chunks_mut(dst_stride))
1105                            {
1106                                simd::widen_u8_to_f32_norm(s, &mut dr[..row_len]);
1107                            }
1108                        }
1109                        DType::F16 => {
1110                            let dst_t = dst.as_typed_mut::<half::f16>().unwrap();
1111                            let mut dst_map = dst_t.map_for_write()?;
1112                            guard_plane(
1113                                dst_map.as_slice().len(),
1114                                dst_stride,
1115                                rows,
1116                                row_len,
1117                                "widen f16 dst",
1118                            )?;
1119                            // u8→f16 `/255` widen; uses native FP16
1120                            // (`ucvtf`+`fdiv`) at runtime on FEAT_FP16 CPUs
1121                            // (Orin), scalar `half::f16::from_f32` elsewhere.
1122                            // See cpu::simd.
1123                            for (s, dr) in
1124                                src_rows.zip(dst_map.as_mut_slice().chunks_mut(dst_stride))
1125                            {
1126                                simd::widen_u8_to_f16_norm(s, &mut dr[..row_len]);
1127                            }
1128                        }
1129                        _ => unreachable!(),
1130                    }
1131                }
1132                self.widen_scratch = Some(tmp);
1133                Ok(())
1134            }
1135            (s, d) => Err(Error::NotSupported(format!("dtype {s} -> {d}",))),
1136        }
1137    }
1138
1139    /// Reuse `cached` if it already has dimensions `(w, h)` and pixel format
1140    /// `fmt`, otherwise allocate a fresh `Mem` image. The returned buffer's
1141    /// contents are **not** zeroed on reuse — callers must fully overwrite the
1142    /// region they later read (see the note at the convert pipeline's tmp/tmp2
1143    /// site). This amortises the per-frame `Tensor::image` `alloc_zeroed`.
1144    fn reuse_or_alloc_image(
1145        cached: Option<Tensor<u8>>,
1146        w: usize,
1147        h: usize,
1148        fmt: PixelFormat,
1149    ) -> Result<Tensor<u8>> {
1150        if let Some(t) = cached {
1151            if t.width() == Some(w) && t.height() == Some(h) && t.format() == Some(fmt) {
1152                return Ok(t);
1153            }
1154        }
1155        Ok(Tensor::<u8>::image(
1156            w,
1157            h,
1158            fmt,
1159            Some(TensorMemory::Mem),
1160            edgefirst_tensor::CpuAccess::ReadWrite,
1161        )?)
1162    }
1163
1164    /// The source sub-rectangle to convert into the pre-resize intermediate for
1165    /// a cropped convert, or `None` to keep converting the whole frame.
1166    ///
1167    /// A cropped convert only ever reads the crop rect plus the resize filter's
1168    /// halo (see [`Self::filter_halo`]), so converting the whole frame into the
1169    /// intermediate wastes work proportional to the frame — for a 4K frame
1170    /// tiled into 640x640 crops, ~22x the pixels actually needed. Returning the
1171    /// halo-grown crop lets the pre-resize convert produce a crop-sized
1172    /// intermediate instead.
1173    ///
1174    /// The returned rect only ever *grows* the crop, and is clamped to the
1175    /// frame, so the resize reads exactly the same real source pixels — and
1176    /// clamps at exactly the same frame edges — as it did with a full-frame
1177    /// intermediate. Output is byte-identical; only the buffer size changes.
1178    ///
1179    /// `None` (unchanged full-frame behaviour) for: an uncropped convert, a
1180    /// crop covering the whole frame, a source format that cannot be extracted
1181    /// (only the semi-planar NV family can — `Tensor::view` rejects non-packed
1182    /// layouts, and NV is what the 4K tiling path feeds in), and a resize
1183    /// algorithm whose filter reach is not modelled.
1184    fn pre_resize_region(
1185        &self,
1186        src_fmt: PixelFormat,
1187        (src_w, src_h): (usize, usize),
1188        (dst_w, dst_h): (usize, usize),
1189        rotation: Rotation,
1190        crop: ResolvedCrop,
1191    ) -> Option<Rect> {
1192        use PixelFormat::{Nv12, Nv16, Nv24};
1193
1194        if !matches!(src_fmt, Nv12 | Nv16 | Nv24) {
1195            return None;
1196        }
1197        let r = crop.src_rect?;
1198        let full_src = Rect {
1199            left: 0,
1200            top: 0,
1201            width: src_w,
1202            height: src_h,
1203        };
1204        if r == full_src {
1205            return None;
1206        }
1207
1208        // The resize maps the source rect onto the destination rect; a quarter
1209        // turn swaps which destination extent each source axis is scaled onto
1210        // (see `adjust_dest_rect_for_rotate_flip_dims`), and the filter halo
1211        // depends on that scale factor.
1212        let d = crop.dst_rect.unwrap_or(Rect {
1213            left: 0,
1214            top: 0,
1215            width: dst_w,
1216            height: dst_h,
1217        });
1218        let (dst_x, dst_y) = match rotation {
1219            Rotation::None | Rotation::Rotate180 => (d.width, d.height),
1220            Rotation::Clockwise90 | Rotation::CounterClockwise90 => (d.height, d.width),
1221        };
1222        let halo_x = self.filter_halo(r.width, dst_x)?;
1223        let halo_y = self.filter_halo(r.height, dst_y)?;
1224
1225        let mut left = r.left.saturating_sub(halo_x);
1226        let mut top = r.top.saturating_sub(halo_y);
1227        let mut right = (r.left + r.width + halo_x).min(src_w);
1228        let mut bottom = (r.top + r.height + halo_y).min(src_h);
1229
1230        // NV12 subsamples chroma on both axes, NV16 on the horizontal one, so
1231        // the extracted origin must land on a chroma sample boundary for the
1232        // sub-image's chroma to line up with the frame's. Snap the origin DOWN
1233        // and the far edge UP — growing only, so every pixel inside `r` keeps
1234        // exactly the neighbours it had, whatever the crop's own parity.
1235        let (align_x, align_y) = match src_fmt {
1236            Nv12 => (2, 2),
1237            Nv16 => (2, 1),
1238            _ => (1, 1),
1239        };
1240        left -= left % align_x;
1241        top -= top % align_y;
1242        right = right.next_multiple_of(align_x).min(src_w);
1243        bottom = bottom.next_multiple_of(align_y).min(src_h);
1244
1245        let grown = Rect {
1246            left,
1247            top,
1248            width: right - left,
1249            height: bottom - top,
1250        };
1251        // The halo already reaches the whole frame — extracting would be a pure
1252        // copy with no saving.
1253        (grown != full_src).then_some(grown)
1254    }
1255
1256    /// U8-to-U8 conversion: the full format conversion + resize pipeline.
1257    #[allow(clippy::too_many_arguments)]
1258    fn convert_u8(
1259        &mut self,
1260        src: &Tensor<u8>,
1261        dst: &mut Tensor<u8>,
1262        src_fmt: PixelFormat,
1263        dst_fmt: PixelFormat,
1264        rotation: Rotation,
1265        flip: Flip,
1266        crop: ResolvedCrop,
1267        src_params: ColorParams,
1268        dst_params: ColorParams,
1269    ) -> Result<()> {
1270        use PixelFormat::*;
1271
1272        #[cfg(test)]
1273        {
1274            self.last_tmp_dims = None;
1275        }
1276
1277        let src_w = src.width().unwrap();
1278        let src_h = src.height().unwrap();
1279        let dst_w = dst.width().unwrap();
1280        let dst_h = dst.height().unwrap();
1281
1282        crop.check_crop_dims(src_w, src_h, dst_w, dst_h)?;
1283
1284        // Determine intermediate format for the resize step
1285        let intermediate = match (src_fmt, dst_fmt) {
1286            (Nv12, Rgb) => Rgb,
1287            (Nv12, Rgba) => Rgba,
1288            (Nv12, Grey) => Grey,
1289            (Nv12, Yuyv) => Rgba,
1290            (Nv12, Nv16) => Rgba,
1291            (Nv12, PlanarRgb) => Rgb,
1292            (Nv12, PlanarRgba) => Rgba,
1293            (Nv16, PlanarRgb) => Rgb,
1294            (Nv16, PlanarRgba) => Rgba,
1295            (Nv24, PlanarRgb) => Rgb,
1296            (Nv24, PlanarRgba) => Rgba,
1297            (Yuyv, Rgb) => Rgb,
1298            (Yuyv, Rgba) => Rgba,
1299            (Yuyv, Grey) => Grey,
1300            (Yuyv, Yuyv) => Rgba,
1301            (Yuyv, PlanarRgb) => Rgb,
1302            (Yuyv, PlanarRgba) => Rgba,
1303            (Yuyv, Nv16) => Rgba,
1304            (Vyuy, Rgb) => Rgb,
1305            (Vyuy, Rgba) => Rgba,
1306            (Vyuy, Grey) => Grey,
1307            (Vyuy, Vyuy) => Rgba,
1308            (Vyuy, PlanarRgb) => Rgb,
1309            (Vyuy, PlanarRgba) => Rgba,
1310            (Vyuy, Nv16) => Rgba,
1311            (Rgba, Rgb) => Rgba,
1312            (Rgba, Rgba) => Rgba,
1313            (Rgba, Grey) => Grey,
1314            (Rgba, Yuyv) => Rgba,
1315            (Rgba, PlanarRgb) => Rgba,
1316            (Rgba, PlanarRgba) => Rgba,
1317            (Rgba, Nv16) => Rgba,
1318            (Rgb, Rgb) => Rgb,
1319            (Rgb, Rgba) => Rgb,
1320            (Rgb, Grey) => Grey,
1321            (Rgb, Yuyv) => Rgb,
1322            (Rgb, PlanarRgb) => Rgb,
1323            (Rgb, PlanarRgba) => Rgb,
1324            (Rgb, Nv16) => Rgb,
1325            (Grey, Rgb) => Rgb,
1326            (Grey, Rgba) => Rgba,
1327            (Grey, Grey) => Grey,
1328            (Grey, Yuyv) => Grey,
1329            (Grey, PlanarRgb) => Grey,
1330            (Grey, PlanarRgba) => Grey,
1331            (Grey, Nv16) => Grey,
1332            (Nv12, Bgra) => Rgba,
1333            (Yuyv, Bgra) => Rgba,
1334            (Vyuy, Bgra) => Rgba,
1335            (Rgba, Bgra) => Rgba,
1336            (Rgb, Bgra) => Rgb,
1337            (Grey, Bgra) => Grey,
1338            (Bgra, Bgra) => Bgra,
1339            (Nv16, Rgb) => Rgb,
1340            (Nv16, Rgba) => Rgba,
1341            (Nv16, Bgra) => Rgba,
1342            (Nv24, Rgb) => Rgb,
1343            (Nv24, Rgba) => Rgba,
1344            (Nv24, Grey) => Grey,
1345            (Nv24, Bgra) => Rgba,
1346            (PlanarRgb, Rgb) => Rgb,
1347            (PlanarRgb, Rgba) => Rgb,
1348            (PlanarRgb, Bgra) => Rgb,
1349            (PlanarRgba, Rgb) => Rgba,
1350            (PlanarRgba, Rgba) => Rgba,
1351            (PlanarRgba, Bgra) => Rgba,
1352            (s, d) => {
1353                return Err(Error::NotSupported(format!("Conversion from {s} to {d}",)));
1354            }
1355        };
1356
1357        let need_resize_flip_rotation = rotation != Rotation::None
1358            || flip != Flip::None
1359            || src_w != dst_w
1360            || src_h != dst_h
1361            || crop.src_rect.is_some_and(|c| {
1362                c != Rect {
1363                    left: 0,
1364                    top: 0,
1365                    width: src_w,
1366                    height: src_h,
1367                }
1368            })
1369            || crop.dst_rect.is_some_and(|c| {
1370                c != Rect {
1371                    left: 0,
1372                    top: 0,
1373                    width: dst_w,
1374                    height: dst_h,
1375                }
1376            });
1377
1378        // Pick the resolved colorimetry for a single conversion by its YUV
1379        // side: YUV→RGB decodes use the source side, RGB→YUV encodes the dest.
1380        let direct_is_yuv_src = matches!(src_fmt, Nv12 | Nv16 | Nv24 | Yuyv | Vyuy);
1381        let direct_params = if direct_is_yuv_src {
1382            src_params
1383        } else {
1384            dst_params
1385        };
1386
1387        // Fused NV→planar: decode the YUV source into packed RGB one
1388        // cache-resident row strip at a time and NEON-deinterleave each strip
1389        // straight into the destination planes, so the full-size packed-RGB
1390        // intermediate never round-trips through DRAM and is not reallocated
1391        // per frame. JPEG decodes to the NV family and the model wants planar
1392        // RGB, so this is the hot Orin CPU-preprocess path.
1393        //
1394        // Two shapes take this path: the whole-frame case (no crop, dst ==
1395        // src size — the original hot path, unchanged) and a **scale-
1396        // identity** source crop (crop size == destination size, no rotate/
1397        // flip, full destination placement, chroma-aligned origin) — the
1398        // primary CPU-fallback path for uniform tiling (e.g. SAHI tiles cut
1399        // from one frame). Any other shape (an actual resize, a partial
1400        // destination placement, or a chroma-misaligned origin) falls
1401        // through to the general pipeline below — never snapped or shifted
1402        // into alignment.
1403        let full_dst_rect = Rect {
1404            left: 0,
1405            top: 0,
1406            width: dst_w,
1407            height: dst_h,
1408        };
1409        let fused_region = if rotation != Rotation::None || flip != Flip::None {
1410            None
1411        } else {
1412            match crop.src_rect {
1413                None if src_w == dst_w && src_h == dst_h => Some(None),
1414                None => None,
1415                Some(r)
1416                    if r.width == dst_w
1417                        && r.height == dst_h
1418                        && crop.dst_rect.is_none_or(|d| d == full_dst_rect)
1419                        && chroma_alignment_ok(src_fmt, r) =>
1420                {
1421                    Some(Some(r))
1422                }
1423                Some(_) => None,
1424            }
1425        };
1426        if let Some(region) = fused_region {
1427            if matches!(src_fmt, Nv12 | Nv16 | Nv24) && matches!(dst_fmt, PlanarRgb | PlanarRgba) {
1428                #[cfg(test)]
1429                {
1430                    self.fused_hits += 1;
1431                }
1432                return self.convert_nv_to_planar_fused(
1433                    src,
1434                    dst,
1435                    src_fmt,
1436                    dst_fmt,
1437                    direct_params,
1438                    region,
1439                );
1440            }
1441        }
1442
1443        // check if a direct conversion can be done
1444        if !need_resize_flip_rotation && Self::support_conversion_pf(src_fmt, dst_fmt) {
1445            return Self::convert_format_pf(src, dst, src_fmt, dst_fmt, direct_params);
1446        }
1447
1448        // any extra checks
1449        if dst_fmt == Yuyv && !dst_w.is_multiple_of(2) {
1450            return Err(Error::NotSupported(format!(
1451                "{} destination must have width divisible by 2",
1452                dst_fmt,
1453            )));
1454        }
1455
1456        // Take the cached intermediates out of `self` so the resize step can
1457        // borrow `self` exclusively; they are restored before returning on the
1458        // success path. Reused buffers are not re-zeroed — every consumer below
1459        // fully overwrites the region it later reads (the pre-resize convert
1460        // writes all of `tmp`; the resize writes the scaled rect of `tmp2` and
1461        // its letterbox border is either pre-filled from `dst` or overwritten in
1462        // `dst` by the final `fill_image_outside_crop_u8`).
1463        let mut cached_tmp = self.convert_tmp.take();
1464        let mut cached_tmp2 = self.convert_tmp2.take();
1465
1466        // For a cropped convert, size the pre-resize intermediate to the crop
1467        // (grown by the resize filter's halo) instead of the whole frame — see
1468        // `pre_resize_region`. `None` keeps the previous full-frame behaviour,
1469        // which is also the uncropped hot path.
1470        let pre_region = if intermediate != src_fmt {
1471            self.pre_resize_region(src_fmt, (src_w, src_h), (dst_w, dst_h), rotation, crop)
1472        } else {
1473            None
1474        };
1475
1476        // create tmp buffer (reusing the cached one when its geometry matches)
1477        let tmp_holder: Option<Tensor<u8>> = if intermediate != src_fmt {
1478            let _s = tracing::trace_span!(
1479                "image.convert.cpu.format_convert",
1480                from = ?src_fmt,
1481                to = ?intermediate,
1482                pass = "pre_resize",
1483            )
1484            .entered();
1485            let (tmp_w, tmp_h) = pre_region.map_or((src_w, src_h), |g| (g.width, g.height));
1486            let mut t = Self::reuse_or_alloc_image(cached_tmp.take(), tmp_w, tmp_h, intermediate)?;
1487            #[cfg(test)]
1488            {
1489                self.last_tmp_dims = Some((tmp_w, tmp_h));
1490            }
1491            match pre_region {
1492                Some(g) => {
1493                    let mut sub = Self::reuse_or_alloc_image(
1494                        self.convert_src_sub.take(),
1495                        g.width,
1496                        g.height,
1497                        src_fmt,
1498                    )?;
1499                    {
1500                        let _s = tracing::trace_span!(
1501                            "image.convert.cpu.extract_region",
1502                            region_w = g.width,
1503                            region_h = g.height,
1504                        )
1505                        .entered();
1506                        Self::extract_nv_region(src, &mut sub, src_fmt, g)?;
1507                    }
1508                    Self::convert_format_pf(&sub, &mut t, src_fmt, intermediate, src_params)?;
1509                    self.convert_src_sub = Some(sub);
1510                }
1511                None => Self::convert_format_pf(src, &mut t, src_fmt, intermediate, src_params)?,
1512            }
1513            Some(t)
1514        } else {
1515            None
1516        };
1517
1518        // The intermediate now starts at `grown`'s origin rather than the
1519        // frame's, so rebase the source crop into its coordinates for the
1520        // resize step. The crop's size — and therefore the resize scale, the
1521        // filter coefficients, and every output pixel — is unchanged.
1522        let crop = match (pre_region, crop.src_rect) {
1523            (Some(g), Some(r)) => ResolvedCrop {
1524                src_rect: Some(Rect {
1525                    left: r.left - g.left,
1526                    top: r.top - g.top,
1527                    ..r
1528                }),
1529                ..crop
1530            },
1531            _ => crop,
1532        };
1533        let (tmp, tmp_fmt): (&Tensor<u8>, PixelFormat) = match &tmp_holder {
1534            Some(t) => (t, intermediate),
1535            None => (src, src_fmt),
1536        };
1537
1538        // format must be RGB/RGBA/GREY
1539        debug_assert!(matches!(tmp_fmt, Rgb | Rgba | Grey));
1540        if tmp_fmt == dst_fmt {
1541            let _s = tracing::trace_span!("image.convert.cpu.resize_flip_rotate").entered();
1542            self.resize_flip_rotate_pf(tmp, dst, dst_fmt, rotation, flip, crop)?;
1543        } else if !need_resize_flip_rotation {
1544            let _s = tracing::trace_span!(
1545                "image.convert.cpu.format_convert",
1546                from = ?tmp_fmt,
1547                to = ?dst_fmt,
1548                pass = "direct",
1549            )
1550            .entered();
1551            Self::convert_format_pf(tmp, dst, tmp_fmt, dst_fmt, dst_params)?;
1552        } else {
1553            let mut tmp2 = Self::reuse_or_alloc_image(cached_tmp2.take(), dst_w, dst_h, tmp_fmt)?;
1554            if crop.dst_rect.is_some_and(|c| {
1555                c != Rect {
1556                    left: 0,
1557                    top: 0,
1558                    width: dst_w,
1559                    height: dst_h,
1560                }
1561            }) && crop.dst_color.is_none()
1562            {
1563                Self::convert_format_pf(dst, &mut tmp2, dst_fmt, tmp_fmt, dst_params)?;
1564            }
1565            {
1566                let _s = tracing::trace_span!("image.convert.cpu.resize_flip_rotate").entered();
1567                self.resize_flip_rotate_pf(tmp, &mut tmp2, tmp_fmt, rotation, flip, crop)?;
1568            }
1569            {
1570                let _s = tracing::trace_span!(
1571                    "image.convert.cpu.format_convert",
1572                    from = ?tmp_fmt,
1573                    to = ?dst_fmt,
1574                    pass = "post_resize",
1575                )
1576                .entered();
1577                Self::convert_format_pf(&tmp2, dst, tmp_fmt, dst_fmt, dst_params)?;
1578            }
1579            cached_tmp2 = Some(tmp2);
1580        }
1581        // Restore the intermediates to the cache for the next call (`tmp` — a
1582        // borrow of `tmp_holder` — is no longer used past this point).
1583        if let Some(t) = tmp_holder {
1584            cached_tmp = Some(t);
1585        }
1586        self.convert_tmp = cached_tmp;
1587        self.convert_tmp2 = cached_tmp2;
1588
1589        if let (Some(dst_rect), Some(dst_color)) = (crop.dst_rect, crop.dst_color) {
1590            let full_rect = Rect {
1591                left: 0,
1592                top: 0,
1593                width: dst_w,
1594                height: dst_h,
1595            };
1596            if dst_rect != full_rect {
1597                Self::fill_image_outside_crop_u8(dst, dst_color, dst_rect, false)?;
1598            }
1599        }
1600
1601        Ok(())
1602    }
1603
1604    fn draw_decoded_masks_impl(
1605        &mut self,
1606        dst: &mut Tensor<u8>,
1607        detect: &[DetectBox],
1608        segmentation: &[Segmentation],
1609        opacity: f32,
1610        color_mode: crate::ColorMode,
1611    ) -> Result<()> {
1612        let dst_fmt = dst.format().ok_or(Error::NotAnImage)?;
1613        if !matches!(dst_fmt, PixelFormat::Rgba | PixelFormat::Rgb) {
1614            return Err(crate::Error::NotSupported(
1615                "CPU image rendering only supports RGBA or RGB images".to_string(),
1616            ));
1617        }
1618
1619        let _timer = FunctionTimer::new("CPUProcessor::draw_decoded_masks");
1620
1621        let dst_w = dst.width().unwrap();
1622        let dst_h = dst.height().unwrap();
1623        let dst_rs = tensor_row_stride(dst);
1624        let dst_c = dst_fmt.channels();
1625
1626        let mut map = dst.map_mut()?;
1627        let dst_slice = map.as_mut_slice();
1628
1629        self.render_box(dst_w, dst_h, dst_rs, dst_c, dst_slice, detect, color_mode)?;
1630
1631        if segmentation.is_empty() {
1632            return Ok(());
1633        }
1634
1635        // Rank guard BEFORE indexing shape()[2]. `Segmentation.segmentation`
1636        // is a `TensorDyn` with public fields, so a caller of the public
1637        // `draw_decoded_masks` can hand over a rank-2 mask; under the former
1638        // `Array3` that was structurally impossible. The guards inside the
1639        // render functions are unreachable for bad rank because this dispatch
1640        // indexes first.
1641        if let Some(bad) = segmentation
1642            .iter()
1643            .find(|s| s.segmentation.shape().len() != 3)
1644        {
1645            return Err(crate::Error::InvalidShape(format!(
1646                "segmentation must be [H, W, C], got {:?}",
1647                bad.segmentation.shape()
1648            )));
1649        }
1650
1651        // Semantic segmentation (e.g. ModelPack) has C > 1 (multi-class),
1652        // instance segmentation (e.g. YOLO) has C = 1 (binary per-instance).
1653        let is_semantic = segmentation[0].segmentation.shape()[2] > 1;
1654
1655        if is_semantic {
1656            self.render_modelpack_segmentation(
1657                dst_w,
1658                dst_h,
1659                dst_rs,
1660                dst_c,
1661                dst_slice,
1662                &segmentation[0],
1663                opacity,
1664            )?;
1665        } else {
1666            for (idx, (seg, det)) in segmentation.iter().zip(detect).enumerate() {
1667                let color_index = color_mode.index(idx, det.label);
1668                self.render_yolo_segmentation(
1669                    dst_w,
1670                    dst_h,
1671                    dst_rs,
1672                    dst_c,
1673                    dst_slice,
1674                    seg,
1675                    color_index,
1676                    opacity,
1677                )?;
1678            }
1679        }
1680
1681        Ok(())
1682    }
1683
1684    fn draw_proto_masks_impl(
1685        &mut self,
1686        dst: &mut Tensor<u8>,
1687        detect: &[DetectBox],
1688        proto_data: &ProtoData,
1689        opacity: f32,
1690        letterbox: Option<[f32; 4]>,
1691        color_mode: crate::ColorMode,
1692    ) -> Result<()> {
1693        let dst_fmt = dst.format().ok_or(Error::NotAnImage)?;
1694        if !matches!(dst_fmt, PixelFormat::Rgba | PixelFormat::Rgb) {
1695            return Err(crate::Error::NotSupported(
1696                "CPU image rendering only supports RGBA or RGB images".to_string(),
1697            ));
1698        }
1699
1700        let _timer = FunctionTimer::new("CPUProcessor::draw_proto_masks");
1701
1702        let dst_w = dst.width().unwrap();
1703        let dst_h = dst.height().unwrap();
1704        let dst_rs = tensor_row_stride(dst);
1705        let channels = dst_fmt.channels();
1706
1707        let mut map = dst.map_mut()?;
1708        let dst_slice = map.as_mut_slice();
1709
1710        self.render_box(
1711            dst_w, dst_h, dst_rs, channels, dst_slice, detect, color_mode,
1712        )?;
1713
1714        if detect.is_empty() {
1715            return Ok(());
1716        }
1717        let proto_shape = proto_data.protos.shape();
1718        if proto_shape.len() != 3 {
1719            return Err(Error::InvalidShape(format!(
1720                "protos tensor must be rank-3, got {proto_shape:?}"
1721            )));
1722        }
1723        let proto_h = proto_shape[0];
1724        let proto_w = proto_shape[1];
1725        let num_protos = proto_shape[2];
1726        let coeff_shape = proto_data.mask_coefficients.shape();
1727        if coeff_shape.len() != 2 {
1728            return Err(Error::InvalidShape(format!(
1729                "mask_coefficients tensor must be rank-2, got {coeff_shape:?}"
1730            )));
1731        }
1732        // Genuine "no detections this frame" → nothing to render.
1733        if coeff_shape[0] == 0 {
1734            return Ok(());
1735        }
1736        if coeff_shape[1] != num_protos {
1737            return Err(Error::InvalidShape(format!(
1738                "mask_coefficients second dimension must match num_protos \
1739                 ({num_protos}), got {coeff_shape:?}"
1740            )));
1741        }
1742
1743        // Widen coefficients to f32 once; shape [N, num_protos].
1744        let coeff_f32: Vec<f32> = match proto_data.mask_coefficients.dtype() {
1745            DType::F32 => {
1746                let t = proto_data.mask_coefficients.as_typed::<f32>().expect("F32");
1747                let m = t.map_read()?;
1748                m.as_slice().to_vec()
1749            }
1750            DType::F16 => {
1751                let t = proto_data
1752                    .mask_coefficients
1753                    .as_typed::<half::f16>()
1754                    .expect("F16");
1755                let m = t.map_read()?;
1756                m.as_slice().iter().map(|v| v.to_f32()).collect()
1757            }
1758            DType::I8 => {
1759                let t = proto_data.mask_coefficients.as_typed::<i8>().expect("I8");
1760                let m = t.map_read()?;
1761                if let Some(q) = t.quantization() {
1762                    use edgefirst_tensor::QuantMode;
1763                    let (scale, zp) = match q.mode() {
1764                        QuantMode::PerTensor { scale, zero_point } => (scale, zero_point as f32),
1765                        QuantMode::PerTensorSymmetric { scale } => (scale, 0.0),
1766                        other => {
1767                            return Err(Error::NotSupported(format!(
1768                                "I8 mask_coefficients quantization mode {other:?} not supported"
1769                            )));
1770                        }
1771                    };
1772                    m.as_slice()
1773                        .iter()
1774                        .map(|&v| (v as f32 - zp) * scale)
1775                        .collect()
1776                } else {
1777                    m.as_slice().iter().map(|&v| v as f32).collect()
1778                }
1779            }
1780            DType::I16 => {
1781                let t = proto_data.mask_coefficients.as_typed::<i16>().expect("I16");
1782                let m = t.map_read()?;
1783                if let Some(q) = t.quantization() {
1784                    use edgefirst_tensor::QuantMode;
1785                    let (scale, zp) = match q.mode() {
1786                        QuantMode::PerTensor { scale, zero_point } => (scale, zero_point as f32),
1787                        QuantMode::PerTensorSymmetric { scale } => (scale, 0.0),
1788                        other => {
1789                            return Err(Error::NotSupported(format!(
1790                                "I16 mask_coefficients quantization mode {other:?} not supported"
1791                            )));
1792                        }
1793                    };
1794                    m.as_slice()
1795                        .iter()
1796                        .map(|&v| (v as f32 - zp) * scale)
1797                        .collect()
1798                } else {
1799                    m.as_slice().iter().map(|&v| v as f32).collect()
1800                }
1801            }
1802            other => {
1803                return Err(Error::InvalidShape(format!(
1804                    "mask_coefficients dtype {other:?} not supported"
1805                )));
1806            }
1807        };
1808
1809        // Precompute letterbox scale/offset for output-pixel → proto-pixel mapping.
1810        let (lx0, lx_range, ly0, ly_range) = match letterbox {
1811            Some([lx0, ly0, lx1, ly1]) => (lx0, lx1 - lx0, ly0, ly1 - ly0),
1812            None => (0.0_f32, 1.0_f32, 0.0_f32, 1.0_f32),
1813        };
1814
1815        // Per-dtype dispatch. Map protos once, call the inner draw loop
1816        // with a dtype-specialized loader closure.
1817        match proto_data.protos.dtype() {
1818            DType::F32 => {
1819                let t = proto_data.protos.as_typed::<f32>().expect("F32");
1820                let m = t.map_read()?;
1821                self.draw_proto_masks_inner(
1822                    dst_slice,
1823                    dst_w,
1824                    dst_h,
1825                    dst_rs,
1826                    channels,
1827                    detect,
1828                    m.as_slice(),
1829                    &coeff_f32,
1830                    proto_h,
1831                    proto_w,
1832                    num_protos,
1833                    opacity,
1834                    (lx0, lx_range, ly0, ly_range),
1835                    color_mode,
1836                    0.0_f32,
1837                    |p: &f32, _| *p,
1838                );
1839            }
1840            DType::F16 => {
1841                let t = proto_data.protos.as_typed::<half::f16>().expect("F16");
1842                let m = t.map_read()?;
1843                self.draw_proto_masks_inner(
1844                    dst_slice,
1845                    dst_w,
1846                    dst_h,
1847                    dst_rs,
1848                    channels,
1849                    detect,
1850                    m.as_slice(),
1851                    &coeff_f32,
1852                    proto_h,
1853                    proto_w,
1854                    num_protos,
1855                    opacity,
1856                    (lx0, lx_range, ly0, ly_range),
1857                    color_mode,
1858                    0.0_f32,
1859                    |p: &half::f16, _| p.to_f32(),
1860                );
1861            }
1862            DType::I8 => {
1863                use edgefirst_tensor::QuantMode;
1864                let t = proto_data.protos.as_typed::<i8>().expect("I8");
1865                let m = t.map_read()?;
1866                let quant = t.quantization().ok_or_else(|| {
1867                    Error::InvalidShape("I8 protos require quantization metadata".into())
1868                })?;
1869                let (scale, zp) = match quant.mode() {
1870                    QuantMode::PerTensor { scale, zero_point } => (scale, zero_point as f32),
1871                    QuantMode::PerTensorSymmetric { scale } => (scale, 0.0),
1872                    QuantMode::PerChannel { axis, .. }
1873                    | QuantMode::PerChannelSymmetric { axis, .. } => {
1874                        return Err(Error::NotSupported(format!(
1875                            "per-channel quantization (axis={axis}) in draw_proto_masks \
1876                             CPU path not yet supported"
1877                        )));
1878                    }
1879                };
1880                self.draw_proto_masks_inner(
1881                    dst_slice,
1882                    dst_w,
1883                    dst_h,
1884                    dst_rs,
1885                    channels,
1886                    detect,
1887                    m.as_slice(),
1888                    &coeff_f32,
1889                    proto_h,
1890                    proto_w,
1891                    num_protos,
1892                    opacity,
1893                    (lx0, lx_range, ly0, ly_range),
1894                    color_mode,
1895                    scale,
1896                    move |p: &i8, _| (*p as f32) - zp,
1897                );
1898            }
1899            other => {
1900                return Err(Error::InvalidShape(format!(
1901                    "proto tensor dtype {other:?} not supported"
1902                )));
1903            }
1904        }
1905
1906        Ok(())
1907    }
1908
1909    #[allow(clippy::too_many_arguments)]
1910    fn draw_proto_masks_inner<P: Copy>(
1911        &self,
1912        dst_slice: &mut [u8],
1913        dst_w: usize,
1914        dst_h: usize,
1915        dst_rs: usize,
1916        channels: usize,
1917        detect: &[DetectBox],
1918        protos: &[P],
1919        coeff_all_f32: &[f32],
1920        proto_h: usize,
1921        proto_w: usize,
1922        num_protos: usize,
1923        opacity: f32,
1924        letterbox_xy: (f32, f32, f32, f32),
1925        color_mode: crate::ColorMode,
1926        acc_scale: f32,
1927        load_f32: impl Fn(&P, f32) -> f32 + Copy,
1928    ) {
1929        let (lx0, lx_range, ly0, ly_range) = letterbox_xy;
1930        let stride_y = proto_w * num_protos;
1931        for (idx, det) in detect.iter().enumerate() {
1932            let coeff = &coeff_all_f32[idx * num_protos..(idx + 1) * num_protos];
1933            let color_index = color_mode.index(idx, det.label);
1934            let color = self.colors[color_index % self.colors.len()];
1935            let alpha = if opacity == 1.0 {
1936                color[3] as u16
1937            } else {
1938                (color[3] as f32 * opacity).round() as u16
1939            };
1940
1941            let start_x = (dst_w as f32 * det.bbox.xmin).round() as usize;
1942            let start_y = (dst_h as f32 * det.bbox.ymin).round() as usize;
1943            let end_x = ((dst_w as f32 * det.bbox.xmax).round() as usize).min(dst_w);
1944            let end_y = ((dst_h as f32 * det.bbox.ymax).round() as usize).min(dst_h);
1945
1946            for y in start_y..end_y {
1947                for x in start_x..end_x {
1948                    let px = (lx0 + (x as f32 / dst_w as f32) * lx_range) * proto_w as f32 - 0.5;
1949                    let py = (ly0 + (y as f32 / dst_h as f32) * ly_range) * proto_h as f32 - 0.5;
1950
1951                    // Bilinear interpolation with per-load widening. Inline
1952                    // bilinear-sample since bilinear_dot_slice takes a
1953                    // different closure shape (no `zp` arg).
1954                    let x0 = (px.floor() as isize).clamp(0, proto_w as isize - 1) as usize;
1955                    let y0 = (py.floor() as isize).clamp(0, proto_h as isize - 1) as usize;
1956                    let x1 = (x0 + 1).min(proto_w - 1);
1957                    let y1 = (y0 + 1).min(proto_h - 1);
1958                    let fx = px - px.floor();
1959                    let fy = py - py.floor();
1960                    let w00 = (1.0 - fx) * (1.0 - fy);
1961                    let w10 = fx * (1.0 - fy);
1962                    let w01 = (1.0 - fx) * fy;
1963                    let w11 = fx * fy;
1964                    let b00 = y0 * stride_y + x0 * num_protos;
1965                    let b10 = y0 * stride_y + x1 * num_protos;
1966                    let b01 = y1 * stride_y + x0 * num_protos;
1967                    let b11 = y1 * stride_y + x1 * num_protos;
1968                    let mut acc = 0.0_f32;
1969                    for p in 0..num_protos {
1970                        let v00 = load_f32(&protos[b00 + p], 0.0);
1971                        let v10 = load_f32(&protos[b10 + p], 0.0);
1972                        let v01 = load_f32(&protos[b01 + p], 0.0);
1973                        let v11 = load_f32(&protos[b11 + p], 0.0);
1974                        let val = w00 * v00 + w10 * v10 + w01 * v01 + w11 * v11;
1975                        acc += coeff[p] * val;
1976                    }
1977                    let final_acc = if acc_scale == 0.0 {
1978                        acc
1979                    } else {
1980                        acc_scale * acc
1981                    };
1982                    // Pass-through: acc_scale=0.0 means "no scaling" (f32/f16
1983                    // native); non-zero means "apply scale once" (i8 with
1984                    // per-tensor quant).
1985                    let mask = 1.0 / (1.0 + (-final_acc).exp());
1986                    if mask < 0.5 {
1987                        continue;
1988                    }
1989                    let dst_index = y * dst_rs + x * channels;
1990                    for c in 0..3 {
1991                        dst_slice[dst_index + c] = ((color[c] as u16 * alpha
1992                            + dst_slice[dst_index + c] as u16 * (255 - alpha))
1993                            / 255) as u8;
1994                    }
1995                }
1996            }
1997        }
1998    }
1999}