edgefirst-image 0.34.1

High-performance image processing with hardware acceleration for edge AI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

//! Portable GL render lowering — the single home for the pure geometry math the
//! converged tile/batch renderer relies on. **No platform types** (no gbm,
//! IOSurface, EGL, or `edgefirst_gl` symbols) appear here so the same lowering serves the
//! Linux DMA-BUF and macOS IOSurface backends behind one seam.
//!
//! Three responsibilities live here, each previously open-coded at several call
//! sites in `processor/mod.rs`:
//!
//! 1. **`region_to_viewport`** — the bottom-left y-origin flip for a *bottom-up*
//!    render target. GL's window origin is bottom-left; HAL regions are
//!    top-left. A tile at pixel `(x, y)` of size `(w, h)` in a `parent_h`-row
//!    target maps to viewport `y' = parent_h − (y + h)`. NOTE: the live Linux
//!    DMA-BUF destination batch path is **top-down** (GL row 0 == memory row 0,
//!    verified on-target — the renderer's texcoords already flip the image
//!    upright), so it uses `region.y` directly and does NOT call this. Kept for a
//!    future bottom-up surface (e.g. the macOS pbuffer batch path).
//!
//! 2. **`source_uv`** — the source sampling rectangle in normalised `[0,1]` UV,
//!    derived from a `Region`. Mirrors the `src_rect_uv` half of
//!    [`crate::gl::core::float_crop_uniforms`].
//!
//! 3. **`plan_batch`** — the chunk planner. A batch of `n` destination tiles
//!    renders into one reused import when every tile fits the GPU's
//!    `GL_MAX_*` limits; otherwise it splits into chunks (one import per chunk)
//!    or, degenerately, one import per tile. The tile region is *render state*
//!    (`glViewport`), never part of the EGL cache key — that is what makes
//!    "N tiles → 1 import" hold.

use crate::Region;
use edgefirst_tensor::{PixelFormat, PixelLayout, TensorMemory};

/// How a convert's destination is realized on the GPU — the pure half of the
/// destination lowering (`bind_dst` in `processor/mod.rs` performs the GL
/// work). One lowering per *destination memory class*, never per platform:
/// platform differences surface as the `zero_copy_import` capability bit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum DstLowering {
    /// The destination buffer itself becomes the FBO colour attachment
    /// (EGLImage renderbuffer/texture today, IOSurface pbuffer after the
    /// platform seam). The render writes the buffer directly — no readback.
    ZeroCopy,
    /// Offscreen texture render target, read back into the mapped tensor.
    TextureMem,
    /// Offscreen texture render target, read back into the destination PBO's
    /// PACK binding (the tensor must never be mapped on the GL thread).
    TexturePbo,
}

/// Classify the destination lowering from the platform's zero-copy import
/// capability and the destination's memory class. A DMA destination without
/// import support (e.g. dma-heap present but `EGL_EXT_image_dma_buf_import`
/// missing) degrades to the mapped texture path rather than failing.
pub(super) fn lower_dst(zero_copy_import: bool, dst_mem: TensorMemory) -> DstLowering {
    match dst_mem {
        TensorMemory::DmaBuf if zero_copy_import => DstLowering::ZeroCopy,
        TensorMemory::Pbo => DstLowering::TexturePbo,
        _ => DstLowering::TextureMem,
    }
}

/// How a convert renders — the pure plan half of the engine
/// (`convert_via_engine` in `processor/mod.rs` executes it). Exactly one
/// plan per (source format, destination format, destination lowering)
/// triple.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ConvertPlan {
    /// One render pass into the bound destination target (packed via the
    /// texture shaders, planar via the planar shader), then the lowering's
    /// readback (none for zero-copy).
    SinglePass,
    /// Zero-copy packed-RGB only: pass 1 renders RGBA into an intermediate
    /// texture, pass 2 packs it into the destination reinterpreted as
    /// RGBA8 at `W*3/4 × H` (GL has no 3-byte render format). Texture
    /// lowerings render genuine RGB in one pass instead — see
    /// `setup_renderbuffer_non_dma`/`setup_renderbuffer_from_pbo`.
    TwoPassPackedRgb,
    /// Planar destination, driven by an ordinary packed convert: pass 1
    /// renders the source into an intermediate RGBA texture via the full
    /// `convert_to` machinery (any source format — `select_nv_path`'s
    /// colorimetry-exact ShaderR8 + Vivante carve-out for NV*, the plain
    /// upload/import path for everything else), pass 2 deinterleaves RGBA
    /// into the planar destination (`bind_dst` classifies pass 2's target
    /// the same way `SinglePass` does, so a texture lowering reads back
    /// same as `SinglePass` would). Selected on EVERY lowering for NV*
    /// sources, and additionally on texture lowerings for every source:
    /// the single-pass planar shader (`draw_camera_texture_to_rgb_planar`)
    /// exists only where `Platform::EXTERNAL_OES` is true (false on
    /// ANGLE/Android — `texture_program_planar` is `None` there,
    /// regardless of source format), and even where it exists its source
    /// import is DMA-only, with no upload path for a heap/Mem source.
    /// Zero-copy keeps the non-NV single-pass route for a source it can
    /// import (proven, EXTERNAL_OES path with a DMA source); a host source
    /// takes this plan there too. Also the Vivante GC7000UL single-pass
    /// GPU-hang workaround for NV* (EDGEAI-1180).
    TwoPassNvPlanar,
}

