edgefirst-image 0.28.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
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
#[allow(deprecated)]
mod cpu_tests {

    use crate::{
        CPUProcessor, Crop, Error, Flip, ImageProcessorTrait, Rect, Region, Result, Rotation,
    };
    use edgefirst_decoder::DetectBox;
    use edgefirst_tensor::{
        DType, PixelFormat, Tensor, TensorDyn, TensorMapTrait, TensorMemory, TensorTrait,
    };

    /// The buffer-geometry guards reject undersized/overflowing inputs with
    /// `InvalidShape` instead of panicking. Exercised directly on plain slices
    /// (the end-to-end malformed-tensor path needs an undersized `from_fd`/DMA
    /// buffer, which is Linux+DMA-gated).
    #[test]
    fn buffer_geometry_guards_reject_bad_input() {
        use super::super::{guard_plane, split_semi_planar_mut};

        // NV16 combined-plane height = 2*h ⇒ stride 4 × h 2 needs 16 bytes.
        let mut ok = [0u8; 16];
        let (y, uv) = split_semi_planar_mut(&mut ok, 4, 2, PixelFormat::Nv16).unwrap();
        assert_eq!((y.len(), uv.len()), (8, 8)); // luma split at stride*h = 8

        let mut small = [0u8; 12];
        assert!(matches!(
            split_semi_planar_mut(&mut small, 4, 2, PixelFormat::Nv16),
            Err(Error::InvalidShape(_))
        ));
        let mut tiny = [0u8; 1];
        assert!(matches!(
            split_semi_planar_mut(&mut tiny, usize::MAX, 4, PixelFormat::Nv16),
            Err(Error::InvalidShape(_))
        ));

        // guard_plane: ok, row_bytes>stride, buffer too small, overflow.
        assert!(guard_plane(16, 4, 2, 4, "t").is_ok());
        assert!(matches!(
            guard_plane(16, 4, 2, 5, "t"),
            Err(Error::InvalidShape(_))
        ));
        assert!(matches!(
            guard_plane(7, 4, 2, 4, "t"),
            Err(Error::InvalidShape(_))
        ));
        assert!(matches!(
            guard_plane(1, usize::MAX, 4, 1, "t"),
            Err(Error::InvalidShape(_))
        ));
    }

