Skip to main content

zenpixels_convert/orient/
mod.rs

1//! Physical EXIF orientation baking — rotate / flip any pixel view or buffer.
2//!
3//! Supports all 8 dihedral orientations (`Identity`, `FlipH`, `FlipV`, `Rotate180`,
4//! `Transpose`, `Rotate90`, `Rotate270`, `Transverse`) across all pixel widths
5//! (`1, 2, 3, 4, 6, 8, 12, 16+` B/px) with SIMD register transposes (`pxn_x86`,
6//! `rgb3_x86`, `pxn_neon`, and WASM SIMD128 4×4) under `#![forbid(unsafe_code)]`.
7
8use core::cmp::min;
9use how_far::Pulse;
10use whereat::At;
11use zenpixels::{
12    BandSizing, BandedBuf, Orientation, PixelBuf, PixelRect, PixelSink, PixelView, PixelViewMut,
13};
14
15use crate::error::{ConvertError, err_at};
16use crate::pulse::{check_pulse, live_pulse, step_pulse};
17
18#[cfg(feature = "fast-transpose")]
19use archmage::prelude::*;
20
21// Private aliases so our preserved SIMD kernel files (`pxn_x86`, `rgb3_x86`, `pxn_neon`)
22// operate directly on 0.5 `PixelView` / `PixelViewMut` with zero changes.
23#[allow(dead_code)]
24type PixelSlice<'a> = PixelView<'a>;
25#[allow(dead_code)]
26type PixelSliceMut<'a> = PixelViewMut<'a>;
27
28const TILE: u32 = 32;
29const PULSE_STRIP_ROWS: u32 = 64;
30
31/// Apply `orientation` to `src`, returning a freshly allocated tightly packed [`PixelBuf`].
32///
33/// Preserves `src.hdr()`, `src.attached_claims()`, and `src.origin()`. The returned buffer has
34/// [`Orientation::Identity`] because `orientation` has been physically applied to the pixels.
35#[doc(alias = "rotate")]
36#[doc(alias = "transpose")]
37#[doc(alias = "exif")]
38pub fn apply_orientation(
39    src: &PixelView<'_>,
40    orientation: Orientation,
41) -> Result<PixelBuf, At<ConvertError>> {
42    apply_orientation_with_pulse(src, orientation, None)
43}
44
45/// Apply `orientation` to `src`, returning a freshly allocated tightly packed [`PixelBuf`],
46/// with optional cooperative cancellation and row progress via `pulse` (pass `None` when not
47/// needed).
48pub fn apply_orientation_with_pulse(
49    src: &PixelView<'_>,
50    orientation: Orientation,
51    pulse: Option<&dyn Pulse>,
52) -> Result<PixelBuf, At<ConvertError>> {
53    let pulse = live_pulse(pulse);
54    check_pulse(pulse)?;
55    let (ow, oh) = orientation.output_dimensions(src.width(), src.height());
56    let mut out = PixelBuf::new(ow, oh, src.format().clone())
57        .map_err(|e| err_at((*e.error()).into()))?
58        .with_hdr(src.hdr());
59    if let Some(origin) = src.origin() {
60        out = out.with_origin(origin.clone());
61    }
62    let facts = src.attached_claims();
63    apply_orientation_into_with_pulse(src, orientation, &mut out.as_view_mut(), pulse)?;
64    out.assume_claims(facts);
65    Ok(out)
66}
67
68/// Apply explicit `orientation` to an owned [`PixelBuf`], returning `buf` **zero-copy** on
69/// [`Orientation::Identity`] and always emitting [`Orientation::Identity`] metadata on the result
70/// (matching [`apply_orientation`]).
71///
72/// Pending input `buf.orientation()` is not implicitly composed; use [`bake_orientation_owned`]
73/// to apply and clear pending orientation.
74pub fn apply_orientation_owned(
75    buf: PixelBuf,
76    orientation: Orientation,
77) -> Result<PixelBuf, At<ConvertError>> {
78    apply_orientation_owned_with_pulse(buf, orientation, None)
79}
80
81/// Apply explicit `orientation` to an owned [`PixelBuf`] with optional cooperative cancellation
82/// and row progress via `pulse` (pass `None` when not needed).
83pub fn apply_orientation_owned_with_pulse(
84    mut buf: PixelBuf,
85    orientation: Orientation,
86    pulse: Option<&dyn Pulse>,
87) -> Result<PixelBuf, At<ConvertError>> {
88    let pulse = live_pulse(pulse);
89    check_pulse(pulse)?;
90    if orientation == Orientation::Identity {
91        buf.set_orientation(Orientation::Identity);
92        return Ok(buf);
93    }
94    apply_orientation_with_pulse(&buf.as_view(), orientation, pulse)
95}
96
97/// Physically bake `src.orientation()` into pixels, returning a tightly packed [`PixelBuf`]
98/// with [`Orientation::Identity`].
99#[doc(alias = "rotate")]
100#[doc(alias = "exif")]
101pub fn bake_orientation(src: &PixelView<'_>) -> Result<PixelBuf, At<ConvertError>> {
102    apply_orientation(src, src.orientation())
103}
104
105/// Physically bake `buf.orientation()` into pixels, returning `buf` **zero-copy** when
106/// `buf.orientation() == Orientation::Identity` and clearing the resulting orientation to
107/// [`Orientation::Identity`].
108pub fn bake_orientation_owned(buf: PixelBuf) -> Result<PixelBuf, At<ConvertError>> {
109    let orient = buf.orientation();
110    if orient == Orientation::Identity {
111        return Ok(buf);
112    }
113    apply_orientation(&buf.as_view(), orient)
114}
115
116/// Physically bake `src.orientation()` into a [`BandedBuf`] partitioned according to `sizing`
117/// ([`BandSizing::MaxBandBytes`] or [`BandSizing::RowsPerBand`]) with [`Orientation::Identity`]
118/// on the result.
119pub fn bake_orientation_banded(
120    src: &BandedBuf,
121    sizing: BandSizing,
122) -> Result<BandedBuf, At<ConvertError>> {
123    apply_orientation_banded(src, src.orientation(), sizing)
124}
125
126/// Apply explicit `orientation` to a [`BandedBuf`], returning a freshly allocated [`BandedBuf`]
127/// partitioned according to `sizing` with [`Orientation::Identity`] metadata and
128/// **zero full-frame contiguous allocation**.
129///
130/// Preserves `src.hdr()`, `src.attached_claims()`, and `src.origin()`.
131pub fn apply_orientation_banded(
132    src: &BandedBuf,
133    orientation: Orientation,
134    sizing: BandSizing,
135) -> Result<BandedBuf, At<ConvertError>> {
136    apply_orientation_banded_with_pulse(src, orientation, sizing, None)
137}
138
139/// Apply explicit `orientation` to a [`BandedBuf`] with optional cooperative cancellation and
140/// progress via `pulse` (pass `None` when not needed).
141pub fn apply_orientation_banded_with_pulse(
142    src: &BandedBuf,
143    orientation: Orientation,
144    sizing: BandSizing,
145    pulse: Option<&dyn Pulse>,
146) -> Result<BandedBuf, At<ConvertError>> {
147    let pulse = live_pulse(pulse);
148    check_pulse(pulse)?;
149    let (ow, oh) = orientation.output_dimensions(src.width(), src.height());
150    let mut out = BandedBuf::new(ow, oh, src.format().clone(), sizing)
151        .map_err(|e| err_at((*e.error()).into()))?
152        .with_origin(src.origin().clone());
153    apply_orientation_banded_into_with_pulse(src, orientation, &mut out, pulse)?;
154    out.sink_finish(src.attached_claims(), src.hdr());
155    Ok(out)
156}
157
158/// Apply `orientation` from `src` into pre-allocated `dst` [`BandedBuf`] with
159/// **zero heap allocation** and full SIMD tile transposes across every `(src_band, dst_band)`
160/// intersection.
161///
162/// Works for arbitrary independent source and destination band heights and all 8 orientations.
163pub fn apply_orientation_banded_into(
164    src: &BandedBuf,
165    orientation: Orientation,
166    dst: &mut BandedBuf,
167) -> Result<(), At<ConvertError>> {
168    apply_orientation_banded_into_with_pulse(src, orientation, dst, None)
169}
170
171/// Apply `orientation` from `src` into pre-allocated `dst` [`BandedBuf`] with optional
172/// cooperative cancellation and progress via `pulse` (pass `None` when not needed).
173pub fn apply_orientation_banded_into_with_pulse(
174    src: &BandedBuf,
175    orientation: Orientation,
176    dst: &mut BandedBuf,
177    pulse: Option<&dyn Pulse>,
178) -> Result<(), At<ConvertError>> {
179    let pulse = live_pulse(pulse);
180    check_pulse(pulse)?;
181    let w = src.width();
182    let h = src.height();
183    let (ow, oh) = orientation.output_dimensions(w, h);
184    if dst.width() != ow || dst.height() != oh || dst.format().layout() != src.format().layout() {
185        return Err(err_at(ConvertError::DimensionMismatch));
186    }
187    if dst.format().color() != src.format().color() {
188        return Err(err_at(ConvertError::UnsupportedRoute));
189    }
190    if w == 0 || h == 0 || src.format().layout().bytes_per_pixel() == 0 {
191        return Ok(());
192    }
193
194    let src_band_rows = src.rows_per_band();
195    let dst_band_rows = dst.rows_per_band();
196    let src_band_count = src.band_count();
197    let dst_band_count = dst.band_count();
198
199    if !orientation.swaps_axes() {
200        let flips_v = matches!(orientation, Orientation::FlipV | Orientation::Rotate180);
201        for sb_idx in 0..src_band_count {
202            let sy0 = (sb_idx as u32) * src_band_rows;
203            let src_band = src.band_view(sb_idx).expect("valid src band");
204            let sh = src_band.height();
205            let sy1 = sy0 + sh;
206            let (m_dy0, m_dy1) = if flips_v {
207                (h - sy1, h - sy0)
208            } else {
209                (sy0, sy1)
210            };
211            let first_db = (m_dy0 / dst_band_rows) as usize;
212            let last_db = ((m_dy1 - 1) / dst_band_rows) as usize;
213            for db_idx in first_db..=last_db {
214                let dy0 = (db_idx as u32) * dst_band_rows;
215                let mut dst_band = dst
216                    .try_cow_band_view_mut(db_idx)
217                    .map_err(|e| err_at((*e.error()).into()))?;
218                let dy1 = dy0 + dst_band.height();
219                let iy0 = dy0.max(m_dy0);
220                let iy1 = dy1.min(m_dy1);
221                if iy0 >= iy1 {
222                    continue;
223                }
224                let ih = iy1 - iy0;
225                let is_y0 = if flips_v { h - iy1 } else { iy0 };
226                let src_sub = src_band
227                    .sub_rows(is_y0 - sy0, ih)
228                    .map_err(|e| err_at((*e.error()).into()))?;
229                let mut dst_sub = dst_band
230                    .sub_rows_mut(iy0 - dy0, ih)
231                    .map_err(|e| err_at((*e.error()).into()))?;
232                apply_orientation_into_with_pulse(&src_sub, orientation, &mut dst_sub, pulse)?;
233            }
234        }
235    } else {
236        let rev_sy_to_dx = matches!(orientation, Orientation::Rotate90 | Orientation::Transverse);
237        let rev_sx_to_dy = matches!(
238            orientation,
239            Orientation::Rotate270 | Orientation::Transverse
240        );
241        for sb_idx in 0..src_band_count {
242            let sy0 = (sb_idx as u32) * src_band_rows;
243            let src_band = src.band_view(sb_idx).expect("valid src band");
244            let sh = src_band.height();
245            let sy1 = sy0 + sh;
246            let dx0 = if rev_sy_to_dx { h - sy1 } else { sy0 };
247            for db_idx in 0..dst_band_count {
248                check_pulse(pulse)?;
249                let dy0 = (db_idx as u32) * dst_band_rows;
250                let mut dst_band = dst
251                    .try_cow_band_view_mut(db_idx)
252                    .map_err(|e| err_at((*e.error()).into()))?;
253                let dh = dst_band.height();
254                let dy1 = dy0 + dh;
255                let sx0 = if rev_sx_to_dy { w - dy1 } else { dy0 };
256                let src_tile = src_band
257                    .crop(PixelRect::new(sx0, 0, dh, sh))
258                    .map_err(|e| err_at((*e.error()).into()))?;
259                let mut dst_tile = dst_band
260                    .crop_mut(PixelRect::new(dx0, 0, sh, dh))
261                    .map_err(|e| err_at((*e.error()).into()))?;
262                apply_orientation_into_with_pulse(&src_tile, orientation, &mut dst_tile, None)?;
263            }
264            step_pulse(pulse, u64::from(sh))?;
265        }
266    }
267    Ok(())
268}
269
270/// Apply `orientation` to `src`, writing into caller-provided `dst` with **zero heap allocation**.
271pub fn apply_orientation_into(
272    src: &PixelView<'_>,
273    orientation: Orientation,
274    dst: &mut PixelViewMut<'_>,
275) -> Result<(), At<ConvertError>> {
276    apply_orientation_into_with_pulse(src, orientation, dst, None)
277}
278
279/// Apply `orientation` to `src`, writing into caller-provided `dst` with **zero heap allocation**
280/// and optional cooperative cancellation/progress via `pulse` (pass `None` when not needed).
281pub fn apply_orientation_into_with_pulse(
282    src: &PixelView<'_>,
283    orientation: Orientation,
284    dst: &mut PixelViewMut<'_>,
285    pulse: Option<&dyn Pulse>,
286) -> Result<(), At<ConvertError>> {
287    let pulse = live_pulse(pulse);
288    check_pulse(pulse)?;
289    let w = src.width();
290    let h = src.height();
291    let bpp = src.format().layout().bytes_per_pixel();
292    let (ow, oh) = orientation.output_dimensions(w, h);
293
294    if dst.width() != ow
295        || dst.height() != oh
296        || dst.format().layout().bytes_per_pixel() != bpp
297        || dst.format().layout() != src.format().layout()
298    {
299        return Err(err_at(ConvertError::DimensionMismatch));
300    }
301    if dst.format().color() != src.format().color() {
302        return Err(err_at(ConvertError::UnsupportedRoute));
303    }
304    if w == 0 || h == 0 || bpp == 0 {
305        return Ok(());
306    }
307
308    match orientation {
309        Orientation::Identity => {
310            for y in 0..h {
311                dst.row_mut(y).copy_from_slice(src.row(y));
312                step_pulse(pulse, 1)?;
313            }
314        }
315        Orientation::FlipV => {
316            for y in 0..h {
317                dst.row_mut(y).copy_from_slice(src.row(h - 1 - y));
318                step_pulse(pulse, 1)?;
319            }
320        }
321        Orientation::FlipH => {
322            for y in 0..h {
323                reverse_row(src.row(y), dst.row_mut(y), w as usize, bpp);
324                step_pulse(pulse, 1)?;
325            }
326        }
327        Orientation::Rotate180 => {
328            for y in 0..h {
329                reverse_row(src.row(h - 1 - y), dst.row_mut(y), w as usize, bpp);
330                step_pulse(pulse, 1)?;
331            }
332        }
333        Orientation::Transpose
334        | Orientation::Rotate90
335        | Orientation::Rotate270
336        | Orientation::Transverse
337        | _ => {
338            if pulse.is_none() || h <= PULSE_STRIP_ROWS {
339                do_transpose(src, dst, orientation, w, h, bpp);
340                step_pulse(pulse, u64::from(h))?;
341            } else {
342                let rev_sy_to_dx =
343                    matches!(orientation, Orientation::Rotate90 | Orientation::Transverse);
344                let mut sy0 = 0u32;
345                while sy0 < h {
346                    let sh = min(PULSE_STRIP_ROWS, h - sy0);
347                    let sy1 = sy0 + sh;
348                    let dx0 = if rev_sy_to_dx { h - sy1 } else { sy0 };
349                    let src_strip = src
350                        .sub_rows(sy0, sh)
351                        .map_err(|e| err_at((*e.error()).into()))?;
352                    let mut dst_strip = dst
353                        .crop_mut(PixelRect::new(dx0, 0, sh, w))
354                        .map_err(|e| err_at((*e.error()).into()))?;
355                    do_transpose(&src_strip, &mut dst_strip, orientation, w, sh, bpp);
356                    step_pulse(pulse, u64::from(sh))?;
357                    sy0 = sy1;
358                }
359            }
360        }
361    }
362    Ok(())
363}
364
365#[inline]
366fn reverse_row(src: &[u8], dst: &mut [u8], width: usize, bpp: usize) {
367    match bpp {
368        1 => {
369            for x in 0..width {
370                dst[x] = src[width - 1 - x];
371            }
372        }
373        2 => {
374            for x in 0..width {
375                let si = (width - 1 - x) * 2;
376                let di = x * 2;
377                dst[di..di + 2].copy_from_slice(&src[si..si + 2]);
378            }
379        }
380        3 => {
381            for x in 0..width {
382                let si = (width - 1 - x) * 3;
383                let di = x * 3;
384                dst[di..di + 3].copy_from_slice(&src[si..si + 3]);
385            }
386        }
387        4 => {
388            for x in 0..width {
389                let si = (width - 1 - x) * 4;
390                let di = x * 4;
391                dst[di..di + 4].copy_from_slice(&src[si..si + 4]);
392            }
393        }
394        _ => {
395            for x in 0..width {
396                let si = (width - 1 - x) * bpp;
397                let di = x * bpp;
398                dst[di..di + bpp].copy_from_slice(&src[si..si + bpp]);
399            }
400        }
401    }
402}
403
404#[allow(clippy::too_many_arguments)]
405#[inline]
406fn scatter_pixel(
407    s: &[u8],
408    dst: &mut PixelViewMut<'_>,
409    orientation: Orientation,
410    sx: u32,
411    sy: u32,
412    w: u32,
413    h: u32,
414    bpp: usize,
415) {
416    let (dx, dy) = orientation.map_pixel_coordinates((sx, sy), (w, h));
417    let si = sx as usize * bpp;
418    let di = dx as usize * bpp;
419    dst.row_mut(dy)[di..di + bpp].copy_from_slice(&s[si..si + bpp]);
420}
421
422fn do_transpose(
423    src: &PixelView<'_>,
424    dst: &mut PixelViewMut<'_>,
425    orientation: Orientation,
426    w: u32,
427    h: u32,
428    bpp: usize,
429) {
430    if let Some(flips) = inverse_flips(orientation) {
431        #[cfg(all(feature = "fast-transpose", target_arch = "x86_64"))]
432        {
433            macro_rules! v3_kernel {
434                ($kernel:path) => {
435                    if let Some(token) = X64V3Token::summon() {
436                        $kernel(token, src, dst, orientation, w, h);
437                        return;
438                    }
439                };
440            }
441            match bpp {
442                1 => v3_kernel!(pxn_x86::transpose1_v3),
443                2 => v3_kernel!(pxn_x86::transpose2_v3),
444                3 => v3_kernel!(rgb3_x86::transpose3_v3),
445                4 => v3_kernel!(pxn_x86::transpose4_v3),
446                6 => v3_kernel!(pxn_x86::transpose6_v3),
447                8 => v3_kernel!(pxn_x86::transpose8_v3),
448                12 => v3_kernel!(pxn_x86::transpose12_v3),
449                16 => v3_kernel!(pxn_x86::transpose16_v3),
450                _ => {}
451            }
452        }
453        #[cfg(all(feature = "fast-transpose", target_arch = "aarch64"))]
454        {
455            macro_rules! neon_kernel {
456                ($kernel:path) => {
457                    if let Some(token) = NeonToken::summon() {
458                        $kernel(token, src, dst, orientation, w, h);
459                        return;
460                    }
461                };
462            }
463            match bpp {
464                1 => neon_kernel!(pxn_neon::transpose1_neon),
465                2 => neon_kernel!(pxn_neon::transpose2_neon),
466                3 => neon_kernel!(pxn_neon::transpose3_neon),
467                4 => neon_kernel!(pxn_neon::transpose4_neon),
468                6 => neon_kernel!(pxn_neon::transpose6_neon),
469                8 => neon_kernel!(pxn_neon::transpose8_neon),
470                12 => neon_kernel!(pxn_neon::transpose12_neon),
471                16 => {
472                    transpose16_deep(src, dst, orientation, w, h);
473                    return;
474                }
475                _ => {}
476            }
477        }
478        #[cfg(feature = "fast-transpose")]
479        if bpp == 4 {
480            transpose4_simd(src, dst, orientation, w, h);
481            return;
482        }
483        match bpp {
484            1 => return transpose_tiled::<1>(src, dst, flips, w, h),
485            2 => return transpose_tiled::<2>(src, dst, flips, w, h),
486            3 => return transpose_tiled::<3>(src, dst, flips, w, h),
487            4 => return transpose_tiled::<4>(src, dst, flips, w, h),
488            6 => return transpose_tiled::<6>(src, dst, flips, w, h),
489            8 => return transpose_tiled::<8>(src, dst, flips, w, h),
490            12 => return transpose_tiled::<12>(src, dst, flips, w, h),
491            16 => return transpose16_deep(src, dst, orientation, w, h),
492            _ => {}
493        }
494    }
495    transpose_blocked(src, dst, orientation, w, h, bpp);
496}
497
498#[inline]
499fn inverse_flips(orientation: Orientation) -> Option<(bool, bool)> {
500    match orientation {
501        Orientation::Transpose => Some((false, false)),
502        Orientation::Rotate90 => Some((false, true)),
503        Orientation::Rotate270 => Some((true, false)),
504        Orientation::Transverse => Some((true, true)),
505        _ => None,
506    }
507}
508
509#[cfg_attr(
510    all(
511        feature = "fast-transpose",
512        any(target_arch = "x86_64", target_arch = "aarch64")
513    ),
514    cold
515)]
516#[inline(never)]
517fn transpose_tiled<const BPP: usize>(
518    src: &PixelView<'_>,
519    dst: &mut PixelViewMut<'_>,
520    (flip_sx, flip_sy): (bool, bool),
521    w: u32,
522    h: u32,
523) {
524    let sbytes = src.as_strided_bytes();
525    // For a 1-row image, `stride` is unused (and may even exceed `isize::MAX`); normalize to 0.
526    let sstride = if h <= 1 { 0 } else { src.stride_bytes() };
527    let (ow, oh) = (h, w);
528
529    let mut ty = 0u32;
530    while ty < oh {
531        let ty_end = min(ty.saturating_add(TILE), oh);
532        let mut tx = 0u32;
533        while tx < ow {
534            let tx_end = min(tx.saturating_add(TILE), ow);
535            let sy0 = (if flip_sy { h - 1 - tx } else { tx }) as usize;
536            for dy in ty..ty_end {
537                let sx = (if flip_sx { w - 1 - dy } else { dy }) as usize;
538                let mut soff = sy0 * sstride + sx * BPP;
539                let drow = &mut dst.row_mut(dy)[tx as usize * BPP..tx_end as usize * BPP];
540                let chunks = drow.as_chunks_mut::<BPP>().0;
541                let n = chunks.len();
542                for (i, dpx) in chunks.iter_mut().enumerate() {
543                    *dpx = sbytes[soff..soff + BPP].try_into().unwrap();
544                    if i + 1 < n {
545                        soff = if flip_sy {
546                            soff - sstride
547                        } else {
548                            soff + sstride
549                        };
550                    }
551                }
552            }
553            tx = tx_end;
554        }
555        ty = ty_end;
556    }
557}
558
559#[cfg_attr(
560    all(
561        feature = "fast-transpose",
562        any(target_arch = "x86_64", target_arch = "aarch64")
563    ),
564    cold
565)]
566#[inline(never)]
567fn transpose_blocked(
568    src: &PixelView<'_>,
569    dst: &mut PixelViewMut<'_>,
570    orientation: Orientation,
571    w: u32,
572    h: u32,
573    bpp: usize,
574) {
575    let mut tile_y = 0u32;
576    while tile_y < h {
577        let y_end = min(tile_y.saturating_add(TILE), h);
578        let mut tile_x = 0u32;
579        while tile_x < w {
580            let x_end = min(tile_x.saturating_add(TILE), w);
581            for sy in tile_y..y_end {
582                let s = src.row(sy);
583                for sx in tile_x..x_end {
584                    scatter_pixel(s, dst, orientation, sx, sy, w, h, bpp);
585                }
586            }
587            tile_x = x_end;
588        }
589        tile_y = y_end;
590    }
591}
592
593#[allow(clippy::too_many_arguments)]
594#[cfg(feature = "fast-transpose")]
595fn transpose_edges(
596    src: &PixelView<'_>,
597    dst: &mut PixelViewMut<'_>,
598    orientation: Orientation,
599    w: u32,
600    h: u32,
601    bpp: usize,
602    full_w: u32,
603    full_h: u32,
604) {
605    for sy in 0..full_h {
606        let s = src.row(sy);
607        for sx in full_w..w {
608            scatter_pixel(s, dst, orientation, sx, sy, w, h, bpp);
609        }
610    }
611    for sy in full_h..h {
612        let s = src.row(sy);
613        for sx in 0..w {
614            scatter_pixel(s, dst, orientation, sx, sy, w, h, bpp);
615        }
616    }
617}
618
619#[cfg(feature = "fast-transpose")]
620#[inline]
621fn tile_dest(
622    orientation: Orientation,
623    bx: u32,
624    by: u32,
625    r: u32,
626    w: u32,
627    h: u32,
628) -> (u32, u32, bool) {
629    match orientation {
630        Orientation::Transpose => (bx + r, by, false),
631        Orientation::Rotate90 => (bx + r, h - 4 - by, true),
632        Orientation::Rotate270 => (w - 1 - bx - r, by, false),
633        Orientation::Transverse => (w - 1 - bx - r, h - 4 - by, true),
634        _ => unreachable!("tile_dest only handles the four transposing orientations"),
635    }
636}
637
638#[cfg(feature = "fast-transpose")]
639#[attune(dispatch, -_v3, -_neon, define(f32x4))]
640fn transpose4_simd(
641    src: &PixelView<'_>,
642    dst: &mut PixelViewMut<'_>,
643    orientation: Orientation,
644    w: u32,
645    h: u32,
646) {
647    let token = Token::from_context();
648    let full_w = w & !3;
649    let full_h = h & !3;
650
651    let mut by = 0;
652    while by < full_h {
653        let mut bx = 0;
654        while bx < full_w {
655            let xb = bx as usize * 4;
656            let f0: [f32; 4] =
657                bytemuck::cast::<[u8; 16], _>(src.row(by)[xb..xb + 16].try_into().unwrap());
658            let f1: [f32; 4] =
659                bytemuck::cast::<[u8; 16], _>(src.row(by + 1)[xb..xb + 16].try_into().unwrap());
660            let f2: [f32; 4] =
661                bytemuck::cast::<[u8; 16], _>(src.row(by + 2)[xb..xb + 16].try_into().unwrap());
662            let f3: [f32; 4] =
663                bytemuck::cast::<[u8; 16], _>(src.row(by + 3)[xb..xb + 16].try_into().unwrap());
664            let mut rows = [
665                f32x4::load_t(token, &f0),
666                f32x4::load_t(token, &f1),
667                f32x4::load_t(token, &f2),
668                f32x4::load_t(token, &f3),
669            ];
670            f32x4::transpose_4x4(&mut rows);
671
672            for r in 0..4u32 {
673                let mut lanes = [0f32; 4];
674                rows[r as usize].store(&mut lanes);
675                let (drow, dcol, rev) = tile_dest(orientation, bx, by, r, w, h);
676                if rev {
677                    lanes.reverse();
678                }
679                let bytes: [u8; 16] = bytemuck::cast(lanes);
680                let db = dcol as usize * 4;
681                dst.row_mut(drow)[db..db + 16].copy_from_slice(&bytes);
682            }
683            bx += 4;
684        }
685        by += 4;
686    }
687
688    transpose_edges(src, dst, orientation, w, h, 4, full_w, full_h);
689}
690
691fn transpose16_deep(
692    src: &PixelView<'_>,
693    dst: &mut PixelViewMut<'_>,
694    orientation: Orientation,
695    w: u32,
696    h: u32,
697) {
698    let Some((flip_sx, flip_sy)) = inverse_flips(orientation) else {
699        return transpose_blocked(src, dst, orientation, w, h, 16);
700    };
701    let sbytes = src.as_strided_bytes();
702    let sstride = src.stride_bytes();
703    let dstride = dst.stride_bytes();
704    let dbytes = dst.as_strided_bytes_mut();
705
706    const T: usize = 16;
707    let full_w = w & !15;
708    let full_h = h & !15;
709    let ntx = (full_w / 16) as usize;
710    let nty = (full_h / 16) as usize;
711    for tyi in 0..nty {
712        let ty = if flip_sy { nty - 1 - tyi } else { tyi } * T;
713        let dx = if flip_sy { h as usize - T - ty } else { ty };
714        for txi in 0..ntx {
715            let tx = (if flip_sx { ntx - 1 - txi } else { txi }) * T;
716            let mut srows: [&[u8]; T] = [&[]; T];
717            for (r, sr) in srows.iter_mut().enumerate() {
718                let off = (ty + r) * sstride + tx * 16;
719                *sr = &sbytes[off..off + T * 16];
720            }
721            for c in 0..T {
722                let dy = if flip_sx {
723                    w as usize - 1 - (tx + c)
724                } else {
725                    tx + c
726                };
727                let drow = &mut dbytes[dy * dstride + dx * 16..dy * dstride + (dx + T) * 16];
728                for (k, chunk) in drow.as_chunks_mut::<16>().0.iter_mut().enumerate() {
729                    let r = if flip_sy { T - 1 - k } else { k };
730                    chunk.copy_from_slice(&srows[r][c * 16..c * 16 + 16]);
731                }
732            }
733        }
734    }
735    let (sb, db) = (sbytes, dbytes);
736    for y in 0..full_h {
737        for x in full_w..w {
738            let (dxx, dyy) = orientation.map_pixel_coordinates((x, y), (w, h));
739            let so = y as usize * sstride + x as usize * 16;
740            let dofs = dyy as usize * dstride + dxx as usize * 16;
741            db[dofs..dofs + 16].copy_from_slice(&sb[so..so + 16]);
742        }
743    }
744    for y in full_h..h {
745        for x in 0..w {
746            let (dxx, dyy) = orientation.map_pixel_coordinates((x, y), (w, h));
747            let so = y as usize * sstride + x as usize * 16;
748            let dofs = dyy as usize * dstride + dxx as usize * 16;
749            db[dofs..dofs + 16].copy_from_slice(&sb[so..so + 16]);
750        }
751    }
752}
753
754#[cfg(all(feature = "fast-transpose", target_arch = "x86_64"))]
755mod rgb3_x86;
756
757#[cfg(all(feature = "fast-transpose", target_arch = "x86_64"))]
758mod pxn_x86;
759
760#[cfg(all(feature = "fast-transpose", target_arch = "aarch64"))]
761mod pxn_neon;