/// Decide the render plan. Pure (src format, src residence, dst format, dst
/// lowering) → plan; capability differences arrive via the lowering, never as
/// platform branches here. `src_host` is a source in host memory (`Mem`,
/// `Shm`): one with no GPU import, which only the upload path of the ordinary
/// packed convert can read.
pub(super) fn plan_convert(
    src_fmt: PixelFormat,
    src_host: bool,
    dst_fmt: PixelFormat,
    lowering: DstLowering,
) -> ConvertPlan {
    // Packed RGB only needs the two-pass W*3/4 reinterpretation on a
    // zero-copy destination (no native 3-byte GL render format); texture
    // destinations already render genuine RGB via `setup_renderbuffer_non_dma`
    // / `setup_renderbuffer_from_pbo`, so they stay single-pass.
    if lowering == DstLowering::ZeroCopy && dst_fmt == PixelFormat::Rgb {
        return ConvertPlan::TwoPassPackedRgb;
    }
    // A texture-lowered (Mem/Pbo) planar destination has NO single-pass
    // route for any source format: `texture_program_planar` (the
    // EXTERNAL_OES planar shader `draw_camera_texture_to_rgb_planar`
    // needs) is built only where `Platform::EXTERNAL_OES` is true — never
    // on ANGLE or Android — and even on Linux (where it IS built) the
    // source import (`get_or_create_egl_image`) is unconditionally
    // DMA-only, so a heap/Mem source fails there too. The two-pass plan's
    // pass 1 is the ordinary `convert_to` packed path, which already
    // handles every source format (including a Mem source) on every
    // platform.
    if dst_fmt.layout() == PixelLayout::Planar && lowering != DstLowering::ZeroCopy {
        return ConvertPlan::TwoPassNvPlanar;
    }
    // The same import rule on a zero-copy destination: the single-pass planar
    // shader cannot read a host source, so it takes pass 1's upload instead.
    // A driver that refuses the destination import re-plans onto the texture
    // lowering above and reaches the same answer; one that accepts it (V3D,
    // Mali) otherwise ended the convert with the source import's error.
    if dst_fmt.layout() == PixelLayout::Planar && src_host {
        return ConvertPlan::TwoPassNvPlanar;
    }
    // Zero-copy NV*→planar still needs the two-pass ShaderR8 route: the
    // single-pass planar shader has no multi-plane EGLImage/IOSurface
    // binding for semi-planar NV even when EXTERNAL_OES is available.
    // Zero-copy non-NV→planar stays single-pass (proven EXTERNAL_OES +
    // DMA-source route).
    if dst_fmt.layout() == PixelLayout::Planar
        && matches!(
            src_fmt,
            PixelFormat::Nv12 | PixelFormat::Nv16 | PixelFormat::Nv24
        )
    {
        return ConvertPlan::TwoPassNvPlanar;
    }
    ConvertPlan::SinglePass
}

/// A GL viewport / scissor rectangle in **pixels**, bottom-left origin.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Viewport {
    pub(super) x: i32,
    pub(super) y: i32,
    pub(super) w: i32,
    pub(super) h: i32,
}

/// Lower a destination tile to its GL band rectangle on the live Linux
/// DMA-BUF path, which is **top-down** (GL framebuffer row 0 == memory row 0,
/// verified on-target): the band's GL `y` is simply `region.y`, with no
/// bottom-left flip — the renderer's texcoord flip keeps the image upright.
/// The single home for the orientation convention: BOTH the band `glViewport`
/// (`bind_dst` setup) and the matching `glScissor` (letterbox-clear
/// confinement in `convert_to`) lower through here so they can never
/// disagree. [`region_to_viewport`] is the bottom-up twin for a future
/// bottom-left-origin surface (e.g. the macOS pbuffer batch path).
#[inline]
pub(super) fn region_to_viewport_top_down(region: Region) -> Viewport {
    Viewport {
        x: region.x as i32,
        y: region.y as i32,
        w: region.width as i32,
        h: region.height as i32,
    }
}

/// Lower a top-left `region` of an image `parent_h` rows tall to a bottom-left
/// GL viewport. The horizontal axis is unchanged; the vertical axis is flipped
/// so the region's *top* edge maps to the correct GL row.
///
/// Staged for the first bottom-left-origin render target (macOS pbuffer batch
/// path, PR-A); the live Linux DMA-BUF path is top-down and uses
/// [`region_to_viewport_top_down`]. Until then only the unit tests call this.
#[allow(dead_code)]
pub(super) fn region_to_viewport(region: Region, parent_h: usize) -> Viewport {
    // Bottom-left origin: the GL y of the region's top-left corner is the number
    // of rows *below* the region — `parent_h - (y + h)`. Saturating so a region
    // flush against the bottom edge (or a degenerate over-tall region) yields a
    // non-negative origin rather than wrapping.
    let y_flipped = parent_h.saturating_sub(region.y.saturating_add(region.height));
    Viewport {
        x: region.x as i32,
        y: y_flipped as i32,
        w: region.width as i32,
        h: region.height as i32,
    }
}

/// Source sampling rectangle as normalised `[u_min, v_min, u_extent, v_extent]`
/// over a `src_w × src_h` texture. `None` (whole source) is the identity
/// `[0, 0, 1, 1]`. Matches the `src_rect_uv` produced by
/// [`crate::gl::core::float_crop_uniforms`] so the converged renderer and the
/// float path agree on source addressing.
///
/// Staged for the source-view sampling path (the u8 renderer still computes
/// its `RegionOfInterest` corners inline); until wired, only the unit tests
/// call this.
#[allow(dead_code)]
pub(super) fn source_uv(region: Option<Region>, src_w: usize, src_h: usize) -> [f32; 4] {
    match region {
        Some(r) if src_w > 0 && src_h > 0 => [
            r.x as f32 / src_w as f32,
            r.y as f32 / src_h as f32,
            r.width as f32 / src_w as f32,
            r.height as f32 / src_h as f32,
        ],
        _ => [0.0, 0.0, 1.0, 1.0],
    }
}