    macro_rules! function {
        () => {{
            fn f() {}
            fn type_name_of<T>(_: T) -> &'static str {
                std::any::type_name::<T>()
            }
            let name = type_name_of(f);

            // Find and cut the rest of the path
            match &name[..name.len() - 3].rfind(':') {
                Some(pos) => &name[pos + 1..name.len() - 3],
                None => &name[..name.len() - 3],
            }
        }};
    }

    fn compare_images_convert_to_grey(
        img1: &TensorDyn,
        img2: &TensorDyn,
        threshold: f64,
        name: &str,
    ) {
        assert_eq!(img1.height(), img2.height(), "Heights differ");
        assert_eq!(img1.width(), img2.width(), "Widths differ");

        // Compare raw bytes as greyscale strip
        let w = img1.width().unwrap() as u32;
        let data1 = img1.as_u8().unwrap().map().unwrap().to_vec();
        let data2 = img2.as_u8().unwrap().map().unwrap().to_vec();
        let h1 = (data1.len() as u32) / w;
        let h2 = (data2.len() as u32) / w;

        let image1 = image::GrayImage::from_vec(w, h1, data1).unwrap();
        let image2 = image::GrayImage::from_vec(w, h2, data2).unwrap();

        let similarity = image_compare::gray_similarity_structure(
            &image_compare::Algorithm::RootMeanSquared,
            &image1,
            &image2,
        )
        .expect("Image Comparison failed");
        if similarity.score < threshold {
            // image1.save(format!("{name}_1.png"));
            // image2.save(format!("{name}_2.png"));
            similarity
                .image
                .to_color_map()
                .save(format!("{name}.png"))
                .unwrap();
            panic!(
                "{name}: converted image and target image have similarity score too low: {} < {}",
                similarity.score, threshold
            )
        }
    }

    fn compare_images_convert_to_rgb(
        img1: &TensorDyn,
        img2: &TensorDyn,
        threshold: f64,
        name: &str,
    ) {
        assert_eq!(img1.height(), img2.height(), "Heights differ");
        assert_eq!(img1.width(), img2.width(), "Widths differ");

        // Try converting both to RGB for comparison. If conversion is not
        // supported (e.g. from PlanarRgb), fall back to raw byte comparison.
        let mut converter = CPUProcessor::default();
        let w = img1.width().unwrap();
        let h = img1.height().unwrap();

        let (img_rgb1, img_rgb2) = {
            let mut rgb1 = TensorDyn::image(
                w,
                h,
                PixelFormat::Rgb,
                DType::U8,
                mem(),
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            let mut rgb2 = TensorDyn::image(
                w,
                h,
                PixelFormat::Rgb,
                DType::U8,
                mem(),
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            let r1 = converter.convert(
                img1,
                &mut rgb1,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            );
            let r2 = converter.convert(
                img2,
                &mut rgb2,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            );
            if r1.is_err() || r2.is_err() {
                // Fallback: compare raw bytes as greyscale strip
                compare_images_convert_to_grey(img1, img2, threshold, name);
                return;
            }
            (rgb1, rgb2)
        };

        let image1 = image::RgbImage::from_vec(
            img_rgb1.width().unwrap() as u32,
            img_rgb1.height().unwrap() as u32,
            img_rgb1.as_u8().unwrap().map().unwrap().to_vec(),
        )
        .unwrap();

        let image2 = image::RgbImage::from_vec(
            img_rgb2.width().unwrap() as u32,
            img_rgb2.height().unwrap() as u32,
            img_rgb2.as_u8().unwrap().map().unwrap().to_vec(),
        )
        .unwrap();

        let similarity = image_compare::rgb_similarity_structure(
            &image_compare::Algorithm::RootMeanSquared,
            &image1,
            &image2,
        )
        .expect("Image Comparison failed");
        if similarity.score < threshold {
            // image1.save(format!("{name}_1.png"));
            // image2.save(format!("{name}_2.png"));
            similarity
                .image
                .to_color_map()
                .save(format!("{name}.png"))
                .unwrap();
            panic!(
                "{name}: converted image and target image have similarity score too low: {} < {}",
                similarity.score, threshold
            )
        }
    }

    /// CPU-processor tests operate on host memory: a tight `Mem` tensor whose
    /// row stride equals `width * bpp`. Pinning these tests to `Mem` keeps them
    /// deterministic across platforms — `None` auto-selects a pitch-padded DMA
    /// tensor on i.MX (DMA heap present), which shears the flat `copy_from_slice`
    /// fill and flat `as_slice()` assertions below. Padded-stride coverage lives
    /// in the dedicated `odd_dim_cpu` integration suite.
    fn mem() -> Option<TensorMemory> {
        Some(TensorMemory::Mem)
    }

    fn load_bytes_to_tensor(
        width: usize,
        height: usize,
        format: PixelFormat,
        memory: Option<TensorMemory>,
        bytes: &[u8],
    ) -> Result<TensorDyn, Error> {
        log::debug!("Current function is {}", function!());
        // Default to host memory (tight) so the flat fill matches the layout.
        let memory = memory.or_else(mem);
        let src = TensorDyn::image(
            width,
            height,
            format,
            DType::U8,
            memory,
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        src.as_u8().unwrap().map()?.as_mut_slice()[0..bytes.len()].copy_from_slice(bytes);
        Ok(src)
    }

    macro_rules! generate_conversion_tests {
        (
        $src_fmt:expr,  $src_file:expr, $dst_fmt:expr, $dst_file:expr
    ) => {{
            // Load source
            let src = load_bytes_to_tensor(
                1280,
                720,
                $src_fmt,
                None,
                &edgefirst_bench::testdata::read($src_file),
            )?;

            // Load destination reference
            let dst = load_bytes_to_tensor(
                1280,
                720,
                $dst_fmt,
                None,
                &edgefirst_bench::testdata::read($dst_file),
            )?;

            let mut converter = CPUProcessor::default();

            let mut converted = TensorDyn::image(
                src.width().unwrap(),
                src.height().unwrap(),
                dst.format().unwrap(),
                DType::U8,
                None,
                edgefirst_tensor::CpuAccess::ReadWrite,
            )?;

            converter.convert(
                &src,
                &mut converted,
                Rotation::None,
                Flip::None,
                Crop::default(),
            )?;

            // Post-WS1 the CPU YUV paths resolve per-source colorimetry against
            // the BT.709 fixtures: every colour↔colour conversion here now
            // measures ≥0.9946 (was the YUV-matrix delta that forced 0.95).
            // Tightened to 0.99.
            compare_images_convert_to_rgb(&dst, &converted, 0.99, function!());

            Ok(())
        }};
    }

    macro_rules! generate_conversion_tests_greyscale {
        (
        $src_fmt:expr,  $src_file:expr, $dst_fmt:expr, $dst_file:expr
    ) => {{
            // Load source
            let src = load_bytes_to_tensor(
                1280,
                720,
                $src_fmt,
                None,
                &edgefirst_bench::testdata::read($src_file),
            )?;

            // Load destination reference
            let dst = load_bytes_to_tensor(
                1280,
                720,
                $dst_fmt,
                None,
                &edgefirst_bench::testdata::read($dst_file),
            )?;

            let mut converter = CPUProcessor::default();

            let mut converted = TensorDyn::image(
                src.width().unwrap(),
                src.height().unwrap(),
                dst.format().unwrap(),
                DType::U8,
                None,
                edgefirst_tensor::CpuAccess::ReadWrite,
            )?;

            converter.convert(
                &src,
                &mut converted,
                Rotation::None,
                Flip::None,
                Crop::default(),
            )?;

            // Used whenever grey is on either side (compared in luma space). The
            // floor is grey→colour (~0.978): one luma channel replicated to RGB
            // inherently loses chroma vs a colour fixture — structural, not a
            // colorimetry gap. Grey→grey / colour→grey measure ≥0.997. Tightened
            // 0.95 → 0.97.
            compare_images_convert_to_grey(&dst, &converted, 0.97, function!());

            Ok(())
        }};
    }

    // let mut dsts = [yuyv, rgb, rgba, grey, nv16, planar_rgb, planar_rgba];

    #[test]
    fn test_cpu_yuyv_to_yuyv() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Yuyv,
            "camera720p.yuyv",
            PixelFormat::Yuyv,
            "camera720p.yuyv"
        )
    }

    #[test]
    fn test_cpu_yuyv_to_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Yuyv,
            "camera720p.yuyv",
            PixelFormat::Rgb,
            "camera720p.rgb"
        )
    }

    #[test]
    fn test_cpu_yuyv_to_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Yuyv,
            "camera720p.yuyv",
            PixelFormat::Rgba,
            "camera720p.rgba"
        )
    }

    #[test]
    fn test_cpu_yuyv_to_grey() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Yuyv,
            "camera720p.yuyv",
            PixelFormat::Grey,
            "camera720p.y800"
        )
    }

    #[test]
    fn test_cpu_yuyv_to_nv16() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Yuyv,
            "camera720p.yuyv",
            PixelFormat::Nv16,
            "camera720p.nv16"
        )
    }

    #[test]
    fn test_cpu_yuyv_to_planar_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Yuyv,
            "camera720p.yuyv",
            PixelFormat::PlanarRgb,
            "camera720p.8bps"
        )
    }

    #[test]
    fn test_cpu_yuyv_to_planar_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Yuyv,
            "camera720p.yuyv",
            PixelFormat::PlanarRgba,
            "camera720p.8bpa"
        )
    }

    #[test]
    fn test_cpu_rgb_to_yuyv() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgb,
            "camera720p.rgb",
            PixelFormat::Yuyv,
            "camera720p.yuyv"
        )
    }

    #[test]
    fn test_cpu_rgb_to_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgb,
            "camera720p.rgb",
            PixelFormat::Rgb,
            "camera720p.rgb"
        )
    }

    #[test]
    fn test_cpu_rgb_to_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgb,
            "camera720p.rgb",
            PixelFormat::Rgba,
            "camera720p.rgba"
        )
    }

    #[test]
    fn test_cpu_rgb_to_grey() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgb,
            "camera720p.rgb",
            PixelFormat::Grey,
            "camera720p.y800"
        )
    }

    #[test]
    fn test_cpu_rgb_to_nv16() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgb,
            "camera720p.rgb",
            PixelFormat::Nv16,
            "camera720p.nv16"
        )
    }

    #[test]
    fn test_cpu_rgb_to_planar_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgb,
            "camera720p.rgb",
            PixelFormat::PlanarRgb,
            "camera720p.8bps"
        )
    }

    #[test]
    fn test_cpu_rgb_to_planar_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgb,
            "camera720p.rgb",
            PixelFormat::PlanarRgba,
            "camera720p.8bpa"
        )
    }

    #[test]
    fn test_cpu_rgba_to_yuyv() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgba,
            "camera720p.rgba",
            PixelFormat::Yuyv,
            "camera720p.yuyv"
        )
    }

    #[test]
    fn test_cpu_rgba_to_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgba,
            "camera720p.rgba",
            PixelFormat::Rgb,
            "camera720p.rgb"
        )
    }

    #[test]
    fn test_cpu_rgba_to_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgba,
            "camera720p.rgba",
            PixelFormat::Rgba,
            "camera720p.rgba"
        )
    }

    #[test]
    fn test_cpu_rgba_to_grey() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgba,
            "camera720p.rgba",
            PixelFormat::Grey,
            "camera720p.y800"
        )
    }

    #[test]
    fn test_cpu_rgba_to_nv16() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgba,
            "camera720p.rgba",
            PixelFormat::Nv16,
            "camera720p.nv16"
        )
    }

    #[test]
    fn test_cpu_rgba_to_planar_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgba,
            "camera720p.rgba",
            PixelFormat::PlanarRgb,
            "camera720p.8bps"
        )
    }

    #[test]
    fn test_cpu_rgba_to_planar_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Rgba,
            "camera720p.rgba",
            PixelFormat::PlanarRgba,
            "camera720p.8bpa"
        )
    }

    #[test]
    fn test_cpu_nv12_to_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv12,
            "camera720p.nv12",
            PixelFormat::Rgb,
            "camera720p.rgb"
        )
    }

    #[test]
    fn test_cpu_nv12_to_yuyv() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv12,
            "camera720p.nv12",
            PixelFormat::Yuyv,
            "camera720p.yuyv"
        )
    }

    #[test]
    fn test_cpu_nv12_to_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv12,
            "camera720p.nv12",
            PixelFormat::Rgba,
            "camera720p.rgba"
        )
    }

    #[test]
    fn test_cpu_nv12_to_grey() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv12,
            "camera720p.nv12",
            PixelFormat::Grey,
            "camera720p.y800"
        )
    }

    #[test]
    fn test_cpu_nv12_to_nv16() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv12,
            "camera720p.nv12",
            PixelFormat::Nv16,
            "camera720p.nv16"
        )
    }

    #[test]
    fn test_cpu_nv12_to_planar_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv12,
            "camera720p.nv12",
            PixelFormat::PlanarRgb,
            "camera720p.8bps"
        )
    }

    #[test]
    fn test_cpu_nv12_to_planar_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv12,
            "camera720p.nv12",
            PixelFormat::PlanarRgba,
            "camera720p.8bpa"
        )
    }

    #[test]
    fn test_cpu_grey_to_yuyv() -> Result<()> {
        generate_conversion_tests_greyscale!(
            PixelFormat::Grey,
            "camera720p.y800",
            PixelFormat::Yuyv,
            "camera720p.yuyv"
        )
    }

    #[test]
    fn test_cpu_grey_to_rgb() -> Result<()> {
        generate_conversion_tests_greyscale!(
            PixelFormat::Grey,
            "camera720p.y800",
            PixelFormat::Rgb,
            "camera720p.rgb"
        )
    }

    #[test]
    fn test_cpu_grey_to_rgba() -> Result<()> {
        generate_conversion_tests_greyscale!(
            PixelFormat::Grey,
            "camera720p.y800",
            PixelFormat::Rgba,
            "camera720p.rgba"
        )
    }

    #[test]
    fn test_cpu_grey_to_grey() -> Result<()> {
        generate_conversion_tests_greyscale!(
            PixelFormat::Grey,
            "camera720p.y800",
            PixelFormat::Grey,
            "camera720p.y800"
        )
    }

    #[test]
    fn test_cpu_grey_to_nv16() -> Result<()> {
        generate_conversion_tests_greyscale!(
            PixelFormat::Grey,
            "camera720p.y800",
            PixelFormat::Nv16,
            "camera720p.nv16"
        )
    }

    #[test]
    fn test_cpu_grey_to_planar_rgb() -> Result<()> {
        generate_conversion_tests_greyscale!(
            PixelFormat::Grey,
            "camera720p.y800",
            PixelFormat::PlanarRgb,
            "camera720p.8bps"
        )
    }

    #[test]
    fn test_cpu_grey_to_planar_rgba() -> Result<()> {
        generate_conversion_tests_greyscale!(
            PixelFormat::Grey,
            "camera720p.y800",
            PixelFormat::PlanarRgba,
            "camera720p.8bpa"
        )
    }

    // ========================================================================
    // VYUY conversion tests
    // ========================================================================

    #[test]
    fn test_cpu_vyuy_to_grey() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Vyuy,
            "camera720p.vyuy",
            PixelFormat::Grey,
            "camera720p.y800"
        )
    }

    #[test]
    fn test_cpu_vyuy_to_planar_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Vyuy,
            "camera720p.vyuy",
            PixelFormat::PlanarRgb,
            "camera720p.8bps"
        )
    }

    #[test]
    fn test_cpu_vyuy_to_nv16() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Vyuy,
            "camera720p.vyuy",
            PixelFormat::Nv16,
            "camera720p.nv16"
        )
    }

    // ========================================================================
    // NV16 conversion tests
    // ========================================================================

    #[test]
    fn test_cpu_nv16_to_rgb() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv16,
            "camera720p.nv16",
            PixelFormat::Rgb,
            "camera720p.rgb"
        )
    }

    #[test]
    fn test_cpu_nv16_to_rgba() -> Result<()> {
        generate_conversion_tests!(
            PixelFormat::Nv16,
            "camera720p.nv16",
            PixelFormat::Rgba,
            "camera720p.rgba"
        )
    }

    #[test]
    fn test_cpu_nearest() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(2, 1, PixelFormat::Rgb, None, &[0, 0, 0, 255, 255, 255])?;

        let mut converter = CPUProcessor::new_nearest();

        let converted = TensorDyn::image(
            4,
            1,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        converter.convert(
            &src_dyn,
            &mut converted_dyn,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        assert_eq!(
            &converted_dyn.as_u8().unwrap().map()?.as_slice(),
            &[0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255]
        );

        Ok(())
    }

    #[test]
    fn test_cpu_rotate_cw() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(
            2,
            2,
            PixelFormat::Rgba,
            None,
            &[0, 0, 0, 255, 1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255],
        )?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        converter.convert(
            &src_dyn,
            &mut converted_dyn,
            Rotation::Clockwise90,
            Flip::None,
            Crop::default(),
        )?;

        let map = converted_dyn.as_u8().unwrap().map()?;
        assert_eq!(&map.as_slice()[0..4], &[2, 2, 2, 255]);
        assert_eq!(&map.as_slice()[12..16], &[0, 0, 0, 255]);
        assert_eq!(&map.as_slice()[48..52], &[3, 3, 3, 255]);
        assert_eq!(&map.as_slice()[60..64], &[1, 1, 1, 255]);

        Ok(())
    }

    #[test]
    fn test_cpu_rotate_ccw() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(
            2,
            2,
            PixelFormat::Rgba,
            None,
            &[0, 0, 0, 255, 1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255],
        )?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        converter.convert(
            &src_dyn,
            &mut converted_dyn,
            Rotation::CounterClockwise90,
            Flip::None,
            Crop::default(),
        )?;

        let map = converted_dyn.as_u8().unwrap().map()?;
        assert_eq!(&map.as_slice()[0..4], &[1, 1, 1, 255]);
        assert_eq!(&map.as_slice()[12..16], &[3, 3, 3, 255]);
        assert_eq!(&map.as_slice()[48..52], &[0, 0, 0, 255]);
        assert_eq!(&map.as_slice()[60..64], &[2, 2, 2, 255]);

        Ok(())
    }

    #[test]
    fn test_cpu_rotate_180() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(
            2,
            2,
            PixelFormat::Rgba,
            None,
            &[0, 0, 0, 255, 1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255],
        )?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        converter.convert(
            &src_dyn,
            &mut converted_dyn,
            Rotation::Rotate180,
            Flip::None,
            Crop::default(),
        )?;

        let map = converted_dyn.as_u8().unwrap().map()?;
        assert_eq!(&map.as_slice()[0..4], &[3, 3, 3, 255]);
        assert_eq!(&map.as_slice()[12..16], &[2, 2, 2, 255]);
        assert_eq!(&map.as_slice()[48..52], &[1, 1, 1, 255]);
        assert_eq!(&map.as_slice()[60..64], &[0, 0, 0, 255]);

        Ok(())
    }

    #[test]
    fn test_cpu_flip_v() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(
            2,
            2,
            PixelFormat::Rgba,
            None,
            &[0, 0, 0, 255, 1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255],
        )?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        converter.convert(
            &src_dyn,
            &mut converted_dyn,
            Rotation::None,
            Flip::Vertical,
            Crop::default(),
        )?;

        let map = converted_dyn.as_u8().unwrap().map()?;
        assert_eq!(&map.as_slice()[0..4], &[2, 2, 2, 255]);
        assert_eq!(&map.as_slice()[12..16], &[3, 3, 3, 255]);
        assert_eq!(&map.as_slice()[48..52], &[0, 0, 0, 255]);
        assert_eq!(&map.as_slice()[60..64], &[1, 1, 1, 255]);

        Ok(())
    }

    #[test]
    fn test_cpu_flip_h() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(
            2,
            2,
            PixelFormat::Rgba,
            None,
            &[0, 0, 0, 255, 1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255],
        )?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        converter.convert(
            &src_dyn,
            &mut converted_dyn,
            Rotation::None,
            Flip::Horizontal,
            Crop::default(),
        )?;

        let map = converted_dyn.as_u8().unwrap().map()?;
        assert_eq!(&map.as_slice()[0..4], &[1, 1, 1, 255]);
        assert_eq!(&map.as_slice()[12..16], &[0, 0, 0, 255]);
        assert_eq!(&map.as_slice()[48..52], &[3, 3, 3, 255]);
        assert_eq!(&map.as_slice()[60..64], &[2, 2, 2, 255]);

        Ok(())
    }

    #[test]
    fn test_cpu_src_crop() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(2, 2, PixelFormat::Grey, None, &[10, 20, 30, 40])?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            2,
            2,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        converter.convert(
            &src_dyn,
            &mut converted_dyn,
            Rotation::None,
            Flip::None,
            Crop::new().with_source(Some(Region::new(0, 0, 1, 2))),
        )?;

        assert_eq!(
            converted_dyn.as_u8().unwrap().map()?.as_slice(),
            &[10, 10, 10, 255, 13, 13, 13, 255, 30, 30, 30, 255, 33, 33, 33, 255]
        );
        Ok(())
    }

    #[test]
    fn test_cpu_dst_crop() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(2, 2, PixelFormat::Grey, None, &[2, 4, 6, 8])?;

        let mut converter = CPUProcessor::default();

        let converted = load_bytes_to_tensor(
            2,
            2,
            PixelFormat::Yuyv,
            None,
            &[200, 128, 200, 128, 200, 128, 200, 128],
        )?;
        let src_dyn = src;
        let converted_dyn = converted;

        // Destination crop is now a destination view: render into the top-row
        // sub-region; the bottom row keeps its pre-fill.
        let mut dst_view = converted_dyn.view(Region::new(0, 0, 2, 1))?;
        converter.convert(
            &src_dyn,
            &mut dst_view,
            Rotation::None,
            Flip::None,
            Crop::new(),
        )?;

        // The untagged 2x2 Grey source is below the HD threshold, so the
        // colorimetry heuristic resolves it to BT.601 limited range: grey luma
        // is mapped into the 16..235 limited range (219-step), so the
        // row-averaged grey [4, 6] yields Y = 19, 21. The second dst row is
        // outside the crop and keeps its pre-fill value.
        assert_eq!(
            converted_dyn.as_u8().unwrap().map()?.as_slice(),
            &[19, 128, 21, 128, 200, 128, 200, 128]
        );
        Ok(())
    }

    #[test]
    fn test_cpu_fill_rgba() -> Result<()> {
        // Load source
        let src = load_bytes_to_tensor(1, 1, PixelFormat::Rgba, None, &[3, 3, 3, 255])?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            2,
            2,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        // Destination fill + sub-region render: fill the whole dst with the pad
        // colour, then render the source into the sub-region view.
        let pad = load_bytes_to_tensor(1, 1, PixelFormat::Rgba, None, &[255, 0, 0, 255])?;
        converter.convert(
            &pad,
            &mut converted_dyn,
            Rotation::None,
            Flip::None,
            Crop::new(),
        )?;
        let mut dst_view = converted_dyn.view(Region::new(1, 1, 1, 1))?;
        converter.convert(
            &src_dyn,
            &mut dst_view,
            Rotation::None,
            Flip::None,
            Crop::new(),
        )?;

        assert_eq!(
            converted_dyn.as_u8().unwrap().map()?.as_slice(),
            &[255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 3, 3, 3, 255]
        );
        Ok(())
    }

    #[test]
    fn test_cpu_fill_yuyv() -> Result<()> {
        // Load source
        let src =
            load_bytes_to_tensor(2, 1, PixelFormat::Rgba, None, &[3, 3, 3, 255, 3, 3, 3, 255])?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            2,
            3,
            PixelFormat::Yuyv,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        let pad = load_bytes_to_tensor(1, 1, PixelFormat::Rgba, None, &[255, 0, 0, 255])?;
        converter.convert(
            &pad,
            &mut converted_dyn,
            Rotation::None,
            Flip::None,
            Crop::new(),
        )?;
        let mut dst_view = converted_dyn.view(Region::new(0, 1, 2, 1))?;
        converter.convert(
            &src_dyn,
            &mut dst_view,
            Rotation::None,
            Flip::None,
            Crop::new(),
        )?;

        // 2x3 YUYV is below the HD threshold, so the colorimetry heuristic
        // resolves it to BT.601 limited (previously a BT.709 hardcode). Red
        // (255,0,0) → Y=81, U=90, V=240 under BT.601 limited.
        assert_eq!(
            converted_dyn.as_u8().unwrap().map()?.as_slice(),
            &[81, 90, 81, 240, 19, 128, 19, 128, 81, 90, 81, 240]
        );
        Ok(())
    }

    #[test]
    fn test_cpu_fill_grey() -> Result<()> {
        // Load source
        let src =
            load_bytes_to_tensor(2, 1, PixelFormat::Rgba, None, &[3, 3, 3, 255, 3, 3, 3, 255])?;

        let mut converter = CPUProcessor::default();

        let converted = TensorDyn::image(
            2,
            3,
            PixelFormat::Grey,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let src_dyn = src;
        let mut converted_dyn = converted;

        let pad = load_bytes_to_tensor(1, 1, PixelFormat::Rgba, None, &[200, 200, 200, 255])?;
        converter.convert(
            &pad,
            &mut converted_dyn,
            Rotation::None,
            Flip::None,
            Crop::new(),
        )?;
        let mut dst_view = converted_dyn.view(Region::new(0, 1, 2, 1))?;
        converter.convert(
            &src_dyn,
            &mut dst_view,
            Rotation::None,
            Flip::None,
            Crop::new(),
        )?;

        assert_eq!(
            converted_dyn.as_u8().unwrap().map()?.as_slice(),
            &[200, 200, 3, 3, 200, 200]
        );
        Ok(())
    }

    #[test]
    fn test_segmentation() {
        use edgefirst_decoder::Segmentation;
        use ndarray::Array3;

        let image = crate::load_image_test_helper(
            &edgefirst_bench::testdata::read("giraffe.jpg"),
            Some(PixelFormat::Rgba),
            None,
        )
        .unwrap();
        let mut image_dyn = image;

        let mut segmentation = Array3::from_shape_vec(
            (2, 160, 160),
            edgefirst_bench::testdata::read("modelpack_seg_2x160x160.bin").to_vec(),
        )
        .unwrap();
        segmentation.swap_axes(0, 1);
        segmentation.swap_axes(1, 2);
        let segmentation = segmentation.as_standard_layout().to_owned();

        let seg = Segmentation {
            segmentation,
            xmin: 0.0,
            ymin: 0.0,
            xmax: 1.0,
            ymax: 1.0,
        };

        let mut renderer = CPUProcessor::new();
        renderer
            .draw_decoded_masks(&mut image_dyn, &[], &[seg], Default::default())
            .unwrap();

        let image = {
            let mut __t = image_dyn.into_u8().unwrap();
            __t.set_format(PixelFormat::Rgba).unwrap();
            TensorDyn::from(__t)
        };
        crate::save_jpeg(&image, "test_segmentation.jpg", 80).unwrap();
    }

    #[test]
    fn test_segmentation_yolo() {
        use edgefirst_decoder::Segmentation;
        use ndarray::Array3;

        // draw_decoded_masks fully writes dst: we must pass the camera
        // frame as a background via MaskOverlay, not as the dst canvas.
        let bg = crate::load_image_test_helper(
            &edgefirst_bench::testdata::read("giraffe.jpg"),
            Some(PixelFormat::Rgba),
            None,
        )
        .unwrap();
        let mut dst = TensorDyn::image(
            bg.width().unwrap(),
            bg.height().unwrap(),
            PixelFormat::Rgba,
            DType::U8,
            None,
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();

        let segmentation = Array3::from_shape_vec(
            (76, 55, 1),
            edgefirst_bench::testdata::read("yolov8_seg_crop_76x55.bin").to_vec(),
        )
        .unwrap();

        let detect = DetectBox {
            bbox: [0.59375, 0.25, 0.9375, 0.725].into(),
            score: 0.99,
            label: 1,
        };

        let seg = Segmentation {
            segmentation,
            xmin: 0.59375,
            ymin: 0.25,
            xmax: 0.9375,
            ymax: 0.725,
        };

        let mut renderer = CPUProcessor::new();
        renderer
            .set_class_colors(&[[255, 255, 0, 233], [128, 128, 255, 100]])
            .unwrap();
        assert_eq!(renderer.colors[1], [128, 128, 255, 100]);
        renderer
            .draw_decoded_masks(
                &mut dst,
                &[detect],
                &[seg],
                crate::MaskOverlay::new().with_background(&bg),
            )
            .unwrap();
        let image = {
            let mut __t = dst.into_u8().unwrap();
            __t.set_format(PixelFormat::Rgba).unwrap();
            TensorDyn::from(__t)
        };
        let expected = crate::load_image_test_helper(
            &edgefirst_bench::testdata::read("output_render_cpu.jpg"),
            Some(PixelFormat::Rgba),
            None,
        )
        .unwrap();
        // Threshold 0.97 (was 0.99): the codec now decodes colour JPEGs to
        // their native NV12 layout, so the `giraffe.jpg` background routes
        // through an NV12 → RGBA conversion (chroma subsampling) before the
        // mask is composited. The `output_render_cpu.jpg` golden was captured
        // from the old direct-RGB JPEG decode, so the NV12-sourced background
        // differs slightly. This mirrors the GL counterpart's 0.97 tolerance.
        compare_images_convert_to_rgb(&image, &expected, 0.97, function!());
    }

    // =========================================================================
    // Generic Conversion Tests
    // (These tests use TensorDyn for all image representations)
    // =========================================================================

    #[test]
    fn test_convert_rgb_to_planar_rgb_generic() {
        // Create PixelFormat::Rgb source image
        let src = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut map = src.as_u8().unwrap().map().unwrap();
            let data = map.as_mut_slice();
            // Fill with pattern: pixel 0 = [10, 20, 30], pixel 1 = [40, 50, 60], etc.
            for i in 0..16 {
                data[i * 3] = (i * 10) as u8;
                data[i * 3 + 1] = (i * 10 + 1) as u8;
                data[i * 3 + 2] = (i * 10 + 2) as u8;
            }
        }

        // Create planar PixelFormat::Rgb destination using TensorDyn
        let mut dst = TensorDyn::image(
            4,
            4,
            PixelFormat::PlanarRgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();

        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        // Verify the conversion - check first few pixels of each plane
        let map = dst.as_u8().unwrap().map().unwrap();
        let data = map.as_slice();

        // R plane starts at 0, G at 16, B at 32
        assert_eq!(data[0], 0); // R of pixel 0
        assert_eq!(data[16], 1); // G of pixel 0
        assert_eq!(data[32], 2); // B of pixel 0

        assert_eq!(data[1], 10); // R of pixel 1
        assert_eq!(data[17], 11); // G of pixel 1
        assert_eq!(data[33], 12); // B of pixel 1
    }

    #[test]
    fn test_convert_rgba_to_planar_rgb_generic() {
        // Create PixelFormat::Rgba source image
        let src = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut map = src.as_u8().unwrap().map().unwrap();
            let data = map.as_mut_slice();
            // Fill with pattern
            for i in 0..16 {
                data[i * 4] = (i * 10) as u8; // R
                data[i * 4 + 1] = (i * 10 + 1) as u8; // G
                data[i * 4 + 2] = (i * 10 + 2) as u8; // B
                data[i * 4 + 3] = 255; // A (ignored)
            }
        }

        // Create planar PixelFormat::Rgb destination
        let mut dst = TensorDyn::image(
            4,
            4,
            PixelFormat::PlanarRgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();

        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        // Verify the conversion
        let map = dst.as_u8().unwrap().map().unwrap();
        let data = map.as_slice();

        assert_eq!(data[0], 0); // R of pixel 0
        assert_eq!(data[16], 1); // G of pixel 0
        assert_eq!(data[32], 2); // B of pixel 0
    }

    #[test]
    fn test_copy_image_generic_same_format() {
        // Create source image with data
        let src = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut map = src.as_u8().unwrap().map().unwrap();
            let data = map.as_mut_slice();
            for (i, byte) in data.iter_mut().enumerate() {
                *byte = (i % 256) as u8;
            }
        }

        // Create destination tensor
        let mut dst = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();

        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        // Verify data was copied
        let src_map = src.as_u8().unwrap().map().unwrap();
        let dst_map = dst.as_u8().unwrap().map().unwrap();
        assert_eq!(src_map.as_slice(), dst_map.as_slice());
    }

    #[test]
    fn test_convert_unsupported_format_pair() {
        // Try NV12 -> NV12 (not supported by CPU converter)
        let src = TensorDyn::image(
            8,
            8,
            PixelFormat::Nv12,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        let mut dst = TensorDyn::image(
            8,
            8,
            PixelFormat::Nv12,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();

        let result = {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
        };
        assert!(result.is_err());
        assert!(matches!(result, Err(Error::NotSupported(_))));
    }

    #[test]
    fn test_fill_image_outside_crop_generic_rgba() {
        let mut dst = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        // Initialize to zeros
        dst.as_u8().unwrap().map().unwrap().as_mut_slice().fill(0);

        // Fill outside a 2x2 crop in the center with red
        let crop = Rect::new(1, 1, 2, 2);
        CPUProcessor::fill_image_outside_crop_u8(dst.as_u8_mut().unwrap(), [255, 0, 0, 255], crop)
            .unwrap();

        let map = dst.as_u8().unwrap().map().unwrap();
        let data = map.as_slice();

        // Top-left corner should be filled (red)
        assert_eq!(&data[0..4], &[255, 0, 0, 255]);

        // Center pixel (1,1) should still be zero (inside crop)
        // row=1, col=1, width=4, bytes_per_pixel=4 -> offset = (1*4 + 1) * 4 = 20
        let center_offset = 20;
        assert_eq!(&data[center_offset..center_offset + 4], &[0, 0, 0, 0]);
    }

    #[test]
    fn test_fill_image_outside_crop_generic_rgb() {
        let mut dst = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        dst.as_u8().unwrap().map().unwrap().as_mut_slice().fill(0);

        let crop = Rect::new(1, 1, 2, 2);
        CPUProcessor::fill_image_outside_crop_u8(dst.as_u8_mut().unwrap(), [0, 255, 0, 255], crop)
            .unwrap();

        let map = dst.as_u8().unwrap().map().unwrap();
        let data = map.as_slice();

        // Top-left corner should be green
        assert_eq!(&data[0..3], &[0, 255, 0]);

        // Center pixel (1,1): row=1, col=1, width=4, bytes=3 -> offset = (1*4 + 1) * 3
        // = 15
        let center_offset = 15;
        assert_eq!(&data[center_offset..center_offset + 3], &[0, 0, 0]);
    }

    #[test]
    fn test_fill_image_outside_crop_generic_planar_rgb() {
        let mut dst = TensorDyn::image(
            4,
            4,
            PixelFormat::PlanarRgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        dst.as_u8().unwrap().map().unwrap().as_mut_slice().fill(0);

        let crop = Rect::new(1, 1, 2, 2);
        CPUProcessor::fill_image_outside_crop_u8(
            dst.as_u8_mut().unwrap(),
            [128, 64, 32, 255],
            crop,
        )
        .unwrap();

        let map = dst.as_u8().unwrap().map().unwrap();
        let data = map.as_slice();

        // For planar: R plane is [0..16], G plane is [16..32], B plane is [32..48]
        // Top-left pixel (0,0) should have R=128, G=64, B=32
        assert_eq!(data[0], 128); // R plane, pixel 0
        assert_eq!(data[16], 64); // G plane, pixel 0
        assert_eq!(data[32], 32); // B plane, pixel 0

        // Center pixel (1,1): row=1, col=1, width=4 -> index = 1*4 + 1 = 5
        let center_idx = 5;
        assert_eq!(data[center_idx], 0); // R
        assert_eq!(data[16 + center_idx], 0); // G
        assert_eq!(data[32 + center_idx], 0); // B
    }

    /// The semi-planar letterbox fill splits luma from chroma at
    /// `row_stride * height` and advances both planes by the stride. Nv16
    /// tensors *always* carry a 64-byte-aligned stride wider than the logical
    /// width, so this is the normal case, not an edge case — the plane boundary
    /// and every row offset move with the pitch.
    #[test]
    fn test_fill_image_outside_crop_nv16_strided() {
        const SENTINEL: u8 = 0x11;
        let (w, h) = (96usize, 8usize);

        let mut dst = TensorDyn::image(
            w,
            h,
            PixelFormat::Nv16,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();

        let stride = dst.effective_row_stride().unwrap();
        assert!(
            stride > w,
            "test needs a padded Nv16 destination to be meaningful (stride={stride}, w={w})"
        );
        {
            let t = dst.as_u8_mut().unwrap();
            let mut map = t.map_mut().unwrap();
            assert_eq!(
                map.as_slice().len(),
                stride * h * 2,
                "Nv16 maps luma + full-height chroma at the padded pitch"
            );
            map.as_mut_slice().fill(SENTINEL);
        }

        // The fill colour resolved exactly as `fill_image_outside_crop_u8` does.
        let rgba = [255u8, 0, 0, 255];
        let (y_fill, u_fill, v_fill) = {
            let t = dst.as_u8().unwrap();
            let cm = crate::colorimetry::resolve_colorimetry(t.colorimetry(), t.height());
            let cp = crate::cpu::ColorParams {
                matrix: crate::colorimetry::yuv_matrix(cm.encoding.unwrap()),
                range: crate::colorimetry::yuv_range(cm.range.unwrap()),
                encoding: cm.encoding.unwrap(),
                range_kind: cm.range.unwrap(),
                src_full_range: cm.range == Some(edgefirst_tensor::ColorRange::Full),
                dst_full_range: cm.range == Some(edgefirst_tensor::ColorRange::Full),
            };
            let yuyv = CPUProcessor::rgba_to_yuyv(rgba, cp);
            (yuyv[0], yuyv[1], yuyv[3])
        };
        assert_ne!(y_fill, SENTINEL, "fill luma must differ from the sentinel");

        // Content occupies columns 32..64 of rows 2..6; everything else is border.
        let crop = Rect::new(32, 2, 32, 4);
        CPUProcessor::fill_image_outside_crop_u8(dst.as_u8_mut().unwrap(), rgba, crop).unwrap();

        let t = dst.as_u8().unwrap();
        let map = t.map().unwrap();
        let data = map.as_slice();
        let (luma, chroma) = data.split_at(stride * h);

        for y in 0..h {
            let border_row = y < crop.top || y >= crop.top + crop.height;
            for x in 0..w {
                let inside = !border_row && x >= crop.left && x < crop.left + crop.width;
                let want = if inside { SENTINEL } else { y_fill };
                assert_eq!(
                    luma[y * stride + x],
                    want,
                    "luma ({x},{y}): expected {want:#04x} (inside_crop={inside})"
                );
            }
            // Row padding past the logical width must never be filled.
            for x in w..stride {
                assert_eq!(
                    luma[y * stride + x],
                    SENTINEL,
                    "luma row {y} padding byte {x} was filled"
                );
            }
        }

        // Nv16 chroma is full height with one (Cb,Cr) pair per two luma columns,
        // so the border maps to half-width columns at the SAME pitch.
        for y in 0..h {
            let border_row = y < crop.top || y >= crop.top + crop.height;
            for cx in 0..w / 2 {
                let inside =
                    !border_row && cx >= crop.left / 2 && cx < (crop.left + crop.width) / 2;
                let (want_u, want_v) = if inside {
                    (SENTINEL, SENTINEL)
                } else {
                    (u_fill, v_fill)
                };
                let off = y * stride + cx * 2;
                assert_eq!(
                    (chroma[off], chroma[off + 1]),
                    (want_u, want_v),
                    "chroma pair {cx} of row {y} (inside_crop={inside})"
                );
            }
            for x in w..stride {
                assert_eq!(
                    chroma[y * stride + x],
                    SENTINEL,
                    "chroma row {y} padding byte {x} was filled"
                );
            }
        }
    }

    #[test]
    fn test_fill_image_outside_crop_yuyv_odd_width() {
        // The Yuyv fill runs the generic filler over `w / 2` four-byte
        // macropixels, which for an odd width structurally misses the
        // trailing unpaired pixel's `[Y, U]` bytes on every row — the same
        // trailing-pixel class the odd-width YUYV encoders fixed. Those two
        // bytes must be filled whenever that pixel lies outside the crop.
        const SENTINEL: u8 = 0xAB;
        let (w, h) = (5usize, 4usize);

        let mut dst = TensorDyn::image(
            w,
            h,
            PixelFormat::Yuyv,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        let stride = dst.effective_row_stride().unwrap();
        dst.as_u8()
            .unwrap()
            .map()
            .unwrap()
            .as_mut_slice()
            .fill(SENTINEL);

        // The fill colour resolved exactly as `fill_image_outside_crop_u8` does.
        let rgba = [255u8, 0, 0, 255];
        let yuyv = {
            let t = dst.as_u8().unwrap();
            let cm = crate::colorimetry::resolve_colorimetry(t.colorimetry(), t.height());
            let cp = crate::cpu::ColorParams {
                matrix: crate::colorimetry::yuv_matrix(cm.encoding.unwrap()),
                range: crate::colorimetry::yuv_range(cm.range.unwrap()),
                encoding: cm.encoding.unwrap(),
                range_kind: cm.range.unwrap(),
                src_full_range: cm.range == Some(edgefirst_tensor::ColorRange::Full),
                dst_full_range: cm.range == Some(edgefirst_tensor::ColorRange::Full),
            };
            CPUProcessor::rgba_to_yuyv(rgba, cp)
        };

        // Crop covers rows 1..3, columns 0..4 — the trailing pixel (x = 4)
        // is outside the crop on every row.
        let crop = Rect::new(0, 1, 4, 2);
        CPUProcessor::fill_image_outside_crop_u8(dst.as_u8_mut().unwrap(), rgba, crop).unwrap();

        let t = dst.as_u8().unwrap();
        let map = t.map().unwrap();
        let data = map.as_slice();
        for y in 0..h {
            // The trailing unpaired pixel's [Y, U] — never covered by the
            // macropixel fill at w/2 = 2 macropixels.
            let tail = y * stride + (w - 1) * 2;
            assert_eq!(
                (data[tail], data[tail + 1]),
                (yuyv[0], yuyv[1]),
                "row {y}: trailing odd-width pixel's [Y, U] must be filled"
            );
            // Crop interior stays untouched.
            let border_row = y < crop.top || y >= crop.top + crop.height;
            if !border_row {
                let inside = y * stride;
                assert_eq!(
                    (data[inside], data[inside + 1]),
                    (SENTINEL, SENTINEL),
                    "row {y}: crop-interior bytes were overwritten"
                );
            }
        }
    }

    #[test]
    fn test_convert_rgba_to_bgra() {
        use edgefirst_tensor::TensorMemory;
        // 2x1 image: pixel0 = [R=10, G=20, B=30, A=255], pixel1 = [R=40, G=50, B=60, A=128]
        let src = TensorDyn::image(
            2,
            1,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut map = src.as_u8().unwrap().map().unwrap();
            let buf = map.as_mut_slice();
            buf[0..4].copy_from_slice(&[10, 20, 30, 255]);
            buf[4..8].copy_from_slice(&[40, 50, 60, 128]);
        }
        let mut dst = TensorDyn::image(
            2,
            1,
            PixelFormat::Bgra,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }
        let map = dst.as_u8().unwrap().map().unwrap();
        let buf = map.as_slice();
        // PixelFormat::Bgra byte order: [B, G, R, A]
        assert_eq!(&buf[0..4], &[30, 20, 10, 255]);
        assert_eq!(&buf[4..8], &[60, 50, 40, 128]);
    }

    #[test]
    fn test_convert_rgb_to_bgra() {
        // Convert PixelFormat::Rgb→PixelFormat::Rgba and PixelFormat::Rgb→PixelFormat::Bgra, verify R↔B swap matches
        let src = TensorDyn::image(
            2,
            1,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut map = src.as_u8().unwrap().map().unwrap();
            let buf = map.as_mut_slice();
            buf[0..3].copy_from_slice(&[100, 150, 200]);
            buf[3..6].copy_from_slice(&[50, 75, 25]);
        }
        let mut rgba_dst = TensorDyn::image(
            2,
            1,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut rgba_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        let mut bgra_dst = TensorDyn::image(
            2,
            1,
            PixelFormat::Bgra,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut bgra_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        assert_bgra_matches_rgba(&bgra_dst, &rgba_dst);

        // Also verify the B,G,R channels are correct (alpha may vary)
        let map = bgra_dst.as_u8().unwrap().map().unwrap();
        let buf = map.as_slice();
        assert_eq!(buf[0], 200, "pixel 0 B");
        assert_eq!(buf[1], 150, "pixel 0 G");
        assert_eq!(buf[2], 100, "pixel 0 R");
        assert_eq!(buf[4], 25, "pixel 1 B");
        assert_eq!(buf[5], 75, "pixel 1 G");
        assert_eq!(buf[6], 50, "pixel 1 R");
    }

    #[test]
    fn test_convert_grey_to_bgra() {
        // 2x1 greyscale image
        let src = TensorDyn::image(
            2,
            1,
            PixelFormat::Grey,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut map = src.as_u8().unwrap().map().unwrap();
            let buf = map.as_mut_slice();
            buf[0] = 128;
            buf[1] = 64;
        }
        let mut dst = TensorDyn::image(
            2,
            1,
            PixelFormat::Bgra,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }
        let map = dst.as_u8().unwrap().map().unwrap();
        let buf = map.as_slice();
        // Grey→PixelFormat::Bgra: all channels same value, A=255; R↔B swap is no-op on grey
        assert_eq!(&buf[0..4], &[128, 128, 128, 255]);
        assert_eq!(&buf[4..8], &[64, 64, 64, 255]);
    }

    #[test]
    fn test_convert_bgra_to_bgra_copy() {
        // Verify PixelFormat::Bgra→PixelFormat::Bgra is a straight copy
        let src = TensorDyn::image(
            2,
            1,
            PixelFormat::Bgra,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut map = src.as_u8().unwrap().map().unwrap();
            let buf = map.as_mut_slice();
            buf[0..4].copy_from_slice(&[10, 20, 30, 255]);
            buf[4..8].copy_from_slice(&[40, 50, 60, 128]);
        }
        let mut dst = TensorDyn::image(
            2,
            1,
            PixelFormat::Bgra,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }
        let map = dst.as_u8().unwrap().map().unwrap();
        let buf = map.as_slice();
        assert_eq!(&buf[0..4], &[10, 20, 30, 255]);
        assert_eq!(&buf[4..8], &[40, 50, 60, 128]);
    }

    /// Helper: compare PixelFormat::Bgra output against PixelFormat::Rgba output by verifying R↔B swap.
    /// Since CPU PixelFormat::Bgra conversion is PixelFormat::Rgba conversion + R↔B swizzle, the results
    /// must be byte-exact after accounting for the channel swap.
    fn assert_bgra_matches_rgba(bgra: &TensorDyn, rgba: &TensorDyn) {
        assert_eq!(bgra.format().unwrap(), PixelFormat::Bgra);
        assert_eq!(rgba.format().unwrap(), PixelFormat::Rgba);
        assert_eq!(bgra.width(), rgba.width());
        assert_eq!(bgra.height(), rgba.height());

        let bgra_map = bgra.as_u8().unwrap().map().unwrap();
        let rgba_map = rgba.as_u8().unwrap().map().unwrap();
        let bgra_buf = bgra_map.as_slice();
        let rgba_buf = rgba_map.as_slice();

        assert_eq!(bgra_buf.len(), rgba_buf.len());
        for (i, (bc, rc)) in bgra_buf
            .chunks_exact(4)
            .zip(rgba_buf.chunks_exact(4))
            .enumerate()
        {
            assert_eq!(bc[0], rc[2], "pixel {i}: B(bgra) != B(rgba)");
            assert_eq!(bc[1], rc[1], "pixel {i}: G mismatch");
            assert_eq!(bc[2], rc[0], "pixel {i}: R(bgra) != R(rgba)");
            assert_eq!(bc[3], rc[3], "pixel {i}: A mismatch");
        }
    }

    #[test]
    fn test_convert_nv12_to_bgra() {
        let src = load_bytes_to_tensor(
            1280,
            720,
            PixelFormat::Nv12,
            None,
            &edgefirst_bench::testdata::read("camera720p.nv12"),
        )
        .unwrap();

        // Convert to both PixelFormat::Rgba and PixelFormat::Bgra, then compare
        let mut rgba_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut rgba_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        let mut bgra_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Bgra,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut bgra_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        assert_bgra_matches_rgba(&bgra_dst, &rgba_dst);
    }

    #[test]
    fn test_convert_yuyv_to_bgra() {
        let src = load_bytes_to_tensor(
            1280,
            720,
            PixelFormat::Yuyv,
            None,
            &edgefirst_bench::testdata::read("camera720p.yuyv"),
        )
        .unwrap();

        let mut rgba_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut rgba_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        let mut bgra_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Bgra,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut bgra_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        assert_bgra_matches_rgba(&bgra_dst, &rgba_dst);
    }

    #[test]
    fn test_convert_vyuy_to_bgra() {
        let src = load_bytes_to_tensor(
            1280,
            720,
            PixelFormat::Vyuy,
            None,
            &edgefirst_bench::testdata::read("camera720p.vyuy"),
        )
        .unwrap();

        let mut rgba_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut rgba_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        let mut bgra_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Bgra,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut bgra_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        assert_bgra_matches_rgba(&bgra_dst, &rgba_dst);
    }

    #[test]
    fn test_convert_nv16_to_bgra() {
        let src = load_bytes_to_tensor(
            1280,
            720,
            PixelFormat::Nv16,
            None,
            &edgefirst_bench::testdata::read("camera720p.nv16"),
        )
        .unwrap();

        let mut rgba_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut rgba_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        let mut bgra_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Bgra,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut __cv = CPUProcessor::default();
            __cv.convert(
                &src,
                &mut bgra_dst,
                crate::Rotation::None,
                crate::Flip::None,
                crate::Crop::default(),
            )
            .unwrap();
        }

        assert_bgra_matches_rgba(&bgra_dst, &rgba_dst);
    }

    // ========================================================================
    // Tests for materialize_segmentations
    // ========================================================================

    fn make_proto_data(
        proto_h: usize,
        proto_w: usize,
        num_protos: usize,
        coefficients: Vec<Vec<f32>>,
    ) -> crate::ProtoData {
        make_proto_data_with_values(
            proto_h,
            proto_w,
            num_protos,
            vec![0.0_f32; proto_h * proto_w * num_protos],
            coefficients,
        )
    }

    fn make_proto_data_with_values(
        proto_h: usize,
        proto_w: usize,
        num_protos: usize,
        proto_values: Vec<f32>,
        coefficients: Vec<Vec<f32>>,
    ) -> crate::ProtoData {
        use edgefirst_tensor::{Tensor, TensorDyn};
        assert_eq!(proto_values.len(), proto_h * proto_w * num_protos);
        let n = coefficients.len();
        let row_len = coefficients.first().map(|r| r.len()).unwrap_or(num_protos);
        let mut flat = Vec::with_capacity(n * row_len);
        for row in &coefficients {
            flat.extend_from_slice(row);
        }
        let coeff_t = Tensor::<f32>::from_slice(&flat, &[n, row_len]).unwrap();
        let protos_t =
            Tensor::<f32>::from_slice(&proto_values, &[proto_h, proto_w, num_protos]).unwrap();
        crate::ProtoData {
            mask_coefficients: TensorDyn::F32(coeff_t),
            protos: TensorDyn::F32(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nhwc,
        }
    }

    fn make_detect_box(xmin: f32, ymin: f32, xmax: f32, ymax: f32) -> crate::DetectBox {
        crate::DetectBox {
            bbox: edgefirst_decoder::BoundingBox {
                xmin,
                ymin,
                xmax,
                ymax,
            },
            score: 0.9,
            label: 0,
        }
    }

    #[test]
    fn test_materialize_empty_detections() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![vec![1.0; 4]]);
        let result = cpu.materialize_segmentations(&[], &proto_data, None);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_materialize_empty_proto_data() {
        // ProtoData from a detection-only model — caller passes no detections
        // to the materializer (detection-only models have a ProtoData stub
        // with an empty coefficient tensor). Materialization must not panic
        // and must return an empty segmentation list.
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![]);
        let result = cpu.materialize_segmentations(&[], &proto_data, None);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_materialize_single_detection() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![vec![0.5; 4]]);
        let det = [make_detect_box(0.1, 0.1, 0.5, 0.5)];
        let result = cpu.materialize_segmentations(&det, &proto_data, None);
        assert!(result.is_ok());
        let segs = result.unwrap();
        assert_eq!(segs.len(), 1);
        // Segmentation should have shape (H, W, 1) with non-zero spatial dims
        assert!(segs[0].segmentation.shape()[0] > 0);
        assert!(segs[0].segmentation.shape()[1] > 0);
        assert_eq!(segs[0].segmentation.shape()[2], 1);
    }

    #[test]
    fn test_materialize_bbox_edge_one() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![vec![0.5; 4]]);
        let det = [make_detect_box(0.5, 0.5, 1.0, 1.0)];
        let result = cpu.materialize_segmentations(&det, &proto_data, None);
        assert!(
            result.is_ok(),
            "bbox at exact boundary (1.0) should not panic"
        );
        let segs = result.unwrap();
        assert_eq!(segs.len(), 1);
    }

    #[test]
    fn test_materialize_bbox_negative_clamp() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![vec![0.5; 4]]);
        let det = [make_detect_box(-0.5, -0.5, 0.5, 0.5)];
        let result = cpu.materialize_segmentations(&det, &proto_data, None);
        assert!(
            result.is_ok(),
            "negative coordinates should be clamped to 0"
        );
        let segs = result.unwrap();
        assert_eq!(segs.len(), 1);
        // xmin should be clamped to 0.0
        assert!((segs[0].xmin - 0.0).abs() < 0.01);
        assert!((segs[0].ymin - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_materialize_invalid_coeff_shape() {
        let cpu = CPUProcessor::new();
        // Proto has 4 channels but coefficients have 6 elements — mismatch
        let proto_data = make_proto_data(8, 8, 4, vec![vec![0.5; 6]]);
        let det = [make_detect_box(0.1, 0.1, 0.5, 0.5)];
        let result = cpu.materialize_segmentations(&det, &proto_data, None);
        assert!(
            result.is_err(),
            "mismatched coeff count vs proto channels should error"
        );
        let err = result.unwrap_err();
        assert!(
            matches!(&err, crate::Error::InvalidShape(s) if s.contains("mask_coefficients")),
            "error should mention coefficient shape: {err:?}"
        );
    }

    #[test]
    fn test_materialize_multiple_detections() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![vec![0.5; 4], vec![0.3; 4], vec![0.1; 4]]);
        let det = [
            make_detect_box(0.0, 0.0, 0.5, 0.5),
            make_detect_box(0.5, 0.0, 1.0, 0.5),
            make_detect_box(0.0, 0.5, 0.5, 1.0),
        ];
        let result = cpu.materialize_segmentations(&det, &proto_data, None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 3);
    }

    #[test]
    fn test_materialize_zero_area_bbox() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![vec![0.5; 4]]);
        // xmin == xmax → zero-width bbox
        let det = [make_detect_box(0.5, 0.1, 0.5, 0.5)];
        let result = cpu.materialize_segmentations(&det, &proto_data, None);
        assert!(
            result.is_ok(),
            "zero-area bbox should return Ok with degenerate segmentation"
        );
        let segs = result.unwrap();
        assert_eq!(segs.len(), 1);
    }

    #[test]
    fn test_materialize_scaled_invalid_coeff_rows() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data(8, 8, 4, vec![vec![0.5; 4]]);
        let det = [
            make_detect_box(0.1, 0.1, 0.5, 0.5),
            make_detect_box(0.5, 0.5, 0.9, 0.9),
        ];
        let result = cpu.materialize_scaled_segmentations(&det, &proto_data, None, 64, 64);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, crate::Error::Internal(s) if s.contains("mask_coefficients rows")),
            "error should report coefficient rows vs detection count mismatch: {err:?}"
        );
    }

    #[test]
    fn test_materialize_scaled_bbox_edge_one() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data_with_values(8, 8, 1, vec![1.0_f32; 64], vec![vec![1.0]]);
        let det = [make_detect_box(0.5, 0.5, 1.0, 1.0)];
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 64, 64)
            .expect("bbox at exact boundary (1.0) should be handled on scaled path");
        assert_eq!(segs.len(), 1);
        let shape = segs[0].segmentation.shape();
        assert!(shape[0] > 0 && shape[1] > 0);
        assert_eq!(shape[2], 1);
        assert!(
            segs[0]
                .segmentation
                .iter()
                .all(|&v| matches!(v, 0_u8 | 255_u8)),
            "scaled path output must remain binarized u8"
        );
    }

    #[test]
    fn test_materialize_scaled_letterbox_mapping() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data_with_values(8, 8, 1, vec![1.0_f32; 64], vec![vec![1.0]]);
        let det = [make_detect_box(0.25, 0.1, 0.75, 0.9)];
        let segs = cpu
            .materialize_scaled_segmentations(
                &det,
                &proto_data,
                Some([0.25, 0.1, 0.75, 0.9]),
                16,
                10,
            )
            .expect("scaled path with letterbox should succeed");
        assert_eq!(segs.len(), 1);
        let seg = &segs[0];
        assert!((seg.xmin - 0.0).abs() < 1e-6);
        assert!((seg.ymin - 0.0).abs() < 1e-6);
        assert!((seg.xmax - 1.0).abs() < 1e-6);
        assert!((seg.ymax - 1.0).abs() < 1e-6);
        let shape = seg.segmentation.shape();
        assert_eq!(shape[0], 10);
        assert_eq!(shape[1], 16);
        assert_eq!(shape[2], 1);
        assert!(
            seg.segmentation.iter().all(|&v| v == 255),
            "positive logits should remain foreground after scaled letterbox mapping"
        );
    }

    #[test]
    fn test_materialize_scaled_out_of_range_letterbox_no_panic() {
        let cpu = CPUProcessor::new();
        let proto_data = make_proto_data_with_values(8, 8, 1, vec![1.0_f32; 64], vec![vec![1.0]]);
        let det = [make_detect_box(0.95, 0.95, 1.0, 1.0)];
        // Deliberately out-of-range letterbox values: this used to drive
        // proto_x0/proto_y0 to the exclusive upper bound and panic in scaled_run.
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, Some([1.2, 1.2, 1.4, 1.4]), 32, 32)
            .expect("scaled path should clamp ROI starts and avoid OOB panics");
        assert_eq!(segs.len(), 1);
        let shape = segs[0].segmentation.shape();
        assert!(shape[0] > 0 && shape[1] > 0);
        assert_eq!(shape[2], 1);
    }

    #[test]
    fn test_materialize_nchw_i8_produces_correct_mask() {
        // Verify that materialize_segmentations handles NCHW layout correctly.
        // Proto data is stored as [K, H, W] (NCHW physical) with K=2, H=4, W=4.
        // Channel 0 filled with +10, channel 1 filled with -10.
        // Coefficient [+1, +1] → dot > 0 for all pixels (positive + negative = 0,
        // but with symmetric scale the sum should still be evaluated correctly).
        // Use coefficients [1, 0] to select only channel 0 → all positive → 255.
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let (proto_h, proto_w, num_protos) = (4, 4, 2);
        // NCHW physical: [K=2, H=4, W=4] → flat = [ch0 16 values, ch1 16 values]
        let mut proto_values = vec![0_i8; num_protos * proto_h * proto_w];
        // Channel 0: all +10, Channel 1: all -10
        for i in 0..proto_h * proto_w {
            proto_values[i] = 10; // channel 0
            proto_values[proto_h * proto_w + i] = -10; // channel 1
        }
        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[num_protos, proto_h, proto_w]).unwrap();
        protos_t
            .set_quantization(Quantization::per_tensor(0.1, 0))
            .unwrap();
        // Coefficient selects channel 0 only: [+1, 0] (raw i8 with scale=1.0)
        let coeff_values = vec![1_i8, 0_i8];
        let mut coeff_t = Tensor::<i8>::from_slice(&coeff_values, &[1, num_protos]).unwrap();
        coeff_t
            .set_quantization(Quantization::per_tensor(1.0, 0))
            .unwrap();
        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::I8(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let segs = cpu
            .materialize_segmentations(&det, &proto_data, None)
            .expect("NCHW i8 proto layout should be handled");
        assert_eq!(segs.len(), 1);
        // All pixels should be 255 (positive dot product from channel 0)
        assert!(
            segs[0].segmentation.iter().all(|&v| v == 255),
            "NCHW proto with positive channel selected should yield all-255 mask"
        );
    }

    #[test]
    fn test_materialize_nchw_float_rejected() {
        // NCHW layout with non-i8 protos should return NotSupported error.
        use edgefirst_tensor::{Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let proto_values = vec![1.0_f32; 2 * 4 * 4];
        let protos_t = Tensor::<f32>::from_slice(&proto_values, &[2, 4, 4]).unwrap();
        let coeff_values = vec![1.0_f32; 2];
        let coeff_t = Tensor::<f32>::from_slice(&coeff_values, &[1, 2]).unwrap();
        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::F32(coeff_t),
            protos: TensorDyn::F32(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let result = cpu.materialize_segmentations(&det, &proto_data, None);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, crate::Error::NotSupported(s) if s.contains("NCHW")),
            "NCHW with non-i8 protos should return NotSupported: {err:?}"
        );
    }

    #[test]
    fn test_materialize_scaled_nchw_float_rejected() {
        // NCHW layout with non-i8 protos on the scaled path should also error.
        use edgefirst_tensor::{Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let proto_values = vec![1.0_f32; 2 * 4 * 4];
        let protos_t = Tensor::<f32>::from_slice(&proto_values, &[2, 4, 4]).unwrap();
        let coeff_values = vec![1.0_f32; 2];
        let coeff_t = Tensor::<f32>::from_slice(&coeff_values, &[1, 2]).unwrap();
        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::F32(coeff_t),
            protos: TensorDyn::F32(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let det = [make_detect_box(0.1, 0.1, 0.9, 0.9)];
        let result = cpu.materialize_scaled_segmentations(&det, &proto_data, None, 64, 64);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, crate::Error::NotSupported(s) if s.contains("NCHW")),
            "NCHW with non-i8 protos should return NotSupported: {err:?}"
        );
    }

    #[test]
    fn test_materialize_scaled_nchw_i8_produces_correct_mask() {
        // Verify that the scaled path handles NCHW i8 layout correctly.
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let (proto_h, proto_w, num_protos) = (4, 4, 2);
        // NCHW physical: [K=2, H=4, W=4]
        let mut proto_values = vec![0_i8; num_protos * proto_h * proto_w];
        // Channel 0: all +10, Channel 1: all -10
        for i in 0..proto_h * proto_w {
            proto_values[i] = 10;
            proto_values[proto_h * proto_w + i] = -10;
        }
        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[num_protos, proto_h, proto_w]).unwrap();
        protos_t
            .set_quantization(Quantization::per_tensor(0.1, 0))
            .unwrap();
        // Coefficient selects channel 0 only: [+1, 0]
        let coeff_values = vec![1_i8, 0_i8];
        let mut coeff_t = Tensor::<i8>::from_slice(&coeff_values, &[1, num_protos]).unwrap();
        coeff_t
            .set_quantization(Quantization::per_tensor(1.0, 0))
            .unwrap();
        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::I8(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 16, 16)
            .expect("NCHW i8 scaled path should succeed");
        assert_eq!(segs.len(), 1);
        // All pixels should be 255 (positive dot product from channel 0)
        assert!(
            segs[0].segmentation.iter().all(|&v| v == 255),
            "NCHW i8 scaled path with positive channel should yield all-255 mask"
        );
    }

    #[test]
    fn test_materialize_nchw_i8_asymmetric_quantization() {
        // Verify that NCHW i8 kernel handles non-zero zero-points correctly.
        // Asymmetric quantization: real_value = (raw - zero_point) * scale
        // Proto: zp=5, scale=0.1 → raw 15 means (15-5)*0.1 = 1.0
        // Coeff: zp=10, scale=0.5 → raw 12 means (12-10)*0.5 = 1.0
        //
        // With K=2 channels: proto ch0=15 (→1.0), proto ch1=5 (→0.0)
        // coeff = [12, 10] (→[1.0, 0.0])
        // dot = 1.0*1.0 + 0.0*0.0 = 1.0 > 0 → mask = 255
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let (proto_h, proto_w, num_protos) = (4, 4, 2);

        // NCHW physical: [K=2, H=4, W=4]
        let mut proto_values = vec![0_i8; num_protos * proto_h * proto_w];
        let proto_zp: i8 = 5;
        // Channel 0: raw = 15 → dequant = (15-5)*0.1 = 1.0
        // Channel 1: raw = 5 → dequant = (5-5)*0.1 = 0.0
        for i in 0..proto_h * proto_w {
            proto_values[i] = 15; // channel 0
            proto_values[proto_h * proto_w + i] = proto_zp; // channel 1 (at zero-point)
        }
        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[num_protos, proto_h, proto_w]).unwrap();
        protos_t
            .set_quantization(Quantization::per_tensor(0.1, proto_zp as i32))
            .unwrap();

        // Coefficient: zp=10, scale=0.5
        // raw=[12, 10] → dequant=[(12-10)*0.5, (10-10)*0.5] = [1.0, 0.0]
        let coeff_zp: i8 = 10;
        let coeff_values = vec![12_i8, coeff_zp];
        let mut coeff_t = Tensor::<i8>::from_slice(&coeff_values, &[1, num_protos]).unwrap();
        coeff_t
            .set_quantization(Quantization::per_tensor(0.5, coeff_zp as i32))
            .unwrap();

        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::I8(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let segs = cpu
            .materialize_segmentations(&det, &proto_data, None)
            .expect("NCHW i8 asymmetric quantization should succeed");
        assert_eq!(segs.len(), 1);
        // Dot product = 1.0 > 0 → all 255
        assert!(
            segs[0].segmentation.iter().all(|&v| v == 255),
            "NCHW i8 with non-zero zero-points: positive dot should yield all-255"
        );

        // Now test case where dot < 0: use coeff that selects a negative channel.
        // coeff raw=[10, 12] → dequant=[0.0, 1.0]; ch1 is at zero_point → 0.0
        // dot = 1.0*0.0 + 0.0*1.0 = 0.0 → NOT > 0 → mask = 0
        let coeff_neg = vec![coeff_zp, 12_i8]; // selects channel 1 which is zero
        let mut coeff_t_neg = Tensor::<i8>::from_slice(&coeff_neg, &[1, num_protos]).unwrap();
        coeff_t_neg
            .set_quantization(Quantization::per_tensor(0.5, coeff_zp as i32))
            .unwrap();

        // Recreate protos tensor (Tensor doesn't implement Clone)
        let mut protos_t2 =
            Tensor::<i8>::from_slice(&proto_values, &[num_protos, proto_h, proto_w]).unwrap();
        protos_t2
            .set_quantization(Quantization::per_tensor(0.1, proto_zp as i32))
            .unwrap();

        let proto_data_neg = crate::ProtoData {
            mask_coefficients: TensorDyn::I8(coeff_t_neg),
            protos: TensorDyn::I8(protos_t2),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let segs_neg = cpu
            .materialize_segmentations(&det, &proto_data_neg, None)
            .expect("NCHW i8 asymmetric: zero-dot case");
        assert_eq!(segs_neg.len(), 1);
        // dot = 0 → NOT > 0 → mask should be 0
        assert!(
            segs_neg[0].segmentation.iter().all(|&v| v == 0),
            "NCHW i8 with non-zero zero-points: zero dot should yield all-0"
        );
    }

    #[test]
    fn test_materialize_per_channel_i8_falls_through_to_f32() {
        // Verify that I8 protos with per-channel quantization fall through
        // from the i8×i8 fast path to the general f32 dequant path.
        // This tests the regression fix: previously the i8 fast path returned
        // NotSupported without falling back.
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let (proto_h, proto_w, num_protos) = (4, 4, 2);

        // NHWC protos: [H, W, K] = [4, 4, 2]
        // Channel 0: all +10, Channel 1: all -10
        let mut proto_values = vec![0_i8; proto_h * proto_w * num_protos];
        for y in 0..proto_h {
            for x in 0..proto_w {
                let base = (y * proto_w + x) * num_protos;
                proto_values[base] = 10; // channel 0
                proto_values[base + 1] = -10; // channel 1
            }
        }
        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[proto_h, proto_w, num_protos]).unwrap();
        // Per-channel symmetric quantization on axis 2 (channel axis).
        let scales = vec![0.1_f32; num_protos];
        protos_t
            .set_quantization(Quantization::per_channel_symmetric(scales, 2).unwrap())
            .unwrap();

        // Per-tensor coeff: [1, 0] → selects channel 0 only
        let coeff_values = vec![1_i8, 0_i8];
        let mut coeff_t = Tensor::<i8>::from_slice(&coeff_values, &[1, num_protos]).unwrap();
        coeff_t
            .set_quantization(Quantization::per_tensor(1.0, 0))
            .unwrap();

        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::I8(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nhwc,
        };
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let segs = cpu
            .materialize_segmentations(&det, &proto_data, None)
            .expect("per-channel I8 protos should fall through to f32 path");
        assert_eq!(segs.len(), 1);
        // Channel 0 is positive (10 * 0.1 = 1.0), coeff selects it → dot > 0 → 255
        assert!(
            segs[0].segmentation.iter().all(|&v| v == 255),
            "per-channel i8 fallback: positive dot should yield all-255"
        );
    }

    /// Golden-byte anchor: runs the quantized decode + CPU mask materialization
    /// file.
    ///
    /// Regression-protection intent: any refactor that changes the i8 fused
    /// dequant+dot+sigmoid kernel, the NMS ordering, or the ROI coordinate
    /// mapping will perturb the mask bytes and fail this test.
    ///
    /// Generating / refreshing the golden:
    /// ```text
    /// REGEN_GOLDEN=1 cargo test -p edgefirst-image --lib \
    ///     test_materialize_golden_i8_cached_model
    /// ```
    /// writes `testdata/yolov8_mask0_160x160.bin` (or updates it). Commit
    /// the resulting file; subsequent runs verify bit-exact.
    #[test]
    fn test_materialize_golden_i8_cached_model() {
        use edgefirst_decoder::{configs, ConfigOutput, DecoderBuilder, DetectBox, Nms, ProtoData};
        use edgefirst_tensor::{Tensor, TensorDyn};

        let boxes_raw = edgefirst_bench::testdata::read("yolov8_boxes_116x8400.bin");
        let boxes_i8 =
            unsafe { std::slice::from_raw_parts(boxes_raw.as_ptr() as *const i8, boxes_raw.len()) };
        let boxes_tensor = TensorDyn::I8(
            Tensor::<i8>::from_slice(boxes_i8, &[1, 116, 8400]).expect("boxes tensor"),
        );

        let protos_raw = edgefirst_bench::testdata::read("yolov8_protos_160x160x32.bin");
        let protos_i8 = unsafe {
            std::slice::from_raw_parts(protos_raw.as_ptr() as *const i8, protos_raw.len())
        };
        let protos_tensor = TensorDyn::I8(
            Tensor::<i8>::from_slice(protos_i8, &[1, 160, 160, 32]).expect("protos tensor"),
        );

        let detection_cfg = configs::Detection {
            decoder: configs::DecoderType::Ultralytics,
            quantization: Some(configs::QuantTuple(0.019_484_945, 20)),
            shape: vec![1, 116, 8400],
            dshape: vec![],
            anchors: None,
            normalized: Some(true),
        };
        let protos_cfg = configs::Protos {
            decoder: configs::DecoderType::Ultralytics,
            quantization: Some(configs::QuantTuple(0.020_889_873, -115)),
            shape: vec![1, 160, 160, 32],
            dshape: vec![],
        };
        let decoder = DecoderBuilder::default()
            .with_score_threshold(0.45)
            .with_iou_threshold(0.45)
            .with_nms(Some(Nms::ClassAgnostic))
            .add_output(ConfigOutput::Detection(detection_cfg))
            .add_output(ConfigOutput::Protos(protos_cfg))
            .build()
            .expect("yolov8-seg golden decoder must build");

        let inputs: Vec<&TensorDyn> = vec![&boxes_tensor, &protos_tensor];
        let mut detections: Vec<DetectBox> = Vec::with_capacity(50);
        let proto_data: ProtoData = decoder
            .decode_proto(&inputs, &mut detections)
            .expect("decode_proto must succeed")
            .expect("yolov8-seg config produces ProtoData");
        assert!(!detections.is_empty(), "fixture produced no detections");

        let cpu = CPUProcessor::new();
        let segs = cpu
            .materialize_segmentations(&detections, &proto_data, None)
            .expect("materialize_segmentations failed on cached fixture");
        assert_eq!(segs.len(), detections.len());

        // Serialize detection 0's binarized mask as a compact byte blob:
        //   [u16 roi_h_le][u16 roi_w_le][roi_h * roi_w bytes of u8 mask data]
        // (Channels dim is always 1; no need to store it.)
        let det0_seg = &segs[0].segmentation;
        let sh = det0_seg.shape();
        assert_eq!(sh.len(), 3, "segmentation must be rank-3");
        assert_eq!(sh[2], 1, "YOLO-seg mask has channel dim 1");
        let roi_h = sh[0];
        let roi_w = sh[1];
        assert!(roi_h <= u16::MAX as usize && roi_w <= u16::MAX as usize);
        let mut actual: Vec<u8> = Vec::with_capacity(4 + roi_h * roi_w);
        actual.extend_from_slice(&(roi_h as u16).to_le_bytes());
        actual.extend_from_slice(&(roi_w as u16).to_le_bytes());
        let det0_contig = det0_seg.as_standard_layout();
        actual.extend_from_slice(det0_contig.as_slice().expect("standard layout gives slice"));

        // Resolve testdata via EDGEFIRST_TESTDATA_DIR when set (on-target runs use
        // a deployed copy; the compile-time manifest path does not exist there),
        // falling back to the source tree for local runs.
        let golden_path = std::env::var_os("EDGEFIRST_TESTDATA_DIR")
            .map(|d| std::path::PathBuf::from(d).join("yolov8_mask0_160x160.bin"))
            .unwrap_or_else(|| {
                std::path::PathBuf::from(concat!(
                    env!("CARGO_MANIFEST_DIR"),
                    "/../../testdata/yolov8_mask0_160x160.bin"
                ))
            });

        if std::env::var_os("REGEN_GOLDEN").is_some() {
            std::fs::write(&golden_path, &actual).expect("could not write golden");
            eprintln!(
                "REGEN_GOLDEN: wrote {} bytes (roi_h={roi_h}, roi_w={roi_w}) to {}",
                actual.len(),
                golden_path.display()
            );
            return;
        }

        let expected = std::fs::read(&golden_path).unwrap_or_else(|e| {
            panic!(
                "missing golden at {}: {e}. Run \
                 `REGEN_GOLDEN=1 cargo test test_materialize_golden_i8_cached_model` \
                 once to create it, then commit the file.",
                golden_path.display()
            )
        });
        assert_eq!(
            actual.len(),
            expected.len(),
            "golden size mismatch: got {} bytes, expected {}",
            actual.len(),
            expected.len()
        );
        if actual != expected {
            let mut first_diff = None;
            for (i, (a, e)) in actual.iter().zip(expected.iter()).enumerate() {
                if a != e {
                    first_diff = Some((i, *a, *e));
                    break;
                }
            }
            let total_diff = actual
                .iter()
                .zip(expected.iter())
                .filter(|(a, e)| a != e)
                .count();
            panic!(
                "golden mismatch — {total_diff}/{} bytes differ; first at {first_diff:?}. \
                 If the change is intentional, verify visually and re-run with REGEN_GOLDEN=1.",
                actual.len()
            );
        }
    }

    // ── i8×i8 integer mask decode path tests ─────────────────────────────────────

    /// Build a ProtoData with I8 protos and I8 coefficients (with quantization).
    #[allow(clippy::too_many_arguments)]
    fn make_proto_data_i8(
        proto_h: usize,
        proto_w: usize,
        num_protos: usize,
        proto_values: Vec<i8>,
        proto_quant: (f32, i32),
        coeff_values: Vec<i8>,
        coeff_quant: (f32, i32),
        num_detections: usize,
    ) -> crate::ProtoData {
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        assert_eq!(proto_values.len(), proto_h * proto_w * num_protos);
        assert_eq!(coeff_values.len(), num_detections * num_protos);

        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[proto_h, proto_w, num_protos]).unwrap();
        protos_t
            .set_quantization(Quantization::per_tensor(proto_quant.0, proto_quant.1))
            .unwrap();

        let mut coeff_t =
            Tensor::<i8>::from_slice(&coeff_values, &[num_detections, num_protos]).unwrap();
        coeff_t
            .set_quantization(Quantization::per_tensor(coeff_quant.0, coeff_quant.1))
            .unwrap();

        crate::ProtoData {
            mask_coefficients: TensorDyn::I8(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nhwc,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn make_proto_data_i16_i8(
        proto_h: usize,
        proto_w: usize,
        num_protos: usize,
        proto_values: Vec<i8>,
        proto_quant: (f32, i32),
        coeff_values: Vec<i16>,
        coeff_quant: (f32, i32),
        num_detections: usize,
    ) -> crate::ProtoData {
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        assert_eq!(proto_values.len(), proto_h * proto_w * num_protos);
        assert_eq!(coeff_values.len(), num_detections * num_protos);

        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[proto_h, proto_w, num_protos]).unwrap();
        protos_t
            .set_quantization(Quantization::per_tensor(proto_quant.0, proto_quant.1))
            .unwrap();

        let mut coeff_t =
            Tensor::<i16>::from_slice(&coeff_values, &[num_detections, num_protos]).unwrap();
        coeff_t
            .set_quantization(Quantization::per_tensor(coeff_quant.0, coeff_quant.1))
            .unwrap();

        crate::ProtoData {
            mask_coefficients: TensorDyn::I16(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nhwc,
        }
    }

    #[test]
    fn test_materialize_scaled_i8_i8_basic() {
        // Uniform positive protos + positive coefficients → all-255 mask.
        let proto_h = 4;
        let proto_w = 4;
        let num_protos = 2;
        let proto_values = vec![10_i8; proto_h * proto_w * num_protos];
        let coeff_values = vec![10_i8; num_protos];
        let proto_data = make_proto_data_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_values,
            (0.1, 0),
            coeff_values,
            (0.1, 0),
            1,
        );
        let det = [make_detect_box(0.1, 0.1, 0.9, 0.9)];
        let cpu = CPUProcessor::new();
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 16, 16)
            .expect("i8×i8 scaled path should succeed");
        assert_eq!(segs.len(), 1);
        assert_eq!(segs[0].segmentation.shape()[2], 1);
        // All protos positive, all coeffs positive → dot products positive
        // → all mask pixels should be 255.
        assert!(
            segs[0].segmentation.iter().all(|&v| v == 255),
            "uniform positive protos+coeffs should produce all-255 mask"
        );
    }

    #[test]
    fn test_materialize_scaled_i8_i8_all_negative() {
        // Positive protos with negative coefficients → all-0 mask.
        let proto_h = 4;
        let proto_w = 4;
        let num_protos = 2;
        let proto_values = vec![10_i8; proto_h * proto_w * num_protos];
        let coeff_values = vec![-10_i8; num_protos];
        let proto_data = make_proto_data_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_values,
            (0.1, 0),
            coeff_values,
            (0.1, 0),
            1,
        );
        let det = [make_detect_box(0.1, 0.1, 0.9, 0.9)];
        let cpu = CPUProcessor::new();
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 16, 16)
            .expect("i8×i8 scaled path should succeed");
        assert_eq!(segs.len(), 1);
        // Negative dot products → all mask pixels should be 0.
        assert!(
            segs[0].segmentation.iter().all(|&v| v == 0),
            "positive protos + negative coeffs should produce all-0 mask"
        );
    }

    #[test]
    fn test_materialize_scaled_i8_i8_mixed_sign_boundary() {
        // Create a proto field where the left half is positive, right half
        // is negative. This exercises the bilinear boundary interpolation
        // code (the non-shortcut path).
        let proto_h = 4;
        let proto_w = 4;
        let num_protos = 1;
        let mut proto_values = Vec::with_capacity(proto_h * proto_w * num_protos);
        for _y in 0..proto_h {
            for x in 0..proto_w {
                proto_values.push(if x < proto_w / 2 { 50_i8 } else { -50_i8 });
            }
        }
        let coeff_values = vec![1_i8]; // identity coefficient
        let proto_data = make_proto_data_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_values,
            (0.1, 0),
            coeff_values,
            (0.1, 0),
            1,
        );
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let cpu = CPUProcessor::new();
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 16, 16)
            .expect("i8×i8 with mixed-sign protos should succeed");
        assert_eq!(segs.len(), 1);
        let mask = &segs[0].segmentation;
        // Mask should have both 0 and 255 values (left half ≈ 255, right ≈ 0).
        let has_255 = mask.iter().any(|&v| v == 255);
        let has_0 = mask.iter().any(|&v| v == 0);
        assert!(
            has_255 && has_0,
            "mixed-sign proto field should produce mixed mask"
        );
        // All values should be binarized.
        assert!(
            mask.iter().all(|&v| v == 0 || v == 255),
            "mask must be binarized (0 or 255)"
        );
    }

    #[test]
    fn test_materialize_scaled_i8_i8_with_zero_points() {
        // Test that zero-point correction is applied correctly.
        // Protos with zp=-5, coeffs with zp=3.
        let proto_h = 4;
        let proto_w = 4;
        let num_protos = 2;
        // Raw proto values are 10, dequantized = (10 - (-5)) * 0.1 = 1.5
        let proto_values = vec![10_i8; proto_h * proto_w * num_protos];
        // Raw coeff values are 10, dequantized = (10 - 3) * 0.1 = 0.7
        // Both positive → dot product positive → mask = 255
        let coeff_values = vec![10_i8; num_protos];
        let proto_data = make_proto_data_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_values,
            (0.1, -5),
            coeff_values,
            (0.1, 3),
            1,
        );
        let det = [make_detect_box(0.1, 0.1, 0.9, 0.9)];
        let cpu = CPUProcessor::new();
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 16, 16)
            .expect("i8×i8 with zero-points should succeed");
        assert_eq!(segs.len(), 1);
        // Dequantized values are both positive → all 255.
        assert!(
            segs[0].segmentation.iter().all(|&v| v == 255),
            "positive dequantized values should produce all-255 mask"
        );
    }

    #[test]
    fn test_materialize_scaled_i8_i8_parity_with_float() {
        // Compare i8×i8 integer path output against the f32 fallback path
        // using symmetric quantization (zp=0) so the results should match exactly.
        let proto_h = 8;
        let proto_w = 8;
        let num_protos = 4;

        // Generate a structured proto field with varied values.
        let mut proto_i8 = Vec::with_capacity(proto_h * proto_w * num_protos);
        for y in 0..proto_h {
            for x in 0..proto_w {
                for k in 0..num_protos {
                    let v = ((y as i32 * 7 + x as i32 * 13 + k as i32 * 3) % 127) as i8 - 60;
                    proto_i8.push(v);
                }
            }
        }

        let coeff_i8: Vec<i8> = (0..num_protos).map(|k| k as i8 * 10 + 5).collect();

        // Build f32 versions (symmetric quant, zp=0, scale=1.0).
        let proto_f32: Vec<f32> = proto_i8.iter().map(|&v| v as f32).collect();
        let coeff_f32: Vec<f32> = coeff_i8.iter().map(|&v| v as f32).collect();

        let proto_data_f32 =
            make_proto_data_with_values(proto_h, proto_w, num_protos, proto_f32, vec![coeff_f32]);
        let proto_data_i8 = make_proto_data_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_i8,
            (1.0, 0),
            coeff_i8,
            (1.0, 0),
            1,
        );

        let det = [make_detect_box(0.05, 0.05, 0.95, 0.95)];
        let cpu = CPUProcessor::new();

        let segs_f32 = cpu
            .materialize_scaled_segmentations(&det, &proto_data_f32, None, 32, 32)
            .expect("f32 path");
        let segs_i8 = cpu
            .materialize_scaled_segmentations(&det, &proto_data_i8, None, 32, 32)
            .expect("i8 path");

        assert_eq!(segs_f32.len(), 1);
        assert_eq!(segs_i8.len(), 1);
        assert_eq!(
            segs_f32[0].segmentation.shape(),
            segs_i8[0].segmentation.shape(),
            "i8 and f32 paths should produce same-shaped masks"
        );

        // With symmetric quantization (zp=0, scale=1.0), the sign of the
        // dot product is identical, so binarized masks must match exactly.
        let f32_mask: Vec<u8> = segs_f32[0].segmentation.iter().copied().collect();
        let i8_mask: Vec<u8> = segs_i8[0].segmentation.iter().copied().collect();
        assert_eq!(
            f32_mask, i8_mask,
            "i8×i8 integer path must produce identical binarized mask as f32 path (symmetric quant)"
        );
    }

    #[test]
    fn test_materialize_i16_i8_parity_with_float() {
        let proto_h = 8;
        let proto_w = 8;
        let num_protos = 4;

        let mut proto_i8 = Vec::with_capacity(proto_h * proto_w * num_protos);
        for y in 0..proto_h {
            for x in 0..proto_w {
                for k in 0..num_protos {
                    let v = ((y as i32 * 7 + x as i32 * 13 + k as i32 * 3) % 127) as i8 - 60;
                    proto_i8.push(v);
                }
            }
        }

        let coeff_i16 = vec![300_i16, -250, 180, -130];
        let proto_f32: Vec<f32> = proto_i8.iter().map(|&v| v as f32).collect();
        let coeff_f32: Vec<f32> = coeff_i16.iter().map(|&v| v as f32).collect();

        let proto_data_f32 =
            make_proto_data_with_values(proto_h, proto_w, num_protos, proto_f32, vec![coeff_f32]);
        let proto_data_i16 = make_proto_data_i16_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_i8,
            (1.0, 0),
            coeff_i16,
            (1.0, 0),
            1,
        );

        let det = [make_detect_box(0.05, 0.05, 0.95, 0.95)];
        let cpu = CPUProcessor::new();

        let segs_f32 = cpu
            .materialize_segmentations(&det, &proto_data_f32, None)
            .expect("f32 path");
        let segs_i16 = cpu
            .materialize_segmentations(&det, &proto_data_i16, None)
            .expect("i16 path");

        let f32_mask: Vec<u8> = segs_f32[0].segmentation.iter().copied().collect();
        let i16_mask: Vec<u8> = segs_i16[0].segmentation.iter().copied().collect();
        assert_eq!(
            f32_mask, i16_mask,
            "i16×i8 proto path should match f32 fallback"
        );
    }

    #[test]
    fn test_materialize_scaled_i16_i8_parity_with_float() {
        let proto_h = 8;
        let proto_w = 8;
        let num_protos = 4;

        let mut proto_i8 = Vec::with_capacity(proto_h * proto_w * num_protos);
        for y in 0..proto_h {
            for x in 0..proto_w {
                for k in 0..num_protos {
                    let v = ((y as i32 * 11 + x as i32 * 5 + k as i32 * 17) % 127) as i8 - 60;
                    proto_i8.push(v);
                }
            }
        }

        let coeff_i16 = vec![220_i16, -180, 150, -90];
        let proto_f32: Vec<f32> = proto_i8.iter().map(|&v| v as f32).collect();
        let coeff_f32: Vec<f32> = coeff_i16.iter().map(|&v| v as f32).collect();

        let proto_data_f32 =
            make_proto_data_with_values(proto_h, proto_w, num_protos, proto_f32, vec![coeff_f32]);
        let proto_data_i16 = make_proto_data_i16_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_i8,
            (1.0, 0),
            coeff_i16,
            (1.0, 0),
            1,
        );

        let det = [make_detect_box(0.05, 0.05, 0.95, 0.95)];
        let cpu = CPUProcessor::new();

        let segs_f32 = cpu
            .materialize_scaled_segmentations(&det, &proto_data_f32, None, 32, 32)
            .expect("f32 path");
        let segs_i16 = cpu
            .materialize_scaled_segmentations(&det, &proto_data_i16, None, 32, 32)
            .expect("i16 path");

        let f32_mask: Vec<u8> = segs_f32[0].segmentation.iter().copied().collect();
        let i16_mask: Vec<u8> = segs_i16[0].segmentation.iter().copied().collect();
        assert_eq!(
            f32_mask, i16_mask,
            "scaled i16×i8 path should match f32 fallback"
        );
    }

    #[test]
    fn test_materialize_nchw_i8_f32_coefficients_use_fallback() {
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let (proto_h, proto_w, num_protos) = (4, 4, 2);
        let mut proto_values = vec![0_i8; num_protos * proto_h * proto_w];
        for i in 0..proto_h * proto_w {
            proto_values[i] = 10;
            proto_values[proto_h * proto_w + i] = -10;
        }
        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[num_protos, proto_h, proto_w]).unwrap();
        protos_t
            .set_quantization(Quantization::per_tensor(0.1, 0))
            .unwrap();
        let coeff_t = Tensor::<f32>::from_slice(&[1.0_f32, 0.0], &[1, num_protos]).unwrap();
        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::F32(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let segs = cpu
            .materialize_segmentations(&det, &proto_data, None)
            .expect("NCHW i8 protos should transpose in f32 fallback");
        assert!(segs[0].segmentation.iter().all(|&v| v == 255));
    }

    #[test]
    fn test_materialize_scaled_nchw_i8_f32_coefficients_use_fallback() {
        use edgefirst_tensor::{Quantization, Tensor, TensorDyn};
        let cpu = CPUProcessor::new();
        let (proto_h, proto_w, num_protos) = (4, 4, 2);
        let mut proto_values = vec![0_i8; num_protos * proto_h * proto_w];
        for i in 0..proto_h * proto_w {
            proto_values[i] = 10;
            proto_values[proto_h * proto_w + i] = -10;
        }
        let mut protos_t =
            Tensor::<i8>::from_slice(&proto_values, &[num_protos, proto_h, proto_w]).unwrap();
        protos_t
            .set_quantization(Quantization::per_tensor(0.1, 0))
            .unwrap();
        let coeff_t = Tensor::<f32>::from_slice(&[1.0_f32, 0.0], &[1, num_protos]).unwrap();
        let proto_data = crate::ProtoData {
            mask_coefficients: TensorDyn::F32(coeff_t),
            protos: TensorDyn::I8(protos_t),
            layout: edgefirst_decoder::ProtoLayout::Nchw,
        };
        let det = [make_detect_box(0.0, 0.0, 1.0, 1.0)];
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 16, 16)
            .expect("NCHW i8 protos should transpose in scaled f32 fallback");
        assert!(segs[0].segmentation.iter().all(|&v| v == 255));
    }

    #[test]
    fn test_materialize_scaled_i8_i8_multiple_detections() {
        let proto_h = 4;
        let proto_w = 4;
        let num_protos = 2;
        let proto_values = vec![10_i8; proto_h * proto_w * num_protos];
        // Two detections: one positive, one negative.
        let mut coeff_values = Vec::with_capacity(2 * num_protos);
        coeff_values.extend_from_slice(&[10_i8, 10]); // det 0: positive
        coeff_values.extend_from_slice(&[-10_i8, -10]); // det 1: negative
        let proto_data = make_proto_data_i8(
            proto_h,
            proto_w,
            num_protos,
            proto_values,
            (0.1, 0),
            coeff_values,
            (0.1, 0),
            2,
        );
        let det = [
            make_detect_box(0.1, 0.1, 0.5, 0.5),
            make_detect_box(0.5, 0.5, 0.9, 0.9),
        ];
        let cpu = CPUProcessor::new();
        let segs = cpu
            .materialize_scaled_segmentations(&det, &proto_data, None, 16, 16)
            .expect("multiple detections i8×i8 should succeed");
        assert_eq!(segs.len(), 2);
        // Det 0: positive coeffs → all 255.
        assert!(segs[0].segmentation.iter().all(|&v| v == 255));
        // Det 1: negative coeffs → all 0.
        assert!(segs[1].segmentation.iter().all(|&v| v == 0));
    }

    // ── Multiplane PixelFormat::Nv12 tests ───────────────────────────────────────

    #[test]
    fn test_multiplane_nv12_creation() -> Result<()> {
        let luma = Tensor::<u8>::new(&[720, 1280], Some(TensorMemory::Mem), Some("luma"))?;
        let chroma = Tensor::<u8>::new(&[360, 1280], Some(TensorMemory::Mem), Some("chroma"))?;
        let img = {
            let __t = Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12)?;
            TensorDyn::from(__t)
        };

        assert_eq!(img.width(), Some(1280));
        assert_eq!(img.height(), Some(720));
        assert_eq!(img.format().unwrap(), PixelFormat::Nv12);
        assert!(img.as_u8().unwrap().is_multiplane());
        assert!(img.as_u8().unwrap().chroma().is_some());
        Ok(())
    }

    #[test]
    fn test_multiplane_is_multiplane() -> Result<()> {
        // Contiguous PixelFormat::Nv12 should NOT be multiplane
        let contiguous = TensorDyn::image(
            640,
            480,
            PixelFormat::Nv12,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        assert!(!contiguous.as_u8().unwrap().is_multiplane());
        assert!(contiguous.as_u8().unwrap().chroma().is_none());

        // from_planes should be multiplane
        let luma = Tensor::<u8>::new(&[480, 640], Some(TensorMemory::Mem), None)?;
        let chroma = Tensor::<u8>::new(&[240, 640], Some(TensorMemory::Mem), None)?;
        let multiplane = {
            let __t = Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12)?;
            TensorDyn::from(__t)
        };
        assert!(multiplane.as_u8().unwrap().is_multiplane());
        assert!(multiplane.as_u8().unwrap().chroma().is_some());

        // PixelFormat::Rgb should NOT be multiplane
        let rgb = TensorDyn::image(
            640,
            480,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        assert!(!rgb.as_u8().unwrap().is_multiplane());
        Ok(())
    }

    #[test]
    fn test_multiplane_invalid_shapes() {
        // Wrong format (PixelFormat::Rgb not supported for multiplane)
        let luma = Tensor::<u8>::new(&[480, 640], Some(TensorMemory::Mem), None).unwrap();
        let chroma = Tensor::<u8>::new(&[240, 640], Some(TensorMemory::Mem), None).unwrap();
        assert!(Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Rgb).is_err());

        // Chroma height mismatch for PixelFormat::Nv12 (should be H/2)
        let luma = Tensor::<u8>::new(&[480, 640], Some(TensorMemory::Mem), None).unwrap();
        let chroma = Tensor::<u8>::new(&[480, 640], Some(TensorMemory::Mem), None).unwrap();
        assert!(Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12).is_err());

        // Chroma width mismatch
        let luma = Tensor::<u8>::new(&[480, 640], Some(TensorMemory::Mem), None).unwrap();
        let chroma = Tensor::<u8>::new(&[240, 320], Some(TensorMemory::Mem), None).unwrap();
        assert!(Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12).is_err());

        // 3D luma (should be 2D)
        let luma = Tensor::<u8>::new(&[480, 640, 1], Some(TensorMemory::Mem), None).unwrap();
        let chroma = Tensor::<u8>::new(&[240, 640], Some(TensorMemory::Mem), None).unwrap();
        assert!(Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12).is_err());
    }

    #[test]
    fn test_multiplane_nv12_to_rgb_cpu() -> Result<()> {
        // Load PixelFormat::Nv12 test data as contiguous buffer
        let nv12_bytes = edgefirst_bench::testdata::read("camera720p.nv12");
        let width = 1280usize;
        let height = 720usize;
        let y_size = width * height;
        let uv_size = width * (height / 2);

        // ── Contiguous path (baseline) ──────────────────────────────
        let contiguous = load_bytes_to_tensor(width, height, PixelFormat::Nv12, None, &nv12_bytes)?;
        let dst_contiguous = TensorDyn::image(
            width,
            height,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let mut converter = CPUProcessor::default();
        let contiguous_dyn = contiguous;
        let mut dst_contiguous_dyn = dst_contiguous;
        converter.convert(
            &contiguous_dyn,
            &mut dst_contiguous_dyn,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        // ── Multiplane path ─────────────────────────────────────────
        let luma = Tensor::<u8>::new(&[height, width], Some(TensorMemory::Mem), Some("luma"))?;
        luma.map()?.as_mut_slice()[..y_size].copy_from_slice(&nv12_bytes[..y_size]);

        let chroma = Tensor::<u8>::new(
            &[height / 2, width],
            Some(TensorMemory::Mem),
            Some("chroma"),
        )?;
        chroma.map()?.as_mut_slice()[..uv_size]
            .copy_from_slice(&nv12_bytes[y_size..y_size + uv_size]);

        let multiplane = {
            let __t = Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12)?;
            TensorDyn::from(__t)
        };
        let dst_multiplane = TensorDyn::image(
            width,
            height,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let multiplane_dyn = multiplane;
        let mut dst_multiplane_dyn = dst_multiplane;
        converter.convert(
            &multiplane_dyn,
            &mut dst_multiplane_dyn,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        // ── Compare: both paths must produce identical output ───────
        let contiguous_map = dst_contiguous_dyn.as_u8().unwrap().map()?;
        let multiplane_map = dst_multiplane_dyn.as_u8().unwrap().map()?;
        assert_eq!(
            contiguous_map.as_slice(),
            multiplane_map.as_slice(),
            "multiplane PixelFormat::Nv12→PixelFormat::Rgb must match contiguous path"
        );
        Ok(())
    }

    #[test]
    fn test_multiplane_nv12_to_rgba_cpu() -> Result<()> {
        let nv12_bytes = edgefirst_bench::testdata::read("camera720p.nv12");
        let width = 1280usize;
        let height = 720usize;
        let y_size = width * height;
        let uv_size = width * (height / 2);

        let contiguous = load_bytes_to_tensor(width, height, PixelFormat::Nv12, None, &nv12_bytes)?;
        let dst_contiguous = TensorDyn::image(
            width,
            height,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let mut converter = CPUProcessor::default();
        let contiguous_dyn = contiguous;
        let mut dst_contiguous_dyn = dst_contiguous;
        converter.convert(
            &contiguous_dyn,
            &mut dst_contiguous_dyn,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        let luma = Tensor::<u8>::new(&[height, width], Some(TensorMemory::Mem), Some("luma"))?;
        luma.map()?.as_mut_slice()[..y_size].copy_from_slice(&nv12_bytes[..y_size]);
        let chroma = Tensor::<u8>::new(
            &[height / 2, width],
            Some(TensorMemory::Mem),
            Some("chroma"),
        )?;
        chroma.map()?.as_mut_slice()[..uv_size]
            .copy_from_slice(&nv12_bytes[y_size..y_size + uv_size]);

        let multiplane = {
            let __t = Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12)?;
            TensorDyn::from(__t)
        };
        let dst_multiplane = TensorDyn::image(
            width,
            height,
            PixelFormat::Rgba,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let multiplane_dyn = multiplane;
        let mut dst_multiplane_dyn = dst_multiplane;
        converter.convert(
            &multiplane_dyn,
            &mut dst_multiplane_dyn,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        let contiguous_map = dst_contiguous_dyn.as_u8().unwrap().map()?;
        let multiplane_map = dst_multiplane_dyn.as_u8().unwrap().map()?;
        assert_eq!(
            contiguous_map.as_slice(),
            multiplane_map.as_slice(),
            "multiplane PixelFormat::Nv12→PixelFormat::Rgba must match contiguous path"
        );
        Ok(())
    }

    #[test]
    fn test_multiplane_nv12_to_grey_cpu() -> Result<()> {
        let nv12_bytes = edgefirst_bench::testdata::read("camera720p.nv12");
        let width = 1280usize;
        let height = 720usize;
        let y_size = width * height;
        let uv_size = width * (height / 2);

        let contiguous = load_bytes_to_tensor(width, height, PixelFormat::Nv12, None, &nv12_bytes)?;
        let dst_contiguous = TensorDyn::image(
            width,
            height,
            PixelFormat::Grey,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let mut converter = CPUProcessor::default();
        let contiguous_dyn = contiguous;
        let mut dst_contiguous_dyn = dst_contiguous;
        converter.convert(
            &contiguous_dyn,
            &mut dst_contiguous_dyn,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        let luma = Tensor::<u8>::new(&[height, width], Some(TensorMemory::Mem), Some("luma"))?;
        luma.map()?.as_mut_slice()[..y_size].copy_from_slice(&nv12_bytes[..y_size]);
        let chroma = Tensor::<u8>::new(
            &[height / 2, width],
            Some(TensorMemory::Mem),
            Some("chroma"),
        )?;
        chroma.map()?.as_mut_slice()[..uv_size]
            .copy_from_slice(&nv12_bytes[y_size..y_size + uv_size]);

        let multiplane = {
            let __t = Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12)?;
            TensorDyn::from(__t)
        };
        let dst_multiplane = TensorDyn::image(
            width,
            height,
            PixelFormat::Grey,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let multiplane_dyn = multiplane;
        let mut dst_multiplane_dyn = dst_multiplane;
        converter.convert(
            &multiplane_dyn,
            &mut dst_multiplane_dyn,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        let contiguous_map = dst_contiguous_dyn.as_u8().unwrap().map()?;
        let multiplane_map = dst_multiplane_dyn.as_u8().unwrap().map()?;
        assert_eq!(
            contiguous_map.as_slice(),
            multiplane_map.as_slice(),
            "multiplane PixelFormat::Nv12→PixelFormat::Grey must match contiguous path"
        );
        Ok(())
    }

    // ──────────────────────────────────────────────────────────────────────
    // src_rect clamping tests — verify that cropping from a larger buffer
    // never samples padding pixels during bilinear resize.
    // ──────────────────────────────────────────────────────────────────────

    /// Create a synthetic RGB tensor where the left half is pure red and the
    /// right half is pure blue.
    fn make_red_blue_src(width: usize, height: usize) -> TensorDyn {
        let mut t = TensorDyn::image(
            width,
            height,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let tensor_u8 = t.as_u8_mut().unwrap();
            let mut map = tensor_u8.map().unwrap();
            let data = map.as_mut_slice();
            let half = width / 2;
            for y in 0..height {
                for x in 0..width {
                    let idx = (y * width + x) * 3;
                    if x < half {
                        data[idx] = 255;
                        data[idx + 1] = 0;
                        data[idx + 2] = 0;
                    } else {
                        data[idx] = 0;
                        data[idx + 1] = 0;
                        data[idx + 2] = 255;
                    }
                }
            }
        }
        t
    }

    /// Crop the blue (right) half of a red|blue image and resize to a smaller
    /// destination. Verify no red pixels bleed into the interior output.
    /// Edge pixels (first/last column) may have filter-radius bleed from the
    /// resize library; we skip those and validate the interior is pure blue.
    #[test]
    fn test_src_rect_crop_no_bleed_cpu() -> Result<()> {
        let src_w = 128;
        let src_h = 64;
        let dst_w = 32;
        let dst_h = 32;

        let src = make_red_blue_src(src_w, src_h);
        let mut dst = TensorDyn::image(
            dst_w,
            dst_h,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;

        let mut cpu = CPUProcessor::default();

        // Crop only the right (blue) half
        let crop = Crop::new().with_source(Some(Region::new(src_w / 2, 0, src_w / 2, src_h)));

        cpu.convert(&src, &mut dst, Rotation::None, Flip::None, crop)?;

        // Skip the leftmost 2 columns (resize filter radius at crop boundary)
        let map = dst.as_u8().unwrap().map()?;
        let data = map.as_slice();
        for y in 0..dst_h {
            for x in 2..dst_w {
                let i = y * dst_w + x;
                let r = data[i * 3];
                let g = data[i * 3 + 1];
                let b = data[i * 3 + 2];
                assert!(
                    r <= 2 && g <= 2 && b >= 253,
                    "CPU pixel ({x},{y}) has red bleed: RGB=({r},{g},{b}), expected pure blue"
                );
            }
        }
        Ok(())
    }

    /// Crop the red (left) half and verify no blue bleeds into the interior.
    #[test]
    fn test_src_rect_crop_left_half_no_bleed_cpu() -> Result<()> {
        let src_w = 128;
        let src_h = 64;
        let dst_w = 32;
        let dst_h = 32;

        let src = make_red_blue_src(src_w, src_h);
        let mut dst = TensorDyn::image(
            dst_w,
            dst_h,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;

        let mut cpu = CPUProcessor::default();

        // Crop only the left (red) half
        let crop = Crop::new().with_source(Some(Region::new(0, 0, src_w / 2, src_h)));

        cpu.convert(&src, &mut dst, Rotation::None, Flip::None, crop)?;

        // Skip the rightmost 2 columns (resize filter radius at crop boundary)
        let map = dst.as_u8().unwrap().map()?;
        let data = map.as_slice();
        for y in 0..dst_h {
            for x in 0..(dst_w - 2) {
                let i = y * dst_w + x;
                let r = data[i * 3];
                let g = data[i * 3 + 1];
                let b = data[i * 3 + 2];
                assert!(
                    r >= 253 && g <= 2 && b <= 2,
                    "CPU pixel ({x},{y}) has blue bleed: RGB=({r},{g},{b}), expected pure red"
                );
            }
        }
        Ok(())
    }

    /// Crop at the exact red→blue boundary and resize. Interior pixels
    /// (away from the crop edge) must be pure blue.
    #[test]
    fn test_src_rect_boundary_crop_no_bleed_cpu() -> Result<()> {
        let src_w = 256;
        let src_h = 64;
        let dst_w = 64;
        let dst_h = 64;

        let src = make_red_blue_src(src_w, src_h);
        let mut dst = TensorDyn::image(
            dst_w,
            dst_h,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;

        let mut cpu = CPUProcessor::default();

        // Crop the right half — boundary is exactly at the colour transition
        let crop = Crop::new().with_source(Some(Region::new(src_w / 2, 0, src_w / 2, src_h)));

        cpu.convert(&src, &mut dst, Rotation::None, Flip::None, crop)?;

        // Skip the leftmost 2 columns (filter radius near crop boundary)
        let map = dst.as_u8().unwrap().map()?;
        let data = map.as_slice();
        for y in 0..dst_h {
            for x in 2..dst_w {
                let i = y * dst_w + x;
                let r = data[i * 3];
                let g = data[i * 3 + 1];
                let b = data[i * 3 + 2];
                assert!(
                    r <= 2 && g <= 2 && b >= 253,
                    "CPU pixel ({x},{y}) contamination at boundary: RGB=({r},{g},{b})"
                );
            }
        }
        Ok(())
    }

    // =========================================================================
    // CPU F16/F32 float destination tests
    // =========================================================================

    /// RGBA8 → Rgb F32 identity (same dims, no resize): every output element
    /// must equal `src_byte as f32 / 255.0` exactly.
    #[test]
    fn cpu_convert_rgba_to_rgb_f32_identity() -> Result<()> {
        const W: usize = 4;
        const H: usize = 4;

        // Build a 4x4 RGBA source with a known per-pixel pattern.
        let src = TensorDyn::image(
            W,
            H,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        {
            let mut map = src.as_u8().unwrap().map()?;
            let data = map.as_mut_slice();
            for i in 0..W * H {
                data[i * 4] = (i * 10) as u8; // R
                data[i * 4 + 1] = (i * 10 + 3) as u8; // G
                data[i * 4 + 2] = (i * 10 + 7) as u8; // B
                data[i * 4 + 3] = 255; // A
            }
        }

        // Destination: Rgb F32 same size.
        let mut dst = TensorDyn::image(
            W,
            H,
            PixelFormat::Rgb,
            DType::F32,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        {
            let mut cv = CPUProcessor::default();
            cv.convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())?;
        }

        // Verify: dst[i*3+c] == src_u8[i*4+c] as f32 / 255.0 exactly.
        let src_map = src.as_u8().unwrap().map()?;
        let src_bytes = src_map.as_slice();
        let dst_map = dst.as_f32().unwrap().map()?;
        let dst_floats = dst_map.as_slice();

        assert_eq!(dst_floats.len(), W * H * 3, "wrong output element count");
        for i in 0..W * H {
            for c in 0..3 {
                let expected = src_bytes[i * 4 + c] as f32 / 255.0;
                let actual = dst_floats[i * 3 + c];
                assert_eq!(
                    actual, expected,
                    "pixel {i} channel {c}: got {actual}, expected {expected}"
                );
            }
        }
        Ok(())
    }

    /// RGBA8 → PlanarRgb F16 identity: verify [0,1] normalization within F16
    /// rounding tolerance (2^-9 ≈ 1/512), and verify planar (channel-major)
    /// layout — distinct R/G/B values land in the correct plane.
    #[test]
    fn cpu_convert_rgba_to_planar_rgb_f16_identity() -> Result<()> {
        const W: usize = 4;
        const H: usize = 4;

        // Use clearly distinct per-channel values to catch plane-swap bugs.
        // pixel (y,x): R = 50+x, G = 100+y*10, B = 200
        let src = TensorDyn::image(
            W,
            H,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        {
            let mut map = src.as_u8().unwrap().map()?;
            let data = map.as_mut_slice();
            for y in 0..H {
                for x in 0..W {
                    let i = y * W + x;
                    data[i * 4] = (50 + x) as u8; // R
                    data[i * 4 + 1] = (100 + y * 10) as u8; // G
                    data[i * 4 + 2] = 200; // B
                    data[i * 4 + 3] = 255; // A
                }
            }
        }

        // Destination: PlanarRgb F16 same size.
        let mut dst = TensorDyn::image(
            W,
            H,
            PixelFormat::PlanarRgb,
            DType::F16,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        {
            let mut cv = CPUProcessor::default();
            cv.convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())?;
        }

        // F16 tolerance: 2^-9 ≈ 0.00195 (one ULP at 0.5 for f16 with 10-bit mantissa)
        let tol = 2.0_f32.powi(-9);

        let src_map = src.as_u8().unwrap().map()?;
        let src_bytes = src_map.as_slice();
        let dst_map = dst.as_f16().unwrap().map()?;
        let dst_halfs = dst_map.as_slice();

        // PlanarRgb layout: [R_plane W*H, G_plane W*H, B_plane W*H]
        let plane = W * H;
        assert_eq!(dst_halfs.len(), plane * 3, "wrong output element count");

        for y in 0..H {
            for x in 0..W {
                let i = y * W + x;
                let r_expected = src_bytes[i * 4] as f32 / 255.0;
                let g_expected = src_bytes[i * 4 + 1] as f32 / 255.0;
                let b_expected = src_bytes[i * 4 + 2] as f32 / 255.0;

                let r_actual = dst_halfs[i].to_f32(); // R plane
                let g_actual = dst_halfs[plane + i].to_f32(); // G plane
                let b_actual = dst_halfs[2 * plane + i].to_f32(); // B plane

                assert!(
                    (r_actual - r_expected).abs() <= tol,
                    "R plane pixel ({x},{y}): got {r_actual}, expected {r_expected}"
                );
                assert!(
                    (g_actual - g_expected).abs() <= tol,
                    "G plane pixel ({x},{y}): got {g_actual}, expected {g_expected}"
                );
                assert!(
                    (b_actual - b_expected).abs() <= tol,
                    "B plane pixel ({x},{y}): got {b_actual}, expected {b_expected}"
                );

                // Verify planar layout: R/G/B must be distinct (not the same value
                // copied to all planes).
                let r_byte = src_bytes[i * 4];
                let g_byte = src_bytes[i * 4 + 1];
                let b_byte = src_bytes[i * 4 + 2];
                if r_byte != g_byte {
                    assert_ne!(
                        r_actual, g_actual,
                        "R and G planes must differ at ({x},{y})"
                    );
                }
                if g_byte != b_byte {
                    assert_ne!(
                        g_actual, b_actual,
                        "G and B planes must differ at ({x},{y})"
                    );
                }
            }
        }
        Ok(())
    }

    /// Exercises the `widen_scratch` cache in `convert_dtype`'s U8→float arm:
    /// the first convert allocates+stores the scratch, a second convert at the
    /// same dst format/size takes the cache-hit branch, and a third at a
    /// different size takes the reallocate branch. A single-convert test (as
    /// all the others are) never reaches the cache-hit/realloc paths.
    #[test]
    fn cpu_widen_scratch_reused_across_converts() -> Result<()> {
        fn rgba(w: usize, h: usize) -> Result<TensorDyn> {
            let src = TensorDyn::image(
                w,
                h,
                PixelFormat::Rgba,
                DType::U8,
                Some(TensorMemory::Mem),
                edgefirst_tensor::CpuAccess::ReadWrite,
            )?;
            {
                let mut map = src.as_u8().unwrap().map()?;
                let data = map.as_mut_slice();
                for (i, px) in data.chunks_exact_mut(4).enumerate() {
                    px[0] = (i * 7) as u8;
                    px[1] = (i * 7 + 1) as u8;
                    px[2] = (i * 7 + 2) as u8;
                    px[3] = 255;
                }
            }
            Ok(src)
        }

        // One processor instance so the scratch cache persists across calls.
        let mut cv = CPUProcessor::default();

        let src4 = rgba(4, 4)?;
        let mut dst_a = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::F32,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        let mut dst_b = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::F32,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;

        // 1st convert: scratch is None → allocate + cache.
        cv.convert(
            &src4,
            &mut dst_a,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;
        // 2nd convert, same dst format+size → cache-hit branch (reuse scratch).
        cv.convert(
            &src4,
            &mut dst_b,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;

        // Both results must be identical and correctly normalized.
        let a = dst_a.as_f32().unwrap().map()?;
        let b = dst_b.as_f32().unwrap().map()?;
        assert_eq!(
            a.as_slice(),
            b.as_slice(),
            "cache-hit produced different output"
        );

        // 3rd convert at a different size → scratch mismatch → realloc branch.
        let src8 = rgba(8, 8)?;
        let mut dst_c = TensorDyn::image(
            8,
            8,
            PixelFormat::Rgb,
            DType::F32,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        cv.convert(
            &src8,
            &mut dst_c,
            Rotation::None,
            Flip::None,
            Crop::default(),
        )?;
        let c = dst_c.as_f32().unwrap().map()?;
        assert_eq!(c.as_slice().len(), 8 * 8 * 3);
        assert!(c.as_slice().iter().all(|v| (0.0..=1.0).contains(v)));
        Ok(())
    }

    /// `convert_dtype` returns `NotAnImage` when the destination tensor has no
    /// pixel format (a bare, non-image tensor), rather than panicking.
    #[test]
    fn cpu_convert_dst_without_format_errors() -> Result<()> {
        let src = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        // A plain tensor with no image format set.
        let mut dst = TensorDyn::new(&[4, 4, 3], DType::F32, Some(TensorMemory::Mem), None)?;
        let mut cv = CPUProcessor::default();
        let err = cv
            .convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())
            .unwrap_err();
        assert!(
            matches!(err, Error::NotAnImage),
            "expected NotAnImage, got {err:?}"
        );
        Ok(())
    }

    /// RGBA8 → Rgb F32 with downscale (8x8 → 4x4): output must be in [0,1]
    /// and finite; a flat-color region survives resize exactly.
    #[test]
    fn cpu_convert_rgba_to_rgb_f32_resize() -> Result<()> {
        const SW: usize = 8;
        const SH: usize = 8;
        const DW: usize = 4;
        const DH: usize = 4;

        // Build an 8x8 source: right half (x >= 4) is solid blue [0,0,255,255].
        let src = TensorDyn::image(
            SW,
            SH,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        {
            let mut map = src.as_u8().unwrap().map()?;
            let data = map.as_mut_slice();
            for y in 0..SH {
                for x in 0..SW {
                    let i = y * SW + x;
                    if x >= 4 {
                        // Solid blue in the right half
                        data[i * 4] = 0;
                        data[i * 4 + 1] = 0;
                        data[i * 4 + 2] = 255;
                        data[i * 4 + 3] = 255;
                    } else {
                        data[i * 4] = 128;
                        data[i * 4 + 1] = 64;
                        data[i * 4 + 2] = 32;
                        data[i * 4 + 3] = 255;
                    }
                }
            }
        }

        let mut dst = TensorDyn::image(
            DW,
            DH,
            PixelFormat::Rgb,
            DType::F32,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )?;
        {
            let mut cv = CPUProcessor::default();
            cv.convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())?;
        }

        let dst_map = dst.as_f32().unwrap().map()?;
        let dst_floats = dst_map.as_slice();

        assert_eq!(dst_floats.len(), DW * DH * 3, "wrong output element count");

        // All values must be in [0, 1] and finite.
        for (i, &v) in dst_floats.iter().enumerate() {
            assert!(
                v.is_finite() && (0.0..=1.0).contains(&v),
                "dst[{i}] = {v} is out of [0,1] or non-finite"
            );
        }

        // The rightmost column (x=3 in 4x4) maps to src pixels x=6..7 which
        // are entirely inside the solid-blue right half — bilinear resize of a
        // flat region is exact.
        for y in 0..DH {
            let x = DW - 1; // x=3
            let i = y * DW + x;
            let r = dst_floats[i * 3];
            let g = dst_floats[i * 3 + 1];
            let b = dst_floats[i * 3 + 2];
            assert_eq!(r, 0.0, "rightmost R must be 0.0 at ({x},{y})");
            assert_eq!(g, 0.0, "rightmost G must be 0.0 at ({x},{y})");
            assert_eq!(b, 1.0, "rightmost B must be 1.0 at ({x},{y})");
        }

        // The left src half is [128, 64, 32] -> normalised [~0.502, ~0.251, ~0.125].
        // x=0 in the 4x4 output maps to src x=0 whose bilinear kernel sits
        // entirely within the left half — bilinear resize of a flat region is
        // exact, so the tolerance just absorbs the f32 /255 rounding.  A zero-
        // filled or miscopied left region would produce 0.0 here and be caught.
        // (x=1 already blends with right-half blue due to the resampler's broad
        // kernel reaching across the seam at src x=4.)
        for y in 0..DH {
            let i = (y * DW) * 3; // x=0
            assert!(
                (dst_floats[i] - 128.0 / 255.0).abs() < 0.02,
                "left R y={y}: {}",
                dst_floats[i]
            );
            assert!(
                (dst_floats[i + 1] - 64.0 / 255.0).abs() < 0.02,
                "left G y={y}: {}",
                dst_floats[i + 1]
            );
            assert!(
                (dst_floats[i + 2] - 32.0 / 255.0).abs() < 0.02,
                "left B y={y}: {}",
                dst_floats[i + 2]
            );
        }
        Ok(())
    }

    #[test]
    fn cpu_nv12_to_rgb_respects_tagged_709_vs_601() {
        use edgefirst_tensor::{ColorEncoding, ColorRange, Colorimetry};
        let make = |enc| {
            // 2x2 NV12: 4 luma + 1 UV pair (U=200,V=40) — saturated chroma so 601≠709.
            let mut src = load_bytes_to_tensor(
                2,
                2,
                PixelFormat::Nv12,
                None,
                &[180, 180, 180, 180, 200, 40],
            )
            .unwrap();
            src.set_colorimetry(Some(
                Colorimetry::default()
                    .with_encoding(enc)
                    .with_range(ColorRange::Limited),
            ));
            let mut dst = TensorDyn::image(
                2,
                2,
                PixelFormat::Rgb,
                DType::U8,
                None,
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            CPUProcessor::default()
                .convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())
                .unwrap();
            dst.as_u8().unwrap().map().unwrap().as_slice().to_vec()
        };
        assert_ne!(make(ColorEncoding::Bt601), make(ColorEncoding::Bt709));
    }

    #[test]
    fn cpu_nv16_to_rgb_respects_tagged_709_vs_601() {
        use edgefirst_tensor::{ColorEncoding, ColorRange, Colorimetry};
        let make = |enc| {
            // 2x2 NV16 (4:2:2): 4 luma + full-height half-width chroma = 2 rows
            // × 1 (Cb,Cr) pair = 4 chroma bytes (U=200,V=40, saturated so 601≠709).
            let mut src = load_bytes_to_tensor(
                2,
                2,
                PixelFormat::Nv16,
                None,
                &[180, 180, 180, 180, 200, 40, 200, 40],
            )
            .unwrap();
            src.set_colorimetry(Some(
                Colorimetry::default()
                    .with_encoding(enc)
                    .with_range(ColorRange::Limited),
            ));
            let mut dst = TensorDyn::image(
                2,
                2,
                PixelFormat::Rgb,
                DType::U8,
                None,
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            CPUProcessor::default()
                .convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())
                .unwrap();
            dst.as_u8().unwrap().map().unwrap().as_slice().to_vec()
        };
        assert_ne!(make(ColorEncoding::Bt601), make(ColorEncoding::Bt709));
    }

    #[test]
    fn cpu_nv24_to_rgb_respects_tagged_709_vs_601() {
        use edgefirst_tensor::{ColorEncoding, ColorRange, Colorimetry};
        let make = |enc| {
            // 2x2 NV24 (4:4:4): 4 luma + full-res chroma = 4 (Cb,Cr) pairs = 8
            // chroma bytes (U=200,V=40, saturated so 601≠709).
            let mut src = load_bytes_to_tensor(
                2,
                2,
                PixelFormat::Nv24,
                None,
                &[180, 180, 180, 180, 200, 40, 200, 40, 200, 40, 200, 40],
            )
            .unwrap();
            src.set_colorimetry(Some(
                Colorimetry::default()
                    .with_encoding(enc)
                    .with_range(ColorRange::Limited),
            ));
            let mut dst = TensorDyn::image(
                2,
                2,
                PixelFormat::Rgb,
                DType::U8,
                None,
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            CPUProcessor::default()
                .convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())
                .unwrap();
            dst.as_u8().unwrap().map().unwrap().as_slice().to_vec()
        };
        assert_ne!(make(ColorEncoding::Bt601), make(ColorEncoding::Bt709));
    }

    #[test]
    fn cpu_convert_tagged_jfif_differs_from_untagged_heuristic_nv12() {
        use edgefirst_tensor::{ColorEncoding, ColorRange, Colorimetry};
        // Same 2x2 NV12 bytes — saturated chroma so matrix/range choice matters.
        // NV12 2x2 = 4 Y-plane bytes + 2 UV-plane bytes = 6 total.
        let bytes = [180u8, 180, 180, 180, 200, 40];
        let convert = |cm: Option<Colorimetry>| {
            let mut src = load_bytes_to_tensor(2, 2, PixelFormat::Nv12, None, &bytes).unwrap();
            src.set_colorimetry(cm);
            let mut dst = TensorDyn::image(
                2,
                2,
                PixelFormat::Rgb,
                DType::U8,
                None,
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            CPUProcessor::default()
                .convert(&src, &mut dst, Rotation::None, Flip::None, Crop::default())
                .unwrap();
            dst.as_u8().unwrap().map().unwrap().as_slice().to_vec()
        };
        // Tagged JFIF (BT.601 full-range) — what the codec sets for JPEG.
        let jfif = convert(Some(Colorimetry::jfif()));
        // Untagged: 2x2 height is below HD_THRESHOLD (720) → heuristic resolves
        // to BT.601 LIMITED.  JFIF is BT.601 FULL, so the two must differ.
        let untagged = convert(None);
        assert_ne!(
            jfif, untagged,
            "JFIF (BT.601 full-range) must differ from heuristic (BT.601 limited)"
        );
        // An explicitly-tagged BT.709-limited must also differ from BT.601 JFIF.
        let bt709 = convert(Some(
            Colorimetry::default()
                .with_encoding(ColorEncoding::Bt709)
                .with_range(ColorRange::Limited),
        ));
        assert_ne!(jfif, bt709, "BT.601-full must differ from BT.709-limited");
    }

    #[test]
    fn cpu_convert_into_heap_subviews_no_aliasing() {
        // Two distinct RGBA sources converted into two RGB sub-views of one
        // heap parent buffer. Each window must bit-match a standalone convert
        // of its source — proving the CPU convert path honors the heap
        // plane_offset with no aliasing. Runs on CI with no GPU/NPU.
        let mut converter = CPUProcessor::default();

        let mut src0 = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        src0.as_u8_mut()
            .unwrap()
            .map()
            .unwrap()
            .as_mut_slice()
            .fill(50);
        let mut src1 = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        src1.as_u8_mut()
            .unwrap()
            .map()
            .unwrap()
            .as_mut_slice()
            .fill(200);

        let mut do_convert = |src: &TensorDyn, dst: &mut TensorDyn| {
            converter
                .convert(src, dst, Rotation::None, Flip::None, Crop::default())
                .unwrap();
        };

        // Standalone reference conversions into full, independent buffers.
        let mut ref0 = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        do_convert(&src0, &mut ref0);
        let mut ref1 = TensorDyn::image(
            4,
            4,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        do_convert(&src1, &mut ref1);

        // One RGB parent holding two stacked 4x4 frames (4 wide, 8 tall). The
        // sub-views inherit the Rgb format, so each is a ready convert target
        // and the plane offset survives.
        let frame = 4 * 4 * 3;
        let parent = TensorDyn::image(
            4,
            8,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        let mut view0 = parent.view(Region::new(0, 0, 4, 4)).unwrap();
        let mut view1 = parent.view(Region::new(0, 4, 4, 4)).unwrap();
        assert_eq!(view1.plane_offset(), Some(frame));

        do_convert(&src0, &mut view0);
        do_convert(&src1, &mut view1);

        let parent_bytes = parent.as_u8().unwrap().map().unwrap().to_vec();
        let ref0_bytes = ref0.as_u8().unwrap().map().unwrap().to_vec();
        let ref1_bytes = ref1.as_u8().unwrap().map().unwrap().to_vec();
        assert_eq!(
            &parent_bytes[..frame],
            ref0_bytes.as_slice(),
            "view 0 window must match a standalone convert of src0"
        );
        assert_eq!(
            &parent_bytes[frame..2 * frame],
            ref1_bytes.as_slice(),
            "view 1 window must match a standalone convert of src1"
        );
    }

    /// A *real* resize (not a same-size format conversion) into a padded
    /// destination view must land each row at the view's stride, not a
    /// tight `dst_w * channels` pitch. Regression coverage for the
    /// `(Rotation::None, Flip::None)` resize branch, which used to build its
    /// `fast_image_resize::images::Image` straight from the padded map
    /// (implicitly tight), smearing later rows across the padding.
    #[test]
    fn resize_into_padded_view_matches_standalone() {
        let tile_w = 320usize;
        let tile_h = 240usize;
        let channels = 3usize; // PixelFormat::Rgb

        // 640x480 Rgb source with non-uniform, deterministic content so a
        // row-stride mismatch shows up as a byte mismatch rather than
        // silently comparing padding zeros to padding zeros.
        let mut src = TensorDyn::image(
            640,
            480,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let mut m = src.as_u8_mut().unwrap().map().unwrap();
            for (i, b) in m.as_mut_slice().iter_mut().enumerate() {
                *b = (i % 251) as u8;
            }
        }

        let mut converter = CPUProcessor::default();
        let mut do_convert = |dst: &mut TensorDyn| {
            converter
                .convert(&src, dst, Rotation::None, Flip::None, Crop::default())
                .unwrap();
        };

        // Reference: standalone tight 320x240 destination.
        let mut reference = TensorDyn::image(
            tile_w,
            tile_h,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        do_convert(&mut reference);
        let reference_bytes = reference.as_u8().unwrap().map().unwrap().to_vec();

        // Parent: allocate wider than the tile (real spare capacity), narrow
        // the logical width back to `tile_w` via `configure_image` (which
        // keeps the wider physical allocation), then record a row stride
        // padded +16 bytes past the tight `tile_w * channels` pitch — the
        // shape a DMA pitch-aligned destination would present.
        let alloc_w = tile_w + 64;
        let mut parent = TensorDyn::image(
            alloc_w,
            2 * tile_h,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Mem),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        parent
            .configure_image(tile_w, 2 * tile_h, PixelFormat::Rgb)
            .unwrap();
        let padded_stride = tile_w * channels + 16;
        parent.set_row_stride(padded_stride).unwrap();

        // Second band: rows [tile_h, 2*tile_h) of the padded parent.
        let mut view = parent.view(Region::new(0, tile_h, tile_w, tile_h)).unwrap();
        do_convert(&mut view);

        // Walk the view's window at the parent's real stride, comparing
        // each row's tight `width * channels` bytes (skipping the padding)
        // against the standalone reference.
        let parent_bytes = parent.as_u8().unwrap().map().unwrap().to_vec();
        let band_offset = tile_h * padded_stride;
        let tight_row = tile_w * channels;
        for row in 0..tile_h {
            let parent_row_start = band_offset + row * padded_stride;
            let parent_row = &parent_bytes[parent_row_start..parent_row_start + tight_row];
            let ref_row = &reference_bytes[row * tight_row..(row + 1) * tight_row];
            assert_eq!(
                parent_row, ref_row,
                "row {row} of the padded destination view must match the standalone convert"
            );
        }
    }

    // ---- Task 3: fused NV→planar source region + scale-identity gate ----

    /// Decode `full` (a whole-frame NV12→PlanarRgb convert, no crop) once and
    /// slice each colour plane down to `region` by hand, entirely without
    /// invoking any cropped-convert code path. This is the ground-truth
    /// oracle both `fused_region_matches_general_path` and
    /// `odd_origin_nv12_crop_falls_through` compare against.
    fn manual_planar_rgb_crop(full: &TensorDyn, region: Region) -> Vec<u8> {
        let full_w = full.width().unwrap();
        let full_h = full.height().unwrap();
        let full_bytes = full.as_u8().unwrap().map().unwrap().to_vec();
        let plane_full = full_w * full_h;
        let plane_dst = region.width * region.height;
        let mut out = vec![0u8; plane_dst * 3];
        for p in 0..3 {
            let src_plane = &full_bytes[p * plane_full..(p + 1) * plane_full];
            let dst_plane = &mut out[p * plane_dst..(p + 1) * plane_dst];
            for row in 0..region.height {
                let s_off = (region.y + row) * full_w + region.x;
                let d_off = row * region.width;
                dst_plane[d_off..d_off + region.width]
                    .copy_from_slice(&src_plane[s_off..s_off + region.width]);
            }
        }
        out
    }

    /// Full-frame (no-crop) NV12→PlanarRgb convert of `camera720p.nv12` —
    /// the source both new tests below slice down to a sub-region by hand.
    ///
    /// Note this itself already routes through `convert_nv_to_planar_fused`
    /// (with `region: None` — the pre-existing whole-frame gate, unchanged
    /// by this task), not some independently-implemented "general path"
    /// decode. It's still a valid oracle for `fused_region_matches_general_path`
    /// because that test's *only* claim is that the fused function's
    /// `region: Some(r)` strip arithmetic reproduces exactly what its own
    /// `region: None` whole-frame arithmetic computes for the same pixels —
    /// i.e. that the region offsets are correct, not that the fused decode
    /// numerically matches the separate `convert_format_pf` pipeline (which
    /// `odd_origin_nv12_crop_falls_through` exercises independently against
    /// this same oracle, and which the frozen `crop_golden` fixtures pin
    /// byte-for-byte as the ultimate independent check).
    fn nv12_720p_to_planar_rgb_full(converter: &mut CPUProcessor) -> (TensorDyn, TensorDyn) {
        let src = load_bytes_to_tensor(
            1280,
            720,
            PixelFormat::Nv12,
            None,
            &edgefirst_bench::testdata::read("camera720p.nv12"),
        )
        .unwrap();
        let mut full = TensorDyn::image(
            1280,
            720,
            PixelFormat::PlanarRgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        converter
            .convert(&src, &mut full, Rotation::None, Flip::None, Crop::default())
            .unwrap();
        (src, full)
    }

    /// A source crop whose size equals the destination (scale identity) with
    /// an even (chroma-aligned) origin must take the fused NV→planar strip
    /// path and produce output identical to decoding the whole frame once
    /// and manually slicing the same sub-rectangle out of each plane (see
    /// `nv12_720p_to_planar_rgb_full`'s doc for exactly what this oracle
    /// does and doesn't independently prove).
    #[test]
    fn fused_region_matches_general_path() {
        let mut converter = CPUProcessor::default();
        let (src, full) = nv12_720p_to_planar_rgb_full(&mut converter);
        let region = Region::new(256, 128, 640, 360); // scale identity, even origin
        let reference = manual_planar_rgb_crop(&full, region);

        let mut cropped = TensorDyn::image(
            640,
            360,
            PixelFormat::PlanarRgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        let crop = Crop::new().with_source(Some(region));
        converter
            .convert(&src, &mut cropped, Rotation::None, Flip::None, crop)
            .unwrap();

        let actual = cropped.as_u8().unwrap().map().unwrap().to_vec();
        assert_eq!(
            actual, reference,
            "fused NV12->PlanarRgb region convert must match the full-decode \
             + manual plane crop reference byte-for-byte"
        );
    }

    /// The same scale-identity, chroma-aligned crop as above must actually
    /// take the fused path — asserted via the test-only `fused_hits` counter
    /// rather than by timing, so the path selection itself is under test.
    #[test]
    fn scale_identity_crop_takes_fused_path() {
        let mut converter = CPUProcessor::default();
        let src = load_bytes_to_tensor(
            1280,
            720,
            PixelFormat::Nv12,
            None,
            &edgefirst_bench::testdata::read("camera720p.nv12"),
        )
        .unwrap();
        let mut cropped = TensorDyn::image(
            640,
            360,
            PixelFormat::PlanarRgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        let crop = Crop::new().with_source(Some(Region::new(256, 128, 640, 360)));

        let before = converter.fused_hits();
        converter
            .convert(&src, &mut cropped, Rotation::None, Flip::None, crop)
            .unwrap();
        assert_eq!(
            converter.fused_hits(),
            before + 1,
            "scale-identity, chroma-aligned crop must take the fused NV->planar path"
        );
    }

    /// An odd-origin NV12 crop (odd left AND top) fails the NV12 chroma-
    /// alignment gate and must fall through to the general path — never
    /// snapped to the nearest even origin, never shifted. The output must
    /// still be correct.
    #[test]
    fn odd_origin_nv12_crop_falls_through() {
        let mut converter = CPUProcessor::default();
        let (src, full) = nv12_720p_to_planar_rgb_full(&mut converter);
        let region = Region::new(257, 129, 640, 360); // odd left AND top
        let reference = manual_planar_rgb_crop(&full, region);

        let mut cropped = TensorDyn::image(
            640,
            360,
            PixelFormat::PlanarRgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        let crop = Crop::new().with_source(Some(region));

        let before = converter.fused_hits();
        converter
            .convert(&src, &mut cropped, Rotation::None, Flip::None, crop)
            .unwrap();
        assert_eq!(
            converter.fused_hits(),
            before,
            "odd-origin NV12 crop must never take the fused path (chroma \
             alignment requires even left/top) — never snap, never shift"
        );

        let actual = cropped.as_u8().unwrap().map().unwrap().to_vec();
        assert_eq!(
            actual, reference,
            "general-path output for the odd-origin crop must still be correct"
        );
    }

    /// Regression: a scale-identity, chroma-aligned (even left/top) crop
    /// whose *width* is odd used to error out of the fused NV12/NV16 region
    /// path (`YuvError::ChromaPlaneMinimumSizeMismatch`). The `yuv` crate
    /// needs `width.div_ceil(2) * 2` chroma bytes per row — a full trailing
    /// U+V pair for the odd column's fractional pair, not `width` bytes —
    /// but the packed UV scratch was sized to exactly `out_w`, one byte
    /// short. Covers both NV12 (4:2:0) and NV16 (4:2:2): both pack one U+V
    /// byte pair per two luma columns and so share the same rounding need.
    #[test]
    fn odd_width_scale_identity_crop_takes_fused_path_and_is_correct() {
        for (src_fmt, asset) in [
            (PixelFormat::Nv12, "camera720p.nv12"),
            (PixelFormat::Nv16, "camera720p.nv16"),
        ] {
            let mut converter = CPUProcessor::default();
            let src = load_bytes_to_tensor(
                1280,
                720,
                src_fmt,
                None,
                &edgefirst_bench::testdata::read(asset),
            )
            .unwrap();
            let mut full = TensorDyn::image(
                1280,
                720,
                PixelFormat::PlanarRgb,
                DType::U8,
                mem(),
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            converter
                .convert(&src, &mut full, Rotation::None, Flip::None, Crop::default())
                .unwrap();

            // Even left/top (chroma-aligned) but an ODD width — the shape
            // that used to crash.
            let region = Region::new(256, 128, 641, 360);
            let reference = manual_planar_rgb_crop(&full, region);

            let mut cropped = TensorDyn::image(
                region.width,
                region.height,
                PixelFormat::PlanarRgb,
                DType::U8,
                mem(),
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            let crop = Crop::new().with_source(Some(region));

            let before = converter.fused_hits();
            converter
                .convert(&src, &mut cropped, Rotation::None, Flip::None, crop)
                .unwrap_or_else(|e| {
                    panic!("{src_fmt:?} odd-width scale-identity crop must not error: {e}")
                });
            assert_eq!(
                converter.fused_hits(),
                before + 1,
                "{src_fmt:?} odd-width, chroma-aligned crop must still take the fused path"
            );

            let actual = cropped.as_u8().unwrap().map().unwrap().to_vec();
            assert_eq!(
                actual, reference,
                "{src_fmt:?} odd-width fused region output must match the \
                 full-decode + manual plane crop reference"
            );
        }
    }

    /// `region.left == 0` crops exercise the fused path's zero-copy arm (no
    /// y/uv row packing — the read slices the parent planes at a row
    /// boundary) and its one mandatory exception. Cases:
    ///
    /// - NV12 flush-bottom, even height: zero-copy; the region's last
    ///   luma/chroma rows are the planes' last rows, so any stride-chunking
    ///   past a row's true end (the bug the packing arm exists to avoid for
    ///   column-shifted crops) would read out of bounds or drop rows here.
    /// - NV12 odd width, even height: zero-copy; the chroma read covers the
    ///   trailing half-pair byte from the parent stride.
    /// - NV12 odd width AND odd height, not flush-bottom: MUST fall back to
    ///   the packing arm — the `yuv` crate's 4:2:0 odd-last-row handling
    ///   (`chunks_exact(..).remainder()` / `.last()`) is only correct on a
    ///   slice of exactly `height` rows, which a row-aligned slice running
    ///   to the plane end is not. Without the fallback this case panics
    ///   inside the crate ("range end index 641 out of range").
    /// - NV16 odd width/height: zero-copy is safe at any height (4:2:2 has
    ///   no vertical subsampling and no remainder path).
    ///
    /// All must stay fused. Even-height NV12 cases and NV16 are byte-exact
    /// against the full-decode + manual plane crop oracle on every CPU. The
    /// odd-height NV12 case compares its LAST row with a small tolerance
    /// instead: an odd-height region decodes its final row through the
    /// crate's halved-chroma-row kernel, while the even-height full-frame
    /// oracle rendered that same source row through the paired kernel — and
    /// on the plain-NEON (non-RDM) path those two kernels round ±1
    /// differently (observed on i.MX 8M Plus Cortex-A53), so bit-equality
    /// with this oracle is unattainable there by construction. All rows
    /// before the last stay byte-exact, which still pins the addressing.
    #[test]
    fn left_edge_crop_zero_copy_arm_is_fused_and_correct() {
        for (src_fmt, asset, region, last_row_tol, label) in [
            (
                PixelFormat::Nv12,
                "camera720p.nv12",
                Region::new(0, 80, 640, 640),
                0u8,
                "nv12 flush-bottom",
            ),
            (
                PixelFormat::Nv12,
                "camera720p.nv12",
                Region::new(0, 0, 641, 360),
                0u8,
                "nv12 odd-width even-height",
            ),
            (
                PixelFormat::Nv12,
                "camera720p.nv12",
                Region::new(0, 0, 641, 361),
                2u8,
                "nv12 odd-width odd-height",
            ),
            (
                PixelFormat::Nv16,
                "camera720p.nv16",
                Region::new(0, 0, 641, 361),
                0u8,
                "nv16 odd-width odd-height",
            ),
        ] {
            let mut converter = CPUProcessor::default();
            let src = load_bytes_to_tensor(
                1280,
                720,
                src_fmt,
                None,
                &edgefirst_bench::testdata::read(asset),
            )
            .unwrap();
            let mut full = TensorDyn::image(
                1280,
                720,
                PixelFormat::PlanarRgb,
                DType::U8,
                mem(),
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            converter
                .convert(&src, &mut full, Rotation::None, Flip::None, Crop::default())
                .unwrap();
            let reference = manual_planar_rgb_crop(&full, region);

            let mut cropped = TensorDyn::image(
                region.width,
                region.height,
                PixelFormat::PlanarRgb,
                DType::U8,
                mem(),
                edgefirst_tensor::CpuAccess::ReadWrite,
            )
            .unwrap();
            let crop = Crop::new().with_source(Some(region));

            let before = converter.fused_hits();
            converter
                .convert(&src, &mut cropped, Rotation::None, Flip::None, crop)
                .unwrap_or_else(|e| panic!("left-edge {label} crop must not error: {e}"));
            assert_eq!(
                converter.fused_hits(),
                before + 1,
                "left-edge {label} crop must take the fused path"
            );

            let actual = cropped.as_u8().unwrap().map().unwrap().to_vec();
            if last_row_tol == 0 {
                assert_eq!(
                    actual, reference,
                    "left-edge {label} region output must match the \
                     full-decode + manual plane crop reference"
                );
            } else {
                // Odd-height NV12: all rows but the last are byte-exact; the
                // last row tolerates the paired-vs-halved chroma kernel
                // rounding delta (see the test doc).
                let (w, h) = (region.width, region.height);
                let plane = w * h;
                for p in 0..3 {
                    for row in 0..h {
                        let off = p * plane + row * w;
                        let (a, r) = (&actual[off..off + w], &reference[off..off + w]);
                        if row + 1 < h {
                            assert_eq!(
                                a, r,
                                "left-edge {label}: plane {p} row {row} must be byte-exact"
                            );
                        } else {
                            for (i, (x, y)) in a.iter().zip(r).enumerate() {
                                assert!(
                                    (i16::from(*x) - i16::from(*y)).abs() <= i16::from(last_row_tol),
                                    "left-edge {label}: plane {p} last row byte {i}: {x} vs {y} exceeds tolerance {last_row_tol}"
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    /// Build a `w`x`h` tensor in `fmt` whose every mapped byte follows a
    /// deterministic gradient, so neighbouring pixels differ and any misplaced
    /// filter tap shows up as a byte difference.
    fn gradient_image(w: usize, h: usize, fmt: PixelFormat) -> TensorDyn {
        let t = TensorDyn::image(
            w,
            h,
            fmt,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let u8t = t.as_u8().unwrap();
            let mut map = u8t.map_mut().unwrap();
            for (i, b) in map.as_mut_slice().iter_mut().enumerate() {
                *b = ((i * 7 + i / w * 13) & 0xFF) as u8;
            }
        }
        t
    }

    /// The crop-sized pre-resize intermediate must be byte-identical to the
    /// pre-Task-4 full-frame intermediate for crops flush against every frame
    /// edge — the cases where the halo clamps against the frame bounds instead
    /// of finding real neighbouring pixels.
    ///
    /// The reference is the old algorithm rebuilt from the public API: convert
    /// the whole frame once into the packed-RGB intermediate, then apply the
    /// same crop+resize to *that* tensor. `Rgb -> Rgb` needs no intermediate,
    /// so the reference convert runs the identical resize against a full-frame
    /// source — exactly what the NV source used to do internally. Any halo
    /// arithmetic error (too small, mis-snapped, or mis-rebased) makes the two
    /// differ. This lives here rather than in `tests/crop_golden.rs` because it
    /// also asserts the shrink actually happened, via the crate-private
    /// `last_tmp_dims`, which an integration test cannot reach.
    ///
    /// Run for both resize algorithms: the golden matrix only ever builds a
    /// `default()` (bilinear) processor, so `new_nearest()` — the one algorithm
    /// with a genuinely zero filter reach — has no other coverage here.
    #[test]
    fn crop_edge_matches_full_frame_intermediate() {
        const SRC_W: usize = 640;
        const SRC_H: usize = 480;
        const CW: usize = 128;
        const CH: usize = 96;

        for alg in ["bilinear", "nearest"] {
            for src_fmt in [PixelFormat::Nv12, PixelFormat::Nv16, PixelFormat::Nv24] {
                let mut converter = match alg {
                    "nearest" => CPUProcessor::new_nearest(),
                    _ => CPUProcessor::default(),
                };
                let src = gradient_image(SRC_W, SRC_H, src_fmt);

                // The pre-Task-4 intermediate: the whole frame, converted once.
                let mut full = gradient_image(SRC_W, SRC_H, PixelFormat::Rgb);
                converter
                    .convert(&src, &mut full, Rotation::None, Flip::None, Crop::default())
                    .unwrap();

                let origins = [
                    (0, 0),                   // top-left corner
                    (SRC_W - CW, 0),          // top-right, flush right
                    (0, SRC_H - CH),          // bottom-left, flush bottom
                    (SRC_W - CW, SRC_H - CH), // bottom-right, flush both
                    (101, 53),                // interior, odd on both axes
                ];
                for (left, top) in origins {
                    for (dst_w, dst_h) in [(CW, CH), (CW / 2, CH / 2)] {
                        let crop = Crop::new()
                            .with_source(Some(Region::new(left, top, CW, CH)))
                            .with_fit(crate::Fit::Stretch);

                        let mut actual = gradient_image(dst_w, dst_h, PixelFormat::Rgb);
                        converter
                            .convert(&src, &mut actual, Rotation::None, Flip::None, crop)
                            .unwrap();
                        let dims = converter.last_tmp_dims();

                        let mut expect = gradient_image(dst_w, dst_h, PixelFormat::Rgb);
                        converter
                            .convert(&full, &mut expect, Rotation::None, Flip::None, crop)
                            .unwrap();

                        let case = format!(
                            "{alg} {src_fmt:?} crop=({left},{top},{CW},{CH}) dst={dst_w}x{dst_h}"
                        );
                        assert_eq!(
                            actual.as_u8().unwrap().map().unwrap().to_vec(),
                            expect.as_u8().unwrap().map().unwrap().to_vec(),
                            "crop-sized intermediate changed output bytes for {case}"
                        );

                        // ...and the intermediate really did shrink to the crop.
                        let (tw, th) = dims.unwrap_or_else(|| {
                            panic!("{case}: expected a pre-resize intermediate")
                        });
                        assert!(
                            tw < SRC_W && th < SRC_H,
                            "{case}: intermediate {tw}x{th} did not shrink below the frame"
                        );
                        assert!(
                            tw >= CW && th >= CH,
                            "{case}: intermediate {tw}x{th} is smaller than the crop"
                        );
                    }
                }
            }
        }
    }

    /// `Nearest` is the one algorithm whose filter reach is genuinely zero, so
    /// without a halo *floor* an already-chroma-aligned crop grows by nothing:
    /// the rebased source rect becomes the whole intermediate, `needs_resize`
    /// in `resize_flip_rotate_pf` flips to false for the first time on this
    /// shape, and control reaches `flip_rotate_ndarray_pf`, which assumes
    /// tightly-packed destination rows and so bypasses the padded-destination
    /// destride entirely.
    ///
    /// Scale-identity crop into a 320x240 view of a parent with a padded row
    /// stride, checked against both a standalone tight convert and the
    /// pre-change full-frame-intermediate oracle.
    #[test]
    fn nearest_scale_identity_crop_into_padded_view() {
        const SRC_W: usize = 640;
        const SRC_H: usize = 480;
        let tile_w = 320usize;
        let tile_h = 240usize;
        let channels = 3usize; // PixelFormat::Rgb

        let src = gradient_image(SRC_W, SRC_H, PixelFormat::Nv12);
        // Even origin on both axes: already chroma-aligned, so the even-snap
        // grows nothing and only the halo floor can separate the rebased rect
        // from the full intermediate.
        let crop = Crop::new()
            .with_source(Some(Region::new(100, 52, tile_w, tile_h)))
            .with_fit(crate::Fit::Stretch);

        let mut converter = CPUProcessor::new_nearest();

        // Reference A: standalone, tightly-packed destination.
        let mut reference = gradient_image(tile_w, tile_h, PixelFormat::Rgb);
        converter
            .convert(&src, &mut reference, Rotation::None, Flip::None, crop)
            .unwrap();
        let reference_bytes = reference.as_u8().unwrap().map().unwrap().to_vec();

        // Reference B: the pre-Task-4 algorithm — whole frame converted once
        // into the packed-RGB intermediate, then the same crop applied to it.
        let mut full = gradient_image(SRC_W, SRC_H, PixelFormat::Rgb);
        converter
            .convert(&src, &mut full, Rotation::None, Flip::None, Crop::default())
            .unwrap();
        let mut oracle = gradient_image(tile_w, tile_h, PixelFormat::Rgb);
        converter
            .convert(&full, &mut oracle, Rotation::None, Flip::None, crop)
            .unwrap();
        assert_eq!(
            reference_bytes,
            oracle.as_u8().unwrap().map().unwrap().to_vec(),
            "Nearest crop-sized intermediate diverged from the full-frame oracle"
        );

        // Padded parent: allocate wider, narrow the logical width back, then
        // record a row stride padded past the tight pitch — the shape a DMA
        // pitch-aligned destination presents.
        let mut parent = TensorDyn::image(
            tile_w + 64,
            2 * tile_h,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        parent
            .configure_image(tile_w, 2 * tile_h, PixelFormat::Rgb)
            .unwrap();
        let padded_stride = tile_w * channels + 16;
        parent.set_row_stride(padded_stride).unwrap();

        let mut view = parent.view(Region::new(0, tile_h, tile_w, tile_h)).unwrap();
        converter
            .convert(&src, &mut view, Rotation::None, Flip::None, crop)
            .unwrap();

        let parent_bytes = parent.as_u8().unwrap().map().unwrap().to_vec();
        let band_offset = tile_h * padded_stride;
        let tight_row = tile_w * channels;
        for row in 0..tile_h {
            let start = band_offset + row * padded_stride;
            assert_eq!(
                &parent_bytes[start..start + tight_row],
                &reference_bytes[row * tight_row..(row + 1) * tight_row],
                "row {row} of the padded destination view must match the standalone convert"
            );
        }
    }

    /// A multiplane (separate luma/chroma tensors) NV12 source must extract the
    /// same crop as the contiguous layout — the two take different branches in
    /// `extract_nv_region` (own chroma stride vs. `split_semi_planar`), and only
    /// the contiguous one is exercised by the golden matrix.
    #[test]
    fn crop_multiplane_nv12_matches_contiguous() {
        const W: usize = 640;
        const H: usize = 480;

        let contiguous = gradient_image(W, H, PixelFormat::Nv12);
        let (luma_bytes, chroma_bytes) = {
            let u8t = contiguous.as_u8().unwrap();
            let stride = u8t.effective_row_stride().unwrap_or(W);
            let map = u8t.map().unwrap();
            let s = map.as_slice();
            (s[..stride * H].to_vec(), s[stride * H..].to_vec())
        };

        let multiplane = {
            let luma = Tensor::<u8>::new(&[H, W], mem(), None).unwrap();
            let chroma = Tensor::<u8>::new(&[H / 2, W], mem(), None).unwrap();
            luma.map_mut().unwrap().as_mut_slice()[..luma_bytes.len()].copy_from_slice(&luma_bytes);
            let n = chroma_bytes
                .len()
                .min(chroma.map().unwrap().as_slice().len());
            chroma.map_mut().unwrap().as_mut_slice()[..n].copy_from_slice(&chroma_bytes[..n]);
            TensorDyn::from(Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12).unwrap())
        };

        let mut converter = CPUProcessor::default();
        // Cropped AND scaled, with an odd origin so the even-snap runs too.
        let crop = Crop::new()
            .with_source(Some(Region::new(101, 53, 320, 240)))
            .with_fit(crate::Fit::Stretch);

        let mut from_multi = gradient_image(160, 120, PixelFormat::Rgb);
        converter
            .convert(
                &multiplane,
                &mut from_multi,
                Rotation::None,
                Flip::None,
                crop,
            )
            .unwrap();
        let mut from_contig = gradient_image(160, 120, PixelFormat::Rgb);
        converter
            .convert(
                &contiguous,
                &mut from_contig,
                Rotation::None,
                Flip::None,
                crop,
            )
            .unwrap();

        assert_eq!(
            from_multi.as_u8().unwrap().map().unwrap().to_vec(),
            from_contig.as_u8().unwrap().map().unwrap().to_vec(),
            "multiplane NV12 crop extraction diverged from the contiguous layout"
        );
    }

    /// A cropped **and scaled** convert must size its pre-resize intermediate
    /// to the crop (plus the resize filter's halo), not to the whole frame.
    ///
    /// 4032x2268 NV12 -> crop (512, 512, 640, 640) -> 320x320 Rgb: the crop is
    /// scaled 2:1, so Task 3's scale-identity fused path does not swallow it
    /// and the general pipeline's pre-resize intermediate is exercised. The
    /// full frame is 9.1 MPix against the crop's 0.41 MPix — a ~22x
    /// difference, so the assertion is about proportionality, not an exact
    /// halo width (which is an implementation detail of the configured
    /// filter).
    #[test]
    fn pre_resize_intermediate_is_crop_sized() {
        const SRC_W: usize = 4032;
        const SRC_H: usize = 2268;
        const CROP: (usize, usize, usize, usize) = (512, 512, 640, 640);

        let mut converter = CPUProcessor::default();
        let src = TensorDyn::image(
            SRC_W,
            SRC_H,
            PixelFormat::Nv12,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        {
            let u8t = src.as_u8().unwrap();
            let mut map = u8t.map_mut().unwrap();
            for (i, b) in map.as_mut_slice().iter_mut().enumerate() {
                *b = ((i * 7 + i / SRC_W * 13) & 0xFF) as u8;
            }
        }

        let mut dst = TensorDyn::image(
            320,
            320,
            PixelFormat::Rgb,
            DType::U8,
            mem(),
            edgefirst_tensor::CpuAccess::ReadWrite,
        )
        .unwrap();
        let crop = Crop::new()
            .with_source(Some(Region::new(CROP.0, CROP.1, CROP.2, CROP.3)))
            .with_fit(crate::Fit::Stretch);

        converter
            .convert(&src, &mut dst, Rotation::None, Flip::None, crop)
            .unwrap();

        let dims = converter
            .last_tmp_dims()
            .expect("a cropped NV12->Rgb scaled convert needs a pre-resize intermediate");
        assert_ne!(
            dims,
            (SRC_W, SRC_H),
            "the pre-resize intermediate is still frame-sized"
        );
        // Crop-sized: at least the crop, and at most the crop plus a small
        // filter halo on each side. 16px of slack per side is far more than
        // any supported filter needs at this 2:1 scale, and far less than the
        // frame.
        assert!(
            (CROP.2..=CROP.2 + 32).contains(&dims.0) && (CROP.3..=CROP.3 + 32).contains(&dims.1),
            "pre-resize intermediate {dims:?} is not crop-sized \
             (expected ~{}x{} + filter halo)",
            CROP.2,
            CROP.3
        );
    }
}