/// How a batch of `n` destination tiles maps onto GPU imports.
///
/// `OneImport` is the goal — the whole destination is imported once and each
/// tile is a `glViewport` into it. `Chunked(tiles_per_chunk)` is the fallback
/// when the full batched render target would exceed a `GL_MAX_*` limit: the
/// batch is split into chunks of `tiles_per_chunk`, one import per chunk.
/// `PerTileImport` is the degenerate floor (a single tile already too large to
/// batch) — equivalent to the legacy per-call path.
/// Staged for the `GL_MAX_*` chunking follow-up (split an over-limit batch
/// into per-chunk imports); until wired into `convert_batch`, only the unit
/// tests exercise this and [`plan_batch`].
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum BatchPath {
    OneImport,
    Chunked(usize),
    PerTileImport,
}

/// Decide the batch path from the per-tile render-target row count and the GPU
/// row limit (`GL_MAX_TEXTURE_SIZE` / `GL_MAX_VIEWPORT_DIMS`, whichever binds).
///
/// `rows_per_tile` is the render target height a single tile occupies (`H` for a
/// packed `HWC` destination, `3·H` for a planar `CHW` packed render target).
/// `max_rows` is the device limit. The result is:
///
/// * `n_tiles · rows_per_tile ≤ max_rows`  → `OneImport`
/// * `rows_per_tile ≤ max_rows < n·rows`   → `Chunked(max_rows / rows_per_tile)`
/// * `rows_per_tile > max_rows`            → `PerTileImport`
#[allow(dead_code)]
pub(super) fn plan_batch(n_tiles: usize, rows_per_tile: usize, max_rows: usize) -> BatchPath {
    if rows_per_tile == 0 || n_tiles == 0 {
        return BatchPath::OneImport;
    }
    if rows_per_tile > max_rows {
        return BatchPath::PerTileImport;
    }
    let tiles_per_chunk = max_rows / rows_per_tile;
    if tiles_per_chunk >= n_tiles {
        BatchPath::OneImport
    } else {
        BatchPath::Chunked(tiles_per_chunk)
    }
}

/// Where a tensor's logical image sits on the texture its import covers.
///
/// Two independent reasons the two can differ, both folded the same way:
/// a pool buffer narrowed by `configure_image` keeps its whole texture and
/// reports a larger [`extent`](Self::extent) (Windows/D3D11), and a source
/// rebased to an aligned DMA-BUF offset starts the logical image partway
/// into the import and reports a nonzero [`origin`](Self::origin) (Linux,
/// issue #170). A platform whose import IS the logical image reports
/// [`ImportMap::WHOLE`], which every helper here treats as the identity.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct ImportMap {
    /// Texel size of the imported texture when it can exceed the logical
    /// image ([`super::platform::GlPlatform::import_extent`]); `None` when
    /// the import is exactly the logical image.
    pub(super) extent: Option<(u32, u32)>,
    /// Texels from the texture's origin to the logical image's first pixel
    /// ([`super::platform::GlPlatform::import_origin`]).
    pub(super) origin: (u32, u32),
}

impl ImportMap {
    /// The import is exactly the logical image: no scale, no shift.
    pub(super) const WHOLE: Self = Self {
        extent: None,
        origin: (0, 0),
    };
}

/// How one axis of a logical image maps onto the texture an import covers:
/// `(origin, scale, limit)` — the normalized coordinate the logical image
/// starts at, the factor that places it over its share of the texture, and the
/// normalized coordinate of its far edge. An axis that is not narrowed or
/// shifted (and a degenerate or contradictory map) maps as the identity.
///
/// The far edge is not pulled half a physical texel inside here. These
/// coordinates are the endpoints of the quad's texcoord attribute, so moving
/// one rescales the whole affine dst-to-source mapping rather than excluding
/// an edge: measured on a narrowed 128x96 source, the inset left the identity
/// convert differing from a fresh buffer in 34380 of 49152 bytes.
///
/// The inset belongs on the sample instead, and that is where it now is: every
/// shader that samples through this mapping clamps each sample coordinate to
/// [`sample_clamp_rect`], so a `LINEAR` kernel centred within half a texel of
/// the logical edge cannot blend the stale texel beyond it. Measured on the
/// RTX 3070 and on WARP, the last row and column of an upscaled narrowed
/// source then match a fresh buffer of the same geometry byte for byte
/// (492-762 bytes differed by up to 48 without the clamp).
///
/// The origin is an ADDITIVE offset and the logical size a MULTIPLICATIVE
/// scale, in that order: a coordinate `t` over the logical image lands at
/// `(origin + t * logical) / extent`. A map whose shifted image would run
/// past the texture is contradictory and maps as the identity, same as a
/// degenerate one.
fn axis_map(logical: usize, origin: u32, extent: u32) -> (f32, f32, f32) {
    let span = (origin as u64).saturating_add(logical as u64);
    if extent == 0 || logical == 0 || span > extent as u64 {
        return (0.0, 1.0, 1.0);
    }
    let texture = extent as f32;
    (
        origin as f32 / texture,
        logical as f32 / texture,
        span as f32 / texture,
    )
}

/// Map a source rectangle from the tensor's logical image onto the larger
/// texture its import covers.
///
/// `roi` is normalized over the logical image; `map` is where that image sits
/// on the texture. The logical image occupies a contiguous block of the
/// texture's own texels starting at the map's origin, so mapping one onto the
/// other is one shift and one multiply per axis — the half-texel inset the
/// crop math already applied scales with it — held inside the logical edge by
/// [`axis_map`]. [`ImportMap::WHOLE`] and an extent no larger than the logical
/// image leave `roi` untouched.
pub(super) fn scale_roi_to_import(
    roi: super::RegionOfInterest,
    logical: (usize, usize),
    map: ImportMap,
) -> super::RegionOfInterest {
    let Some((pw, ph)) = map.extent else {
        return roi;
    };
    let (ox, sx, lx) = axis_map(logical.0, map.origin.0, pw);
    let (oy, sy, ly) = axis_map(logical.1, map.origin.1, ph);
    super::RegionOfInterest {
        left: (ox + roi.left * sx).min(lx),
        top: (oy + roi.top * sy).min(ly),
        right: (ox + roi.right * sx).min(lx),
        bottom: (oy + roi.bottom * sy).min(ly),
    }
}

/// [`scale_roi_to_import`] for the float paths' `src_rect_uv`, which is an
/// origin and a size rather than two corners: the origin shifts and scales,
/// and the size is trimmed to keep the far edge inside the same limit.
pub(super) fn scale_uv_rect_to_import(
    rect: [f32; 4],
    logical: (usize, usize),
    map: ImportMap,
) -> [f32; 4] {
    let Some((pw, ph)) = map.extent else {
        return rect;
    };
    let (ox, sx, lx) = axis_map(logical.0, map.origin.0, pw);
    let (oy, sy, ly) = axis_map(logical.1, map.origin.1, ph);
    let left = (ox + rect[0] * sx).min(lx);
    let top = (oy + rect[1] * sy).min(ly);
    [
        left,
        top,
        (rect[2] * sx).min(lx - left).max(0.0),
        (rect[3] * sy).min(ly - top).max(0.0),
    ]
}

/// The rectangle a source sample may reach, as the `src_extent` uniform of
/// the source-sampling shaders: `[u_min, v_min, u_max, v_max]`, the logical
/// image's share of the texture in normalized coordinates, inset by half a
/// physical texel on each side.
///
/// A `LINEAR` sample at those bounds is centred on the logical image's edge
/// texel, so the kernel cannot reach the texel beyond it. On a texture that
/// is exactly the logical image ([`ImportMap::WHOLE`], or an extent no larger
/// than `logical`) that texel does not exist and `CLAMP_TO_EDGE` already
/// returns the edge value, so the clamp changes nothing there. On an import
/// that covers more of the texture than the logical image the texels outside
/// the image hold the pool buffer's previous content, or — when the map has a
/// nonzero origin — the bytes the rebase walked back over and the pitch
/// padding behind the last column, which an upscale would otherwise blend
/// into the first or last row or column.
///
/// A degenerate logical size yields the whole texture, `[0, 0, 1, 1]`.
pub(super) fn sample_clamp_rect(logical: (usize, usize), map: ImportMap) -> [f32; 4] {
    sample_clamp_rect_within(logical, map, [0.0, 0.0, 1.0, 1.0])
}

/// [`sample_clamp_rect`] narrowed to a source crop: `crop` is
/// `[u_min, v_min, u_max, v_max]` normalized to the logical image, and the
/// result brackets the crop's texels instead of the whole image's. A source
/// crop's texture coordinates span its true edges, so this clamp is what keeps
/// a `LINEAR` kernel at those edges from blending the pixels beyond them.
pub(super) fn sample_clamp_rect_within(
    logical: (usize, usize),
    map: ImportMap,
    crop: [f32; 4],
) -> [f32; 4] {
    fn axis(logical: usize, origin: u32, extent: Option<u32>, lo: f32, hi: f32) -> (f32, f32) {
        if logical == 0 {
            return (0.0, 1.0);
        }
        let span = (origin as u64).saturating_add(logical as u64);
        let (texture, first) = match extent {
            Some(e) if e as u64 > logical as u64 && e as u64 >= span => (e as f32, origin as f32),
            // No extent, an extent no larger than the image, or a
            // contradictory shift: the texture is the image at its origin.
            _ => (logical as f32, 0.0),
        };
        let lo = (lo * logical as f32).clamp(0.0, logical as f32);
        let hi = (hi * logical as f32).clamp(lo, logical as f32);
        // A crop narrower than one texel collapses to its centre.
        let (lo, hi) = if hi - lo < 1.0 {
            let c = (lo + hi) * 0.5;
            (c, c)
        } else {
            (lo + 0.5, hi - 0.5)
        };
        ((first + lo) / texture, (first + hi) / texture)
    }
    let (u_min, u_max) = axis(
        logical.0,
        map.origin.0,
        map.extent.map(|e| e.0),
        crop[0],
        crop[2],
    );
    let (v_min, v_max) = axis(
        logical.1,
        map.origin.1,
        map.extent.map(|e| e.1),
        crop[1],
        crop[3],
    );
    [u_min, v_min, u_max, v_max]
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    fn region(x: usize, y: usize, w: usize, h: usize) -> Region {
        Region::new(x, y, w, h)
    }

    #[test]
    fn viewport_top_down_is_identity() {
        // The live DMA path is top-down: GL y == memory row y, no flip. Three
        // stacked 16-row tiles keep their memory order in GL coordinates.
        let ys: Vec<i32> = (0..3)
            .map(|n| region_to_viewport_top_down(region(0, n * 16, 64, 16)).y)
            .collect();
        assert_eq!(ys, vec![0, 16, 32]);
        assert_eq!(
            region_to_viewport_top_down(region(10, 4, 20, 8)),
            Viewport {
                x: 10,
                y: 4,
                w: 20,
                h: 8
            }
        );
    }

    #[test]
    fn viewport_whole_image_is_origin() {
        // A region covering the whole image maps to the full viewport at (0,0):
        // y_flip = H - (0 + H) = 0.
        let vp = region_to_viewport(region(0, 0, 64, 48), 48);
        assert_eq!(
            vp,
            Viewport {
                x: 0,
                y: 0,
                w: 64,
                h: 48
            }
        );
    }

    #[test]
    fn viewport_top_tile_lands_at_top_in_gl_coords() {
        // Top 16-row band of a 48-tall image: GL y = 48 - (0 + 16) = 32
        // (the top of a top-left image is the HIGH end of bottom-left GL space).
        let vp = region_to_viewport(region(0, 0, 64, 16), 48);
        assert_eq!(
            vp,
            Viewport {
                x: 0,
                y: 32,
                w: 64,
                h: 16
            }
        );
    }

    #[test]
    fn viewport_bottom_tile_lands_at_origin() {
        // Bottom 16-row band (y=32): GL y = 48 - (32 + 16) = 0.
        let vp = region_to_viewport(region(0, 32, 64, 16), 48);
        assert_eq!(
            vp,
            Viewport {
                x: 0,
                y: 0,
                w: 64,
                h: 16
            }
        );
    }

    #[test]
    fn viewport_batch_bands_tile_without_overlap() {
        // Three stacked 16-row tiles of a 48-tall batched target partition the
        // viewport exactly: GL y bands are [32,48), [16,32), [0,16).
        let h = 16;
        let ys: Vec<i32> = (0..3)
            .map(|n| region_to_viewport(region(0, n * h, 64, h), 3 * h).y)
            .collect();
        assert_eq!(ys, vec![32, 16, 0]);
    }

    #[test]
    fn viewport_x_offset_preserved() {
        let vp = region_to_viewport(region(10, 4, 20, 8), 32);
        assert_eq!(
            vp,
            Viewport {
                x: 10,
                y: 32 - 12,
                w: 20,
                h: 8
            }
        );
    }

    #[test]
    fn source_uv_none_is_identity() {
        assert_eq!(source_uv(None, 640, 480), [0.0, 0.0, 1.0, 1.0]);
    }

    #[test]
    fn source_uv_half_rect() {
        // Right half of a 640×480 source.
        assert_eq!(
            source_uv(Some(region(320, 0, 320, 480)), 640, 480),
            [0.5, 0.0, 0.5, 1.0]
        );
    }

    #[test]
    fn source_uv_zero_dims_falls_back_to_identity() {
        assert_eq!(
            source_uv(Some(region(0, 0, 1, 1)), 0, 0),
            [0.0, 0.0, 1.0, 1.0]
        );
    }

    #[test]
    fn plan_batch_fits_one_import() {
        // 4 tiles × 64 rows = 256 ≤ 2048 → one import.
        assert_eq!(plan_batch(4, 64, 2048), BatchPath::OneImport);
    }

    #[test]
    fn plan_batch_chunks_when_over_limit() {
        // 40 tiles × 64 rows = 2560 > 2048; floor(2048/64)=32 per chunk.
        assert_eq!(plan_batch(40, 64, 2048), BatchPath::Chunked(32));
    }

    #[test]
    fn plan_batch_single_oversize_tile_is_per_tile() {
        // One planar tile of 3·1024 = 3072 rows > 2048 → degenerate per-tile.
        assert_eq!(plan_batch(8, 3072, 2048), BatchPath::PerTileImport);
    }

    #[test]
    fn plan_batch_exact_fit_is_one_import() {
        // 32 tiles × 64 = 2048 == limit → still one import (≤, not <).
        assert_eq!(plan_batch(32, 64, 2048), BatchPath::OneImport);
    }

    #[test]
    fn plan_batch_degenerate_inputs() {
        assert_eq!(plan_batch(0, 64, 2048), BatchPath::OneImport);
        assert_eq!(plan_batch(4, 0, 2048), BatchPath::OneImport);
    }

    #[test]
    fn plan_convert_full_table() {
        use DstLowering::*;
        use PixelFormat::*;
        let nv = [Nv12, Nv16, Nv24];
        let non_nv = [Rgba, Bgra, Grey, Yuyv];
        // Zero-copy: packed RGB always two-pass; NV→planar two-pass; the rest
        // single-pass (incl. non-NV → planar, which the planar shader handles
        // in one pass).
        for src in nv.iter().chain(&non_nv) {
            assert_eq!(
                plan_convert(*src, false, Rgb, ZeroCopy),
                ConvertPlan::TwoPassPackedRgb,
                "{src:?}->Rgb zero-copy"
            );
        }
        for src in nv {
            assert_eq!(
                plan_convert(src, false, PlanarRgb, ZeroCopy),
                ConvertPlan::TwoPassNvPlanar
            );
            assert_eq!(
                plan_convert(src, false, PlanarRgba, ZeroCopy),
                ConvertPlan::TwoPassNvPlanar
            );
            assert_eq!(
                plan_convert(src, false, Rgba, ZeroCopy),
                ConvertPlan::SinglePass
            );
        }
        for src in non_nv {
            assert_eq!(
                plan_convert(src, false, PlanarRgb, ZeroCopy),
                ConvertPlan::SinglePass
            );
            assert_eq!(
                plan_convert(src, false, Rgba, ZeroCopy),
                ConvertPlan::SinglePass
            );
        }
        // A host source cannot feed the single-pass planar shader, so a
        // zero-copy planar destination takes the two-pass route for it; a
        // packed destination is unaffected.
        for src in nv.iter().chain(&non_nv) {
            for dst in [PlanarRgb, PlanarRgba] {
                assert_eq!(
                    plan_convert(*src, true, dst, ZeroCopy),
                    ConvertPlan::TwoPassNvPlanar,
                    "host {src:?}->{dst:?} zero-copy"
                );
            }
            assert_eq!(
                plan_convert(*src, true, Rgb, ZeroCopy),
                ConvertPlan::TwoPassPackedRgb
            );
            assert_eq!(
                plan_convert(*src, true, Rgba, ZeroCopy),
                ConvertPlan::SinglePass
            );
        }
        // Texture lowerings: packed-RGB single-pass (the texture destination
        // renders genuine RGB); EVERY source→planar is two-pass regardless
        // of format — the single-pass planar shader
        // (`draw_camera_texture_to_rgb_planar`) needs
        // `Platform::EXTERNAL_OES` (false on ANGLE/Android) AND a DMA
        // source, neither of which a texture-lowered destination can rely
        // on, so non-NV sources route through the same two-pass plan as NV*
        // instead of single-pass.
        for lowering in [TextureMem, TexturePbo] {
            for src in nv.iter().chain(&non_nv) {
                for dst in [PlanarRgb, PlanarRgba] {
                    assert_eq!(
                        plan_convert(*src, false, dst, lowering),
                        ConvertPlan::TwoPassNvPlanar,
                        "{src:?}->{dst:?} via {lowering:?}"
                    );
                }
                for dst in [Rgba, Bgra, Rgb, Grey] {
                    assert_eq!(
                        plan_convert(*src, false, dst, lowering),
                        ConvertPlan::SinglePass,
                        "{src:?}->{dst:?} via {lowering:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn lower_dst_full_table() {
        use TensorMemory::*;
        // With zero-copy import: only a DMA destination is zero-copy; PBO
        // keeps its PACK readback; Mem/Shm read back through the map.
        assert_eq!(lower_dst(true, DmaBuf), DstLowering::ZeroCopy);
        assert_eq!(lower_dst(true, Pbo), DstLowering::TexturePbo);
        assert_eq!(lower_dst(true, Mem), DstLowering::TextureMem);
        assert_eq!(lower_dst(true, Shm), DstLowering::TextureMem);
        // Without import support a DMA destination degrades to the mapped
        // texture path (dma-heap without EGL dma_buf_import) — never an error.
        assert_eq!(lower_dst(false, DmaBuf), DstLowering::TextureMem);
        assert_eq!(lower_dst(false, Pbo), DstLowering::TexturePbo);
        assert_eq!(lower_dst(false, Mem), DstLowering::TextureMem);
        assert_eq!(lower_dst(false, Shm), DstLowering::TextureMem);
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod import_extent_tests {
    use super::*;

    /// The pre-origin shape of every fold call: an extent, at origin `(0, 0)`.
    fn narrowed(extent: (u32, u32)) -> ImportMap {
        ImportMap {
            extent: Some(extent),
            origin: (0, 0),
        }
    }

    fn roi() -> super::super::RegionOfInterest {
        super::super::RegionOfInterest {
            left: 0.0,
            top: 1.0,
            right: 1.0,
            bottom: 0.0,
        }
    }

    /// 128x96 written into a 128x128 pool texture: u is untouched (that axis
    /// is not narrowed), v is scaled to the logical image's share.
    #[test]
    fn a_narrowed_logical_image_scales_by_its_share_of_the_texture() {
        let r = scale_roi_to_import(roi(), (128, 96), narrowed((128, 128)));
        assert_eq!(r.left, 0.0);
        assert_eq!(r.right, 1.0);
        assert_eq!(r.top, 0.75);
        assert_eq!(r.bottom, 0.0);
    }

    #[test]
    fn both_axes_scale_and_an_interior_rectangle_is_unchanged_in_shape() {
        let src = super::super::RegionOfInterest {
            left: 0.25,
            top: 0.75,
            right: 0.5,
            bottom: 0.25,
        };
        let r = scale_roi_to_import(src, (64, 100), narrowed((128, 200)));
        assert_eq!((r.left, r.right), (0.125, 0.25));
        assert_eq!((r.top, r.bottom), (0.375, 0.125));
    }

    #[test]
    fn equal_extents_and_no_extent_leave_the_rectangle_alone() {
        let r = scale_roi_to_import(roi(), (128, 96), narrowed((128, 96)));
        assert_eq!((r.left, r.top, r.right, r.bottom), (0.0, 1.0, 1.0, 0.0));
        let r = scale_roi_to_import(roi(), (128, 96), ImportMap::WHOLE);
        assert_eq!((r.left, r.top, r.right, r.bottom), (0.0, 1.0, 1.0, 0.0));
    }

    /// A logical image larger than the reported extent is a contradiction; the
    /// rectangle is left alone rather than magnified past the texture.
    #[test]
    fn a_logical_image_larger_than_the_extent_is_not_magnified() {
        let r = scale_roi_to_import(roi(), (256, 256), narrowed((128, 128)));
        assert_eq!((r.left, r.top, r.right, r.bottom), (0.0, 1.0, 1.0, 0.0));
    }

    #[test]
    fn a_degenerate_extent_leaves_the_rectangle_alone() {
        let r = scale_roi_to_import(roi(), (128, 96), narrowed((0, 0)));
        assert_eq!((r.left, r.top, r.right, r.bottom), (0.0, 1.0, 1.0, 0.0));
    }

    /// The float paths' origin+size rectangle: the origin scales and the size
    /// is trimmed so the far edge lands where a corner would.
    #[test]
    fn a_uv_rect_scales_its_origin_and_trims_its_size() {
        let r = scale_uv_rect_to_import([0.0, 0.0, 1.0, 1.0], (128, 96), narrowed((128, 128)));
        assert_eq!([r[0], r[1]], [0.0, 0.0]);
        assert_eq!(r[2], 1.0);
        assert_eq!(r[3], 0.75);
    }

    #[test]
    fn a_uv_rect_keeps_an_interior_crop_and_passes_no_extent_through() {
        // Half the width starting a quarter in, on an axis narrowed to 3/4:
        // both scale, and the far edge (0.25 + 0.5) * 0.75 stays interior.
        let r = scale_uv_rect_to_import([0.25, 0.25, 0.5, 0.5], (96, 96), narrowed((128, 128)));
        assert_eq!([r[0], r[1]], [0.1875, 0.1875]);
        assert_eq!([r[2], r[3]], [0.375, 0.375]);
        let r = scale_uv_rect_to_import([0.25, 0.25, 0.5, 0.5], (96, 96), ImportMap::WHOLE);
        assert_eq!(r, [0.25, 0.25, 0.5, 0.5]);
    }

    /// 128x96 in a 128x128 texture: u spans the whole texture inset by half
    /// a texel, v stops half a texel short of row 96.
    #[test]
    fn a_narrowed_image_clamps_samples_half_a_texel_inside_its_edge() {
        let r = sample_clamp_rect((128, 96), narrowed((128, 128)));
        assert_eq!(r, [0.5 / 128.0, 0.5 / 128.0, 127.5 / 128.0, 95.5 / 128.0]);
    }

    /// Without an extent the texture is the logical image, and the clamp is
    /// the half-texel inset of the whole texture on both axes.
    #[test]
    fn no_extent_clamps_to_the_textures_own_edge_texels() {
        let r = sample_clamp_rect((128, 96), ImportMap::WHOLE);
        assert_eq!(r, [0.5 / 128.0, 0.5 / 96.0, 127.5 / 128.0, 95.5 / 96.0]);
        assert_eq!(sample_clamp_rect((128, 96), narrowed((128, 96))), r);
    }

    /// An extent smaller than the logical image is a contradiction; the
    /// texture is taken to be the logical image, as in `scale_roi_to_import`.
    #[test]
    fn an_extent_smaller_than_the_image_is_ignored() {
        assert_eq!(
            sample_clamp_rect((256, 256), narrowed((128, 128))),
            sample_clamp_rect((256, 256), ImportMap::WHOLE)
        );
    }

    #[test]
    fn a_degenerate_logical_size_leaves_the_whole_texture_reachable() {
        assert_eq!(
            sample_clamp_rect((0, 0), narrowed((128, 128))),
            [0.0, 0.0, 1.0, 1.0]
        );
        assert_eq!(
            sample_clamp_rect((0, 96), ImportMap::WHOLE),
            [0.0, 0.5 / 96.0, 1.0, 95.5 / 96.0]
        );
    }

    /// One logical texel in a larger texture: min and max meet at that
    /// texel's centre. The only input where the bound could invert.
    #[test]
    fn a_one_texel_image_clamps_to_its_single_texel_centre() {
        assert_eq!(
            sample_clamp_rect((1, 1), narrowed((128, 128))),
            [0.5 / 128.0; 4]
        );
        assert_eq!(sample_clamp_rect((1, 1), ImportMap::WHOLE), [0.5; 4]);
    }

    /// A shifted import: the logical 16-wide image sits at texel 8 of a
    /// 24-wide texture. The ROI must land on `[8/24, 24/24]`, not `[0, 16/24]`
    /// -- the whole point of the origin. This is the (8, 0) view of issue
    /// #165's probe at RGBA, whose 32-byte offset rebases to 0 with a
    /// 8-texel shift.
    #[test]
    fn scale_roi_to_import_offsets_by_the_origin() {
        let roi = super::super::RegionOfInterest {
            left: 0.0,
            top: 0.0,
            right: 1.0,
            bottom: 1.0,
        };
        let map = ImportMap {
            extent: Some((24, 16)),
            origin: (8, 0),
        };
        let got = scale_roi_to_import(roi, (16, 16), map);
        assert!((got.left - 8.0 / 24.0).abs() < 1e-6, "left {}", got.left);
        assert!((got.right - 1.0).abs() < 1e-6, "right {}", got.right);
        // The unshifted axis is untouched.
        assert!((got.top - 0.0).abs() < 1e-6, "top {}", got.top);
        assert!((got.bottom - 1.0).abs() < 1e-6, "bottom {}", got.bottom);
    }

    /// A half-width ROI on a shifted import: the origin is an ADDITIVE
    /// offset and the logical size is the MULTIPLICATIVE scale, so the
    /// midpoint lands at `(8 + 8) / 24`, not at `8 / 24 * 0.5` or `0.5`.
    #[test]
    fn scale_roi_to_import_composes_origin_and_scale() {
        let roi = super::super::RegionOfInterest {
            left: 0.0,
            top: 0.25,
            right: 0.5,
            bottom: 0.75,
        };
        let map = ImportMap {
            extent: Some((24, 16)),
            origin: (8, 0),
        };
        let got = scale_roi_to_import(roi, (16, 16), map);
        assert!((got.left - 8.0 / 24.0).abs() < 1e-6, "left {}", got.left);
        assert!(
            (got.right - 16.0 / 24.0).abs() < 1e-6,
            "right {}",
            got.right
        );
        assert!((got.top - 0.25).abs() < 1e-6, "top {}", got.top);
        assert!((got.bottom - 0.75).abs() < 1e-6, "bottom {}", got.bottom);
    }

    /// `ImportMap::WHOLE` is the identity on all three helpers -- the state
    /// every platform whose import IS the logical image reports, and the
    /// state every call site had before the origin existed.
    #[test]
    fn whole_import_map_is_the_identity() {
        let roi = super::super::RegionOfInterest {
            left: 0.1,
            top: 0.2,
            right: 0.8,
            bottom: 0.9,
        };
        let got = scale_roi_to_import(roi, (64, 64), ImportMap::WHOLE);
        assert_eq!(
            (got.left, got.top, got.right, got.bottom),
            (0.1, 0.2, 0.8, 0.9)
        );
        assert_eq!(
            scale_uv_rect_to_import([0.1, 0.2, 0.3, 0.4], (64, 64), ImportMap::WHOLE),
            [0.1, 0.2, 0.3, 0.4]
        );
        assert_eq!(ImportMap::default(), ImportMap::WHOLE);
        let [u0, v0, u1, v1] = sample_clamp_rect((64, 64), ImportMap::WHOLE);
        assert!((u0 - 0.5 / 64.0).abs() < 1e-9 && (v0 - 0.5 / 64.0).abs() < 1e-9);
        assert!((u1 - 63.5 / 64.0).abs() < 1e-9 && (v1 - 63.5 / 64.0).abs() < 1e-9);
    }

    /// A source crop narrows the clamp to its own texels, half a texel inside
    /// its edges, on a whole texture and on a shifted import alike.
    #[test]
    fn sample_clamp_rect_within_brackets_a_crop() {
        let crop = [16.0 / 64.0, 8.0 / 32.0, 48.0 / 64.0, 24.0 / 32.0];
        let [u0, v0, u1, v1] = sample_clamp_rect_within((64, 32), ImportMap::WHOLE, crop);
        assert!((u0 - 16.5 / 64.0).abs() < 1e-6 && (u1 - 47.5 / 64.0).abs() < 1e-6);
        assert!((v0 - 8.5 / 32.0).abs() < 1e-6 && (v1 - 23.5 / 32.0).abs() < 1e-6);
        let map = ImportMap {
            extent: Some((80, 32)),
            origin: (8, 0),
        };
        let [u0, _, u1, _] = sample_clamp_rect_within((64, 32), map, crop);
        assert!((u0 - 24.5 / 80.0).abs() < 1e-6 && (u1 - 55.5 / 80.0).abs() < 1e-6);
        assert_eq!(
            sample_clamp_rect_within((64, 32), map, [0.0, 0.0, 1.0, 1.0]),
            sample_clamp_rect((64, 32), map)
        );
    }

    /// The clamp rectangle must bracket the LOGICAL image's texels on a
    /// shifted texture, so a LINEAR kernel at the left edge cannot blend
    /// the rebase padding in front of it and one at the right edge cannot
    /// reach the pitch padding behind it.
    #[test]
    fn sample_clamp_rect_brackets_a_shifted_image() {
        let map = ImportMap {
            extent: Some((24, 16)),
            origin: (8, 0),
        };
        let [u0, v0, u1, v1] = sample_clamp_rect((16, 16), map);
        assert!((u0 - 8.5 / 24.0).abs() < 1e-6, "u0 {u0}");
        assert!((u1 - 23.5 / 24.0).abs() < 1e-6, "u1 {u1}");
        assert!((v0 - 0.5 / 16.0).abs() < 1e-6, "v0 {v0}");
        assert!((v1 - 15.5 / 16.0).abs() < 1e-6, "v1 {v1}");
    }

    /// A contradictory map -- the shifted image would run past the texture
    /// -- falls back to the identity rather than sampling outside it.
    #[test]
    fn a_shifted_image_that_overruns_the_extent_maps_as_the_identity() {
        let roi = super::super::RegionOfInterest {
            left: 0.0,
            top: 0.0,
            right: 1.0,
            bottom: 1.0,
        };
        let map = ImportMap {
            extent: Some((20, 16)),
            origin: (8, 0),
        };
        let got = scale_roi_to_import(roi, (16, 16), map);
        assert_eq!((got.left, got.right), (0.0, 1.0));
        let [u0, _, u1, _] = sample_clamp_rect((16, 16), map);
        assert!((u0 - 0.5 / 16.0).abs() < 1e-6, "u0 {u0}");
        assert!((u1 - 15.5 / 16.0).abs() < 1e-6, "u1 {u1}");
    }

    /// An origin with NO extent is DROPPED by every helper -- the map is the
    /// identity, and the shift silently goes nowhere. This is why a leaf that
    /// reports a nonzero origin must report the widened extent alongside it
    /// (`GLProcessorST::cached_src_import_map` asserts the pairing): the
    /// failure mode is a wrongly-sampled frame on the one board that rebases,
    /// with nothing to see anywhere else.
    #[test]
    fn an_origin_without_an_extent_is_dropped_by_every_helper() {
        let map = ImportMap {
            extent: None,
            origin: (8, 0),
        };
        let r = roi();
        let got = scale_roi_to_import(r, (16, 16), map);
        assert_eq!(
            (got.left, got.top, got.right, got.bottom),
            (r.left, r.top, r.right, r.bottom)
        );
        assert_eq!(
            scale_uv_rect_to_import([0.1, 0.2, 0.3, 0.4], (16, 16), map),
            [0.1, 0.2, 0.3, 0.4]
        );
        assert_eq!(
            sample_clamp_rect((16, 16), map),
            sample_clamp_rect((16, 16), ImportMap::WHOLE)
        );
    }

    /// The float paths' origin-and-size rect: the origin shifts and the
    /// size stays trimmed inside the same limit.
    #[test]
    fn scale_uv_rect_to_import_offsets_by_the_origin() {
        let map = ImportMap {
            extent: Some((24, 16)),
            origin: (8, 0),
        };
        let got = scale_uv_rect_to_import([0.0, 0.0, 1.0, 1.0], (16, 16), map);
        assert!((got[0] - 8.0 / 24.0).abs() < 1e-6, "x {}", got[0]);
        assert!((got[2] - 16.0 / 24.0).abs() < 1e-6, "w {}", got[2]);
        assert!((got[1] - 0.0).abs() < 1e-6, "y {}", got[1]);
        assert!((got[3] - 1.0).abs() < 1e-6, "h {}", got[3]);
    }
}