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
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0
#[cfg(test)]
#[cfg(feature = "opengl")]
#[allow(deprecated)]
mod gl_tests {
#[cfg(target_os = "linux")]
use crate::test_support::is_dma_available;
#[cfg(target_os = "linux")]
use crate::{probe_egl_displays, EglDisplayKind};
use crate::{Crop, GLProcessorThreaded, ImageProcessorTrait};
use edgefirst_tensor::{
DType, PixelFormat, Tensor, TensorDyn, TensorMapTrait, TensorMemory, TensorTrait,
};
use edgefirst_tensor::{DetectBox, ProtoData, ProtoLayout};
use image::buffer::ConvertBuffer;
use ndarray::Array3;
#[test]
fn test_segmentation() {
use edgefirst_tensor::Segmentation;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let image = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
None,
)
.unwrap();
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: edgefirst_tensor::Tensor::from_arrayview3(segmentation.view())
.unwrap()
.into(),
xmin: 0.0,
ymin: 0.0,
xmax: 1.0,
ymax: 1.0,
};
let mut renderer = GLProcessorThreaded::new(None).unwrap();
let mut image_dyn = image;
renderer
.draw_decoded_masks(&mut image_dyn, &[], &[seg], Default::default())
.unwrap();
}
#[test]
fn test_segmentation_mem() {
use edgefirst_tensor::Segmentation;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let image = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
Some(edgefirst_tensor::TensorMemory::Mem),
)
.unwrap();
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: edgefirst_tensor::Tensor::from_arrayview3(segmentation.view())
.unwrap()
.into(),
xmin: 0.0,
ymin: 0.0,
xmax: 1.0,
ymax: 1.0,
};
let mut renderer = GLProcessorThreaded::new(None).unwrap();
let mut image_dyn = image;
renderer
.draw_decoded_masks(&mut image_dyn, &[], &[seg], Default::default())
.unwrap();
}
#[test]
fn test_segmentation_yolo() {
use edgefirst_tensor::Segmentation;
use ndarray::Array3;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
// draw_decoded_masks fully writes dst — pass the camera frame as
// the MaskOverlay background, 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: edgefirst_tensor::Tensor::from_arrayview3(segmentation.view())
.unwrap()
.into(),
xmin: 0.59375,
ymin: 0.25,
xmax: 0.9375,
ymax: 0.725,
};
let mut renderer = GLProcessorThreaded::new(None).unwrap();
renderer
.set_class_colors(&[[255, 255, 0, 233], [128, 128, 255, 100]])
.unwrap();
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_gl.jpg"),
Some(PixelFormat::Rgba),
None,
)
.unwrap();
// Threshold 0.95 (was 0.97): GPU-specific smoothstep anti-aliasing at
// mask edges produces small cross-platform differences (x86 Mesa vs
// Vivante), and the codec now decodes the `giraffe.jpg` background to
// native NV12 (chroma subsampling) before the RGBA conversion, so the
// NV12-sourced background diverges further from the golden captured
// under the old direct-RGB JPEG decode.
compare_images(&image, &expected, 0.95, function!());
}
/// `a` and `b` agree to within the GPU's blend rounding.
fn px_close(a: [u8; 4], b: [u8; 4]) -> bool {
a.iter().zip(b).all(|(&x, y)| x.abs_diff(y) <= 2)
}
#[test]
fn test_box_line_width_matches_cpu() {
use crate::test_support::{box_drawn_columns, box_drawn_rows, box_expected_span, BOX_DIM};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = GLProcessorThreaded::new(None).unwrap();
let mut cpu = crate::CPUProcessor::new();
let mid = BOX_DIM / 2;
for width in [
None,
Some(1u32),
Some(6),
Some(8),
Some(9),
Some(12),
Some(40),
] {
let expected =
box_expected_span(width.unwrap_or(crate::DEFAULT_BOX_LINE_WIDTH) as usize);
let g = crate::test_support::draw_box_fixture(&mut gl, [200, 100, 50, 255], width, 1.0);
let c =
crate::test_support::draw_box_fixture(&mut cpu, [200, 100, 50, 255], width, 1.0);
assert_eq!(
box_drawn_columns(&g, mid),
expected,
"gl width {width:?} row"
);
assert_eq!(
box_drawn_rows(&g, mid),
expected,
"gl width {width:?} column"
);
assert_eq!(
box_drawn_columns(&c, mid),
expected,
"cpu width {width:?} row"
);
assert_eq!(
box_drawn_rows(&c, mid),
expected,
"cpu width {width:?} column"
);
assert_eq!(g, c, "gl and cpu width {width:?}");
}
let err = gl.set_box_line_width(0).unwrap_err();
assert!(matches!(err, crate::Error::InvalidOptions(_)), "{err:?}");
}
#[test]
fn test_box_colour_alpha_matches_cpu() {
use crate::test_support::{box_blend, box_expected_span, box_px, BOX_BG, BOX_DIM};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = GLProcessorThreaded::new(None).unwrap();
let mid = BOX_DIM / 2;
let corner = BOX_DIM / 4 - 1;
for (color, opacity, alpha) in [
([200u8, 100, 50, 255u8], 1.0f32, 255u16),
([200, 100, 50, 128], 1.0, 128),
([200, 100, 50, 255], 0.5, 128),
] {
let want = box_blend(color, alpha);
let flat = crate::test_support::draw_box_fixture(&mut gl, color, Some(3), opacity);
for x in box_expected_span(3) {
let got = box_px(&flat, x, mid);
assert!(
px_close(got, want),
"{color:?}@{opacity} x={x}: {got:?} != {want:?}"
);
}
let got = box_px(&flat, corner, corner);
assert!(
px_close(got, want),
"{color:?}@{opacity} corner: {got:?} != {want:?}"
);
assert_eq!(
box_px(&flat, mid, mid),
BOX_BG,
"box interior must not be drawn"
);
}
}
#[test]
fn test_boxes() {
use edgefirst_tensor::DetectBox;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let image = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
None,
)
.unwrap();
let mut image_dyn = image;
let detect = DetectBox {
bbox: [0.59375, 0.25, 0.9375, 0.725].into(),
score: 0.99,
label: 0,
};
let mut renderer = GLProcessorThreaded::new(None).unwrap();
renderer
.set_class_colors(&[[255, 255, 0, 233], [128, 128, 255, 100]])
.unwrap();
renderer
.draw_decoded_masks(&mut image_dyn, &[detect], &[], Default::default())
.unwrap();
}
static GL_AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
#[cfg(target_os = "linux")]
static NEUTRON_AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
fn is_opengl_available() -> bool {
// Portable: the unified engine runs on Linux (EGL/DMA-BUF) and
// macOS (ANGLE/IOSurface). On the macOS coverage flow this returns
// false in pass 1 (unsigned binaries, ANGLE dlopen gate closed) so
// the GL tests self-skip there and execute in pass 2.
*GL_AVAILABLE.get_or_init(|| GLProcessorThreaded::new(None).is_ok())
}
/// Zero-copy GPU image buffers available? DMA-BUF heaps on Linux,
/// IOSurface on macOS. The portable seam for tests whose `@Dma`
/// fixtures allocate on both platforms (RGBA/BGRA/GREY/NV*/YUYV);
/// packed-RGB `@Dma` has no IOSurface FourCC, so tests with RGB DMA
/// destinations stay Linux-gated.
fn is_gpu_image_buffer_available() -> bool {
crate::test_support::is_gpu_buffer_available()
}
/// Returns true when running on an i.MX 95 board with Mali GPU.
///
/// `/dev/neutron0` is used as a platform discriminator for i.MX 95 + Mali GPU,
/// not as a check for NPU functionality. The Neutron-scenario tests exercise
/// large-offset DMA-BUF EGLImage imports that work on Mali but fail with
/// `EGL(BadAccess)` on Vivante (i.MX 8MP) — even without the NPU driver.
#[cfg(target_os = "linux")]
fn is_neutron_available() -> bool {
*NEUTRON_AVAILABLE.get_or_init(|| std::path::Path::new("/dev/neutron0").exists())
}
// DEDUP: this function is also defined verbatim in the `image_tests` module
// of `crates/image/src/lib.rs`. Both copies must be kept in sync. See the
// comment there for why cross-module sharing was deferred.
fn compare_images(img1: &TensorDyn, img2: &TensorDyn, threshold: f64, name: &str) {
assert_eq!(img1.height(), img2.height(), "Heights differ");
assert_eq!(img1.width(), img2.width(), "Widths differ");
assert_eq!(
img1.format().unwrap(),
img2.format().unwrap(),
"PixelFormat differ"
);
assert!(
matches!(
img1.format().unwrap(),
PixelFormat::Rgb
| PixelFormat::Rgba
| PixelFormat::Grey
| PixelFormat::PlanarRgb
| PixelFormat::PlanarRgba
),
"format must be Rgb or Rgba for comparison"
);
// A pitch-padded destination -- the D3D11 staging texture behind a
// Windows `TensorMemory::DmaBuf` tensor pads an RGBA row to 128 bytes
// -- spaces its rows at `effective_row_stride()`, so reading the head
// of the mapping as a tight image would read padding as pixels.
// `copy_to_flat` is the tensor's own compaction and degenerates to one
// memcpy when the tensor is tight.
fn flat(img: &TensorDyn) -> Vec<u8> {
let t = img.as_u8().expect("u8 image");
let mut out = vec![0u8; t.shape().iter().product::<usize>()];
t.copy_to_flat(&mut out).expect("compact the padded rows");
out
}
let image1 = match img1.format().unwrap() {
PixelFormat::Rgb => image::RgbImage::from_vec(
img1.width().unwrap() as u32,
img1.height().unwrap() as u32,
flat(img1),
)
.unwrap(),
PixelFormat::Rgba => image::RgbaImage::from_vec(
img1.width().unwrap() as u32,
img1.height().unwrap() as u32,
flat(img1),
)
.unwrap()
.convert(),
PixelFormat::Grey => image::GrayImage::from_vec(
img1.width().unwrap() as u32,
img1.height().unwrap() as u32,
flat(img1),
)
.unwrap()
.convert(),
PixelFormat::PlanarRgb | PixelFormat::PlanarRgba => image::GrayImage::from_vec(
img1.width().unwrap() as u32,
(img1.height().unwrap() * img1.format().unwrap().channels()) as u32,
flat(img1),
)
.unwrap()
.convert(),
_ => return,
};
let image2 = match img2.format().unwrap() {
PixelFormat::Rgb => image::RgbImage::from_vec(
img2.width().unwrap() as u32,
img2.height().unwrap() as u32,
flat(img2),
)
.unwrap(),
PixelFormat::Rgba => image::RgbaImage::from_vec(
img2.width().unwrap() as u32,
img2.height().unwrap() as u32,
flat(img2),
)
.unwrap()
.convert(),
PixelFormat::Grey => image::GrayImage::from_vec(
img2.width().unwrap() as u32,
img2.height().unwrap() as u32,
flat(img2),
)
.unwrap()
.convert(),
PixelFormat::PlanarRgb | PixelFormat::PlanarRgba => image::GrayImage::from_vec(
img2.width().unwrap() as u32,
(img2.height().unwrap() * img2.format().unwrap().channels()) as u32,
flat(img2),
)
.unwrap()
.convert(),
_ => return,
};
let similarity = image_compare::rgb_similarity_structure(
&image_compare::Algorithm::RootMeanSquared,
&image1,
&image2,
)
.expect("Image Comparison failed");
if similarity.score < threshold {
// Best-effort save of diff image for debugging (may fail on CI
// where paths contain special characters or the fs is read-only).
let save_name = name.replace('\0', "_");
let _ = similarity
.image
.to_color_map()
.save(format!("{save_name}.png"));
panic!(
"{name}: converted image and target image have similarity score too low: {} < {}",
similarity.score, threshold
)
}
}
// =========================================================================
// PixelFormat::Nv12 Reference Validation Tests
// These tests compare OpenGL PixelFormat::Nv12 conversions against ffmpeg-generated
// references
// =========================================================================
/// An image tensor of `format` holding `bytes`, a *tight* buffer laid into
/// it at the destination's own row pitch by [`write_tight_rows`].
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn load_raw_image(
width: usize,
height: usize,
format: PixelFormat,
memory: Option<TensorMemory>,
bytes: &[u8],
) -> Result<TensorDyn, crate::Error> {
let img = TensorDyn::image(
width,
height,
format,
DType::U8,
memory,
edgefirst_tensor::CpuAccess::ReadWrite,
)?;
write_tight_rows(&img, bytes)?;
Ok(img)
}
/// Copy a *tight* image buffer -- rows packed at the image's own row
/// length, with no padding -- into `t`, re-spacing the rows to the
/// destination's own pitch.
///
/// A backing can carry a physical pitch wider than the image: an
/// IOSurface's `bytesPerRow`, and on Windows a D3D11 texture allocated as
/// wide as the driver's staging pitch (128 bytes on this NVIDIA adapter, so
/// a 64-wide NV16 source is a 128-wide texture). `effective_row_stride()`
/// is the spacing every consumer of that tensor uses, the Path B shader
/// included, so a block `copy_from_slice` of the whole buffer puts row `r`
/// at `r * tight` where the texture and the shader look at `r * stride`,
/// and every pixel past the first row is wrong.
///
/// A semi-planar buffer is re-spaced by *line*, not by row: its combined
/// plane is `height` luma lines of `width` bytes followed by chroma lines
/// of `2 * chroma_w` bytes, and the chroma lines sit
/// `ChromaLayout::uv_rows_per_luma` destination rows apart -- two, for
/// NV24, whose `2W`-byte line is wider than one image row. That is the
/// layout `fill_patterned_nv` writes and the layout the shader decodes.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn write_tight_rows(t: &TensorDyn, bytes: &[u8]) -> Result<(), crate::Error> {
let format = t.format().unwrap();
let width = t.width().unwrap();
let height = t.height().unwrap();
// `bytes` and the map are byte slices, but the rows they hold are
// samples: a row is as many bytes as the element type is wide. Every
// caller today is `DType::U8`, where this is a multiplication by one;
// taking it from the tensor means a float caller addresses its rows
// rather than a quarter of them.
let elem = t.dtype().size();
let bound = t.as_u8().unwrap();
let stride = bound.effective_row_stride().unwrap();
let mut map = bound.map()?;
let dst = map.as_mut_slice();
match format.chroma_layout() {
Some(chroma) => {
let luma = width * elem;
let chroma_h = height.div_ceil(1 << chroma.shift_y);
let line = width.div_ceil(1 << chroma.shift_x) * 2 * elem;
for r in 0..height {
dst[r * stride..r * stride + luma]
.copy_from_slice(&bytes[r * luma..(r + 1) * luma]);
}
let uv = &bytes[luma * height..];
for i in 0..chroma_h {
let at = (height + i * chroma.uv_rows_per_luma) * stride;
dst[at..at + line].copy_from_slice(&uv[i * line..(i + 1) * line]);
}
}
None => {
let tight = match format.layout() {
edgefirst_tensor::PixelLayout::Packed => width * format.channels() * elem,
_ => width * elem,
};
for (r, row) in bytes.chunks(tight).enumerate() {
dst[r * stride..r * stride + row.len()].copy_from_slice(row);
}
}
}
Ok(())
}
/// Steady-state import gate: an N-frame convert loop over a fixed pool of
/// DMA source buffers into a same-size and a resized DMA destination must
/// perform ZERO new EGLImage imports after the pool has been seen once —
/// every later convert is a cache hit on all caches (src/dst/NV R8, and
/// the NV chroma view the bilinear resize binds). The import
/// count, not latency, is the regression signal that pins EGLImage cache
/// behavior across GL refactors: a refactor that re-imports per frame
/// passes every pixel-equality test but fails this one.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_pool_steady_state_zero_imports() {
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let mut renderer = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
let (w, h) = (128usize, 96usize);
const POOL: usize = 3;
const FRAMES: usize = 300;
// NV12 pool (the camera-pipeline shape): Y plane + neutral chroma.
let mut bytes = vec![100u8; w * h];
bytes.extend(std::iter::repeat_n(128u8, w * h / 2));
let pool: Vec<TensorDyn> = (0..POOL)
.map(|_| {
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::DmaBuf), &bytes).unwrap()
})
.collect();
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut scaled = TensorDyn::image(
w * 3 / 2,
h * 3 / 2,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut frame = |renderer: &mut GLProcessorThreaded, src: &TensorDyn| {
for dst in [&mut dst, &mut scaled] {
renderer.convert(src, dst, None).unwrap();
}
};
// Warmup: two passes over the pool import every buffer once.
for src in pool.iter().cycle().take(POOL * 2) {
frame(&mut renderer, src);
}
let warm = renderer.egl_cache_stats().unwrap();
for src in pool.iter().cycle().take(FRAMES) {
frame(&mut renderer, src);
}
let steady = renderer.egl_cache_stats().unwrap();
assert_eq!(
warm.total_misses(),
steady.total_misses(),
"steady-state loop performed new EGLImage imports: warm={warm:?} steady={steady:?}"
);
let hits = |s: &crate::opengl_headless::cache::GlCacheStats| {
s.src.hits + s.dst.hits + s.nv_r8.hits + s.nv_uv.hits
};
let gained = hits(&steady) - hits(&warm);
assert!(
gained >= FRAMES as u64,
"expected at least {FRAMES} cache hits over the loop, got {gained} \
(warm={warm:?} steady={steady:?})"
);
}
/// Cross-package regression gate: a buffer that arrives as a FRESH tensor
/// every frame must still hit the import cache.
///
/// This is the shape of every convert that crosses a package boundary —
/// `import_descriptor` builds a tensor over the producer's buffer, the
/// call uses it, and it drops on return — and it is NOT covered by
/// `dma_pool_steady_state_zero_imports` above, which holds its pool
/// tensors alive for the whole loop. Measured before the fix on this
/// path: 0 hits / 50 misses, against 49 / 1 for the native source, plus
/// 49 × "swept 1 dead entries" — the cache was creating and destroying
/// one `eglCreateImageKHR` (100 µs–1 ms on Mali/Vivante) per frame.
///
/// Two independent things have to hold for this to pass, which is why it
/// is worth asserting even though it looks like the test above: the two
/// tensors must derive the SAME identity from the buffer's system key
/// (so the key matches at all), and the entry must OUTLIVE the tensor it
/// was built from (so there is still an entry to match).
///
/// The first of those cannot hold on Windows. A D3D11 handle import keys
/// on the `ID3D11Texture2D` the open produced (see
/// `IdentityKind::D3d11Texture`), and `OpenSharedResource1` mints a fresh
/// object per open. Keying on a handle value instead would be stable
/// here and unsound: Windows recycles a closed handle value at once --
/// measured at 49 of 50 frames on this box -- so a cache entry outliving
/// its tensor would be served to an unrelated later import of a different
/// texture. The Windows arm below therefore asserts what is true and
/// load-bearing instead.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn reimported_buffer_hits_the_cache() {
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let mut renderer = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
let (w, h) = (128usize, 96usize);
const FRAMES: usize = 50;
// The producer's buffer. It stays alive for the whole test (a real
// producer owns its pool); what churns is the CONSUMER's tensor.
let mut bytes = vec![100u8; w * h];
bytes.extend(std::iter::repeat_n(128u8, w * h / 2));
let producer =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::DmaBuf), &bytes).unwrap();
let desc = producer.descriptor();
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
// Warmup: import the buffer (and the destination) exactly once.
{
let frame = TensorDyn::import_descriptor(&desc).unwrap();
renderer.convert(&frame, &mut dst, None).unwrap();
}
let warm = renderer.egl_cache_stats().unwrap();
for _ in 0..FRAMES {
// Freshly imported, used, and dropped within the iteration —
// precisely what a cross-package `convert()` does per frame.
let frame = TensorDyn::import_descriptor(&desc).unwrap();
renderer.convert(&frame, &mut dst, None).unwrap();
}
let steady = renderer.egl_cache_stats().unwrap();
#[cfg(not(target_os = "windows"))]
{
assert_eq!(
warm.total_misses(),
steady.total_misses(),
"re-imported buffer was re-imported into GL every frame: \
warm={warm:?} steady={steady:?}"
);
let hits = |s: &crate::opengl_headless::cache::GlCacheStats| {
s.src.hits + s.dst.hits + s.nv_r8.hits + s.nv_uv.hits
};
let gained = hits(&steady) - hits(&warm);
assert!(
gained >= FRAMES as u64,
"expected at least {FRAMES} cache hits over the loop, got {gained} \
(warm={warm:?} steady={steady:?})"
);
}
#[cfg(target_os = "windows")]
{
// See the doc comment: a fresh identity per handle import is the
// price of an identity that cannot be recycled under a live cache
// entry. What still holds, and is what the cache is for, is that
// the long-lived destination never re-imports and the per-frame
// source churn is bounded by the loop rather than unbounded.
assert_eq!(
steady.dst.misses, warm.dst.misses,
"the destination lives across the loop, so it must not re-import: \
warm={warm:?} steady={steady:?}"
);
assert!(
steady.dst.hits - warm.dst.hits >= FRAMES as u64,
"the destination must hit every frame: warm={warm:?} steady={steady:?}"
);
assert!(
steady.total_misses() - warm.total_misses() <= FRAMES as u64,
"source imports must be bounded by the loop: warm={warm:?} steady={steady:?}"
);
}
}
/// RGBA gradient bytes (w*h*4) with distinct R/G/B functions and a salt —
/// non-uniform content so a stride/geometry/feed misread cannot pass.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn rgba_gradient(w: usize, h: usize, salt: u8) -> Vec<u8> {
let mut v = Vec::with_capacity(w * h * 4);
for y in 0..h {
for x in 0..w {
v.push(((x * 255) / w.max(1)) as u8 ^ salt);
v.push(((y * 255) / h.max(1)) as u8);
v.push((((x + y) * 255) / (w + h).max(1)) as u8);
v.push(255);
}
}
v
}
/// Portable contract of the GL→NPU fence entry point: whether or not the
/// display exports a fence, the converted output must equal the blocking
/// convert's. On platforms with no device fence (Linux/macOS) the call
/// also returns `Ok(None)` — the blocking contract, destination
/// immediately readable. Android exports an
/// `EGL_ANDROID_native_fence_sync` fd and Windows an event on the D3D11
/// device fence, so those two may return a handle; the Android arm is
/// device-verified by `verify_fence_handoff` in the Device Farm harness.
// Desktop-gated only for the fixture helpers (`rgba_gradient`, `load_raw_image`); the tensors are Mem.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn convert_with_fence_blocking_fallback_matches() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
let mut gl = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
let (sw, sh, dw) = (96usize, 72usize, 64usize);
let bytes = rgba_gradient(sw, sh, 3);
let src = load_raw_image(sw, sh, PixelFormat::Rgba, Some(TensorMemory::Mem), &bytes)
.expect("src alloc");
let mut dst_fenced = TensorDyn::image(
dw,
dw,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("dst alloc");
let mut dst_blocking = TensorDyn::image(
dw,
dw,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("dst alloc");
let fence = gl
.convert_with_fence(&src, &mut dst_fenced, None)
.expect("convert_with_fence");
if cfg!(not(any(target_os = "android", target_os = "windows"))) {
assert!(
fence.is_none(),
"no platform in this test tier has native fence sync"
);
}
gl.convert(&src, &mut dst_blocking, None).expect("convert");
let (ma, mb) = (
dst_fenced.as_u8().unwrap().map().unwrap(),
dst_blocking.as_u8().unwrap().map().unwrap(),
);
assert_eq!(ma.as_slice(), mb.as_slice(), "fenced vs blocking output");
}
/// The float paths' zero-copy source import (`feed_float_src` arm 1) must
/// produce bit-identical output to the CPU-upload feed of the same bytes:
/// same shader, same filtering, only the source feed differs. Also proves
/// the imported source buffer is left untouched.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn float_dma_src_import_matches_upload() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or GL",
function!()
));
return;
}
let mut gl = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// The F16 destinations below are a render target, and Vivante has no
// float color buffer at all (`float_render_support` returns
// `{f32: false, f16: false}` for it), so `convert` refuses the
// destination outright. Gated the way
// `convert_f16_gl_cpu_parity_identity` and the F16 cache tests in
// `lib.rs` already gate, on the capability the processor reports
// rather than on a driver name.
if !gl.supported_render_dtypes().f16 {
crate::test_support::report_skip(&format!(
"{} - this GPU has no F16 render target",
function!()
));
return;
}
let (sw, sh, dw) = (96usize, 72usize, 64usize);
let bytes = rgba_gradient(sw, sh, 0);
let src_dma = load_raw_image(
sw,
sh,
PixelFormat::Rgba,
Some(TensorMemory::DmaBuf),
&bytes,
)
.unwrap();
let src_mem =
load_raw_image(sw, sh, PixelFormat::Rgba, Some(TensorMemory::Mem), &bytes).unwrap();
let mut dst_a = TensorDyn::image(
dw,
dw,
PixelFormat::PlanarRgb,
DType::F16,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dst_b = TensorDyn::image(
dw,
dw,
PixelFormat::PlanarRgb,
DType::F16,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src_dma, &mut dst_a, None).unwrap();
gl.convert(&src_mem, &mut dst_b, None).unwrap();
let (ma, mb) = (
dst_a.as_f16().unwrap().map().unwrap(),
dst_b.as_f16().unwrap().map().unwrap(),
);
assert_eq!(ma.as_slice().len(), mb.as_slice().len());
for (i, (a, b)) in ma.as_slice().iter().zip(mb.as_slice().iter()).enumerate() {
assert_eq!(
a.to_bits(),
b.to_bits(),
"import vs upload diverged at f16 element {i}: {a} vs {b}"
);
}
drop((ma, mb));
// The imported source must be pristine — an attach that let a later
// texture operation write through would corrupt the camera's buffer.
let m = src_dma.as_u8().unwrap().map().unwrap();
let stride = src_dma.effective_row_stride().unwrap_or(sw * 4);
for y in 0..sh {
let row = &m.as_slice()[y * stride..y * stride + sw * 4];
assert_eq!(
row,
&bytes[y * sw * 4..(y + 1) * sw * 4],
"src row {y} modified"
);
}
}
/// Alternating Dma → Mem → Dma float frames on one processor: the
/// upload-poison must force fresh storage after an attach (a
/// TexSubImage2D into the EGLImage sibling would scribble on the Dma
/// buffer), and the binding-skip key must clear after an upload (a
/// skipped re-attach would sample stale uploaded bytes). A u8 convert is
/// interleaved because it shares `camera_normal_texture`.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn float_src_feed_alternating_frames() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or GL",
function!()
));
return;
}
let mut gl = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// The F16 destinations below are a render target, and Vivante has no
// float color buffer at all (`float_render_support` returns
// `{f32: false, f16: false}` for it), so `convert` refuses the
// destination outright. Gated the way
// `convert_f16_gl_cpu_parity_identity` and the F16 cache tests in
// `lib.rs` already gate, on the capability the processor reports
// rather than on a driver name.
if !gl.supported_render_dtypes().f16 {
crate::test_support::report_skip(&format!(
"{} - this GPU has no F16 render target",
function!()
));
return;
}
let (sw, sh, dw) = (96usize, 72usize, 64usize);
let content_a = rgba_gradient(sw, sh, 0x00);
let content_b = rgba_gradient(sw, sh, 0x5A);
let content_c = rgba_gradient(sw, sh, 0xA5);
let src_dma = load_raw_image(
sw,
sh,
PixelFormat::Rgba,
Some(TensorMemory::DmaBuf),
&content_a,
)
.unwrap();
let run_float = |gl: &mut GLProcessorThreaded, src: &TensorDyn| -> Vec<u16> {
let mut dst = TensorDyn::image(
dw,
dw,
PixelFormat::PlanarRgb,
DType::F16,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(src, &mut dst, None).unwrap();
let m = dst.as_f16().unwrap().map().unwrap();
m.as_slice().iter().map(|v| v.to_bits()).collect()
};
let reference = |gl: &mut GLProcessorThreaded, bytes: &[u8]| -> Vec<u16> {
let mem =
load_raw_image(sw, sh, PixelFormat::Rgba, Some(TensorMemory::Mem), bytes).unwrap();
run_float(gl, &mem)
};
// Frame 1: Dma source (attach arm).
let out1 = run_float(&mut gl, &src_dma);
assert_eq!(out1, reference(&mut gl, &content_a), "frame 1 (Dma A)");
// Interleaved u8 convert — crosses the shared source texture.
let u8_src = load_raw_image(
sw,
sh,
PixelFormat::Rgba,
Some(TensorMemory::Mem),
&content_b,
)
.unwrap();
let mut u8_dst = TensorDyn::image(
dw,
dw,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&u8_src, &mut u8_dst, None).unwrap();
// Frame 2: Mem source (upload arm; storage must be respecified).
let out2 = run_float(&mut gl, &u8_src);
assert_eq!(out2, reference(&mut gl, &content_b), "frame 2 (Mem B)");
// The scribble detector: frame 2's upload must NOT have written into
// frame 1's still-attached Dma buffer.
{
let m = src_dma.as_u8().unwrap().map().unwrap();
let stride = src_dma.effective_row_stride().unwrap_or(sw * 4);
for y in 0..sh {
let row = &m.as_slice()[y * stride..y * stride + sw * 4];
assert_eq!(
row,
&content_a[y * sw * 4..(y + 1) * sw * 4],
"Dma source scribbled by the upload frame (row {y})"
);
}
}
// Frame 3: Dma source again with NEW content (re-attach must not be
// skipped; stale uploaded bytes must not be sampled).
overwrite_in_place(&src_dma, &content_c);
let out3 = run_float(&mut gl, &src_dma);
assert_eq!(out3, reference(&mut gl, &content_c), "frame 3 (Dma C)");
}
/// Steady-state: a fixed pool of Dma float sources must import once and
/// hit the src cache thereafter — the float analog of the NV pool gate.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn float_dma_src_pool_steady_state() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or GL",
function!()
));
return;
}
let mut gl = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// The F16 destinations below are a render target, and Vivante has no
// float color buffer at all (`float_render_support` returns
// `{f32: false, f16: false}` for it), so `convert` refuses the
// destination outright. Gated the way
// `convert_f16_gl_cpu_parity_identity` and the F16 cache tests in
// `lib.rs` already gate, on the capability the processor reports
// rather than on a driver name.
if !gl.supported_render_dtypes().f16 {
crate::test_support::report_skip(&format!(
"{} - this GPU has no F16 render target",
function!()
));
return;
}
let (sw, sh, dw) = (128usize, 96usize, 64usize);
const FRAMES: usize = 100;
let pool: Vec<TensorDyn> = (0..2)
.map(|i| {
load_raw_image(
sw,
sh,
PixelFormat::Rgba,
Some(TensorMemory::DmaBuf),
&rgba_gradient(sw, sh, i as u8),
)
.unwrap()
})
.collect();
let mut dst = TensorDyn::image(
dw,
dw,
PixelFormat::PlanarRgb,
DType::F16,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
for src in pool.iter().cycle().take(4) {
gl.convert(src, &mut dst, None).unwrap();
}
let warm = gl.egl_cache_stats().unwrap();
let warm_feed = gl.convert_stats().unwrap();
for src in pool.iter().cycle().take(FRAMES) {
gl.convert(src, &mut dst, None).unwrap();
}
let steady = gl.egl_cache_stats().unwrap();
let steady_feed = gl.convert_stats().unwrap();
assert_eq!(
warm.total_misses(),
steady.total_misses(),
"float src loop performed new EGLImage imports: warm={warm:?} steady={steady:?}"
);
// Feed telemetry is 1:1 with frames: every convert is counted as
// exactly one of import/pbo/upload…
let d_imports = steady_feed.src_imports - warm_feed.src_imports;
let d_pbo = steady_feed.src_pbo_uploads - warm_feed.src_pbo_uploads;
let d_uploads = steady_feed.src_uploads - warm_feed.src_uploads;
let d_declines = steady_feed.zero_copy_declines - warm_feed.zero_copy_declines;
assert_eq!(
d_imports + d_pbo + d_uploads,
FRAMES as u64,
"feed counters don't account for every frame: \
warm={warm_feed:?} steady={steady_feed:?}"
);
// …and when the driver never declined the import (macOS ANGLE, most
// Linux), every Dma-source frame MUST have been fed zero-copy. A
// declining driver (e.g. Vivante rejecting TEXTURE_2D dma-buf attach)
// is a designed fallback, not a telemetry bug — accounted above.
if d_declines == 0 {
assert_eq!(
d_imports, FRAMES as u64,
"no declines yet frames were not import-fed: \
warm={warm_feed:?} steady={steady_feed:?}"
);
}
}
/// Regression test for the repeat-convert GL_INVALID_VALUE (0x501) state
/// leak: heap-RGBA source → two-pass packed RGB → DMA destination succeeded
/// on the FIRST convert and failed on the SECOND on Vivante/Mali/V3D alike.
///
/// Root cause: `convert_to_packed_rgb` pass 2 exits with `ActiveTexture`
/// left at TEXTURE1 and the destination EGLImage texture bound on unit 0,
/// while `draw_src_texture` issued `BindTexture` BEFORE `ActiveTexture` —
/// binding the camera texture to the leaked unit and then uploading the
/// 1280×720 source into the 640×640 destination texture via the
/// `TexSubImage2D` fast path → GL_INVALID_VALUE. Driver-independent GLES
/// semantics, hence identical on all dmabuf GPUs.
///
/// The loop runs each dtype cell several times (not just twice) and pins
/// byte-identical output across iterations, so any texture-unit state leak
/// between converts surfaces either as an error or as a pixel diff.
#[test]
// Portable since packed-RGB u8 gained its RGBA8888 IOSurface mapping
// (`packed_rgb888_layout`): the fixture allocates on macOS too, and the
// two-pass packed-RGB pipeline runs zero-copy on both backends.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn repeat_convert_rgba_mem_to_rgb_dma() {
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let mut renderer = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// Deterministic RGBA gradient source in plain heap memory (the cell's
// defining property: NOT DMA, so the source goes through the
// draw_src_texture CPU-upload path).
let (src_w, src_h) = (1280usize, 720usize);
let mut bytes = vec![0u8; src_w * src_h * 4];
for (i, px) in bytes.as_chunks_mut::<4>().0.iter_mut().enumerate() {
px[0] = (i % 256) as u8;
px[1] = ((i / 256) % 256) as u8;
px[2] = ((i / 65536) % 256) as u8;
px[3] = 255;
}
let src = load_raw_image(
src_w,
src_h,
PixelFormat::Rgba,
Some(TensorMemory::Mem),
&bytes,
)
.unwrap();
let lb = Crop::letterbox([114, 114, 114, 255]);
for dtype in [DType::U8, DType::I8] {
let Some(mut dst) = crate::test_support::gpu_buffer_allocated(
TensorDyn::image(
640,
640,
PixelFormat::Rgb,
dtype,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
),
&format!("cell {dtype:?}: DMA RGB destination"),
) else {
continue;
};
let mut first: Option<Vec<u8>> = None;
for round in 0..4 {
renderer
.convert(&src, &mut dst, Some(crate::ConvertOptions::new().crop(lb)))
.unwrap_or_else(|e| {
panic!(
"rgba@mem->rgb.{dtype:?}@dma convert #{} failed: {e} \
(repeat-convert state leak — see 0x501 regression)",
round + 1
)
});
let out: Vec<u8> = match dtype {
DType::I8 => dst
.as_i8()
.unwrap()
.map()
.unwrap()
.as_slice()
.iter()
.map(|&v| v as u8)
.collect(),
_ => dst.as_u8().unwrap().map().unwrap().as_slice().to_vec(),
};
match &first {
None => first = Some(out),
Some(reference) => assert_eq!(
reference,
&out,
"rgba@mem->rgb.{dtype:?}@dma convert #{} output diverged from #1",
round + 1
),
}
}
}
}
/// The int8 variant of every draw must differ from the u8 variant by
/// exactly XOR 0x80 on the colour channels — the int8 fragment shaders
/// are the u8 shaders plus the bias, nothing else (alpha passes through).
///
/// Catches the texture-destination program-selection gap: the heap-source
/// NV12 (ShaderR8 upload) int8 convert rendered through the UN-biased NV
/// program (only the DMA destination path swapped `nv_r8_program`),
/// producing u8-semantics bytes in an i8 tensor — 0x80 off on every
/// channel. Needs no DMA at runtime (Mem src/dst — runs on llvmpipe,
/// included); the platform gate only matches the `load_raw_image` helper's.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn int8_mem_convert_is_xor_biased_u8() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut renderer = match GLProcessorThreaded::new(None) {
Ok(r) => r,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// Gradient luma + off-neutral chroma so the bias is exercised across
// values straddling 0x80 (where a missing bias is a ~128 byte diff).
let (w, h) = (64usize, 48usize);
let mut nv12 = vec![0u8; w * h * 3 / 2];
for row in 0..h {
for col in 0..w {
nv12[row * w + col] = ((row * 255) / h) as u8;
}
}
for i in 0..w * h / 4 {
nv12[w * h + 2 * i] = 110; // Cb
nv12[w * h + 2 * i + 1] = 150; // Cr
}
let src = load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::Mem), &nv12).unwrap();
// RGBA must convert everywhere the NV upload path exists; RGB-format
// readback is implementation-defined in GLES (V3D rejects it with
// GL_INVALID_OPERATION — the cell was absent from rpi5's PR-0 matrix
// baseline too), so a failing RGB cell skips rather than fails.
let mut validated = 0usize;
'fmt: for fmt in [PixelFormat::Rgb, PixelFormat::Rgba] {
let mut out = [Vec::new(), Vec::new()];
for (slot, dtype) in [(0, DType::U8), (1, DType::I8)] {
let mut dst = TensorDyn::image(
w,
h,
fmt,
dtype,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if let Err(e) = renderer.convert(&src, &mut dst, None) {
if fmt == PixelFormat::Rgba {
panic!("nv12@mem -> rgba.{dtype:?}@mem must be supported: {e}");
}
crate::test_support::report_skip(&format!(
"cell nv12@mem -> {fmt}.{dtype:?}@mem: {e}"
));
continue 'fmt;
}
out[slot] = match dtype {
DType::I8 => dst
.as_i8()
.unwrap()
.map()
.unwrap()
.as_slice()
.iter()
.map(|&v| v as u8)
.collect(),
_ => dst.as_u8().unwrap().map().unwrap().as_slice().to_vec(),
};
}
let channels = fmt.channels();
let mut diffs = 0usize;
for (i, (&u, &b)) in out[0].iter().zip(out[1].iter()).enumerate() {
let expect = if channels == 4 && i % 4 == 3 {
u
} else {
u ^ 0x80
};
// ±1 LSB: the int8 shader's explicit floor(v*255+0.5)+128
// quantization double-rounds against the driver's own
// float→unorm8 store, shifting ~2% of bytes by one on some
// GPUs (seen on Vivante). A missing bias is a ~128 diff, so
// the tolerance keeps full sensitivity to the real bug.
if (b as i16 - expect as i16).abs() > 1 {
diffs += 1;
if diffs <= 5 {
eprintln!("byte {i}: u8={u:#04x} i8={b:#04x} expected {expect:#04x}");
}
}
}
assert_eq!(
diffs, 0,
"nv12@mem -> {fmt}: i8 output is not the XOR-0x80 bias of the u8 output \
({diffs} bytes differ beyond ±1 — un-biased int8 NV program?)"
);
validated += 1;
}
assert!(validated >= 1, "no format validated the int8 NV bias");
}
/// Test OpenGL PixelFormat::Nv12→PixelFormat::Rgba conversion against ffmpeg reference
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_opengl_nv12_to_rgba_reference() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
// Load PixelFormat::Nv12 source with DMA
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
// Load PixelFormat::Rgba reference (ffmpeg-generated)
let reference = load_raw_image(
1280,
720,
PixelFormat::Rgba,
None,
&edgefirst_bench::testdata::read("camera720p.rgba"),
)
.unwrap();
// Convert using OpenGL
let dst = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src;
let mut dst_dyn = dst;
gl.convert(&src_dyn, &mut dst_dyn, None).unwrap();
// Copy to CPU for comparison
let cpu_dst = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
cpu_dst
.as_u8()
.unwrap()
.map()
.unwrap()
.as_mut_slice()
.copy_from_slice(dst_dyn.as_u8().unwrap().map().unwrap().as_slice());
// Post-WS1 the GL NV path threads per-tensor colorimetry (same coeffs as
// CPU/ffmpeg for the resolved encoding+range), so the YUV-matrix delta
// that forced 0.95 has closed; restored to the pre-WIP 0.98.
compare_images(&reference, &cpu_dst, 0.98, "opengl_nv12_to_rgba_reference");
}
/// Test OpenGL PixelFormat::Yuyv→PixelFormat::Rgba conversion against ffmpeg reference
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_opengl_yuyv_to_rgba_reference() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
// Load PixelFormat::Yuyv source with DMA
let src = load_raw_image(
1280,
720,
PixelFormat::Yuyv,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.yuyv"),
)
.unwrap();
// Load PixelFormat::Rgba reference (ffmpeg-generated)
let reference = load_raw_image(
1280,
720,
PixelFormat::Rgba,
None,
&edgefirst_bench::testdata::read("camera720p.rgba"),
)
.unwrap();
// Convert using OpenGL
let dst = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src;
let mut dst_dyn = dst;
gl.convert(&src_dyn, &mut dst_dyn, None).unwrap();
// Copy to CPU for comparison
let cpu_dst = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
cpu_dst
.as_u8()
.unwrap()
.map()
.unwrap()
.as_mut_slice()
.copy_from_slice(dst_dyn.as_u8().unwrap().map().unwrap().as_slice());
// Post-WS1 the GL YUYV path applies the resolved colorimetry via the EGL
// YUV color-space/sample-range hints (dma_import), so the YUV-matrix
// delta that forced 0.95 has closed; restored to the pre-WIP 0.98.
// (Driver matrix may differ from CPU by rounding — confirmed on the GPU
// lanes.)
compare_images(&reference, &cpu_dst, 0.98, "opengl_yuyv_to_rgba_reference");
}
/// On-target (V3D) regression for the EGLImage cache `plane_offset` key:
/// render two distinct sources into two `plane_offset` sub-views of ONE
/// DMA-BUF and assert each window matches a standalone full-buffer convert.
///
/// The two views share the parent's `BufferIdentity` but start at different
/// byte offsets. Before the cache-key fix the second view aliased the
/// first (offset-0) EGLImage, so both rendered into the base region — the
/// exact failure that capped batched render-to-DMA-BUF. With the fix each
/// offset gets its own EGLImage and the buffer is correctly partitioned.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn opengl_render_into_dma_subviews_no_aliasing() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
let frame = w * h * 4; // RGBA bytes per frame
// Two distinct solid NV12 sources (different luma → different grey).
let make_nv12 = |y: u8| {
let mut buf = vec![y; w * h];
buf.extend(std::iter::repeat_n(128u8, w * h / 2)); // neutral chroma
buf
};
let src0 = load_raw_image(
w,
h,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&make_nv12(50),
)
.unwrap();
let src1 = load_raw_image(
w,
h,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&make_nv12(200),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(s, d, None).unwrap();
};
// Standalone full-buffer reference conversions (independent buffers).
let mut ref0 = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &src0, &mut ref0);
let mut ref1 = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &src1, &mut ref1);
// One DMA-BUF holding two stacked RGBA frames; two offset sub-views
// sharing the parent buffer identity (same fd) on the SAME processor,
// so view 1's lookup hits view 0's cache entry unless the key carries
// the offset.
let parent = TensorDyn::image(
w,
2 * h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut view0 = parent.view(crate::Region::new(0, 0, w, h)).unwrap();
let mut view1 = parent.view(crate::Region::new(0, h, w, h)).unwrap();
assert_eq!(view1.plane_offset(), Some(frame));
convert(&mut gl, &src0, &mut view0);
convert(&mut gl, &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 (offset 0) must match a standalone convert of src0"
);
assert_eq!(
&parent_bytes[frame..2 * frame],
ref1_bytes.as_slice(),
"view 1 window (offset {frame}) must match a standalone convert of src1 — \
aliasing/cache-collision if it doesn't"
);
}
// =========================================================================
// Recycled DMA-BUF *source* stale-read regression
//
// A DMA-BUF-backed source that is CPU-written, GPU-sampled by convert(),
// and then RECYCLED across frames must reflect the latest write. The
// recycled buffer keeps a stable BufferIdentity, so the source EGLImage
// cache (keyed by BufferIdentity + chroma id + plane_offset) hits.
//
// The defect this guards against: a decode pool reuses ONE oversized buffer
// and calls `configure_image()` each frame, so the SAME fd is presented to
// convert() with a DIFFERENT geometry/stride every frame (e.g. a 128-wide
// pool decoding a 96-wide image). Because the cache key omits geometry, the
// cached EGLImage built for the previous frame's stride is reused and the
// GPU samples the buffer at the wrong pitch — deterministically wrong
// single-threaded, nondeterministic in parallel, correct on a heap source.
// (Recycling at CONSTANT geometry is fine — V3D re-fetches the DMA-BUF each
// draw — so the constant-geometry tests below pass on buggy and fixed code
// alike; the geometry-change test is the one that fails pre-fix.)
//
// Oracle = a FRESH DMA source of the same content+geometry (new identity →
// cache miss → correct convert). Same code path as the recycled source; the
// only difference is buffer identity.
// =========================================================================
/// Overwrite an existing tensor's bytes in place (re-map → copy → drop →
/// DMA_BUF_IOCTL_SYNC(END)), simulating a pool recycle of one buffer.
///
/// Through [`write_tight_rows`], like the fresh-source half of the same
/// tests: the recycled buffer and the oracle must be laid out identically,
/// or the comparison measures the two writers' disagreement instead of the
/// stale read it is looking for.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn overwrite_in_place(t: &TensorDyn, bytes: &[u8]) {
write_tight_rows(t, bytes).unwrap();
}
/// Write image A into a DMA source, convert, then overwrite the SAME source
/// with distinct image B and convert again on the SAME processor. Assert the
/// second output matches a fresh-DMA-source convert of B (no stale read).
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_stale_read_check(
w: usize,
h: usize,
src_fmt: PixelFormat,
bytes_a: &[u8],
bytes_b: &[u8],
tolerance: u8,
) {
// ONE recycled DMA-BUF source, reused across two "frames".
let src = load_raw_image(w, h, src_fmt, Some(TensorMemory::DmaBuf), bytes_a).unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(s, d, None).unwrap();
};
// Frame A: warms the src EGLImage cache + texture binding.
let mut dst_a = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &src, &mut dst_a);
let dst_a_bytes = dst_a.as_u8().unwrap().map().unwrap().to_vec();
// Frame B: overwrite the SAME buffer (same fd / BufferIdentity), convert
// again. Cache HIT + binding-skip → this is where the stale read fires.
overwrite_in_place(&src, bytes_b);
let mut dst_b = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &src, &mut dst_b);
let dst_b_bytes = dst_b.as_u8().unwrap().map().unwrap().to_vec();
// Oracle: a fresh DMA source of B (new identity → cache miss → correct).
let fresh_b = load_raw_image(w, h, src_fmt, Some(TensorMemory::DmaBuf), bytes_b).unwrap();
let mut oracle_b = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &fresh_b, &mut oracle_b);
let oracle_b_bytes = oracle_b.as_u8().unwrap().map().unwrap().to_vec();
// Guard against bad test data: A and B must produce different output, or
// the test could never distinguish stale from correct.
assert_ne!(
dst_a_bytes, oracle_b_bytes,
"test data invalid for {src_fmt:?}: frame A and frame B convert identically"
);
// The bug: dst_b carries frame-A content (stale) instead of frame-B.
assert_pixels_match(&oracle_b_bytes, &dst_b_bytes, tolerance);
}
/// Grey source (profiler's decode-pool format; EXTERNAL_OES Path A).
/// Grey→Rgba is a scalar luma replicate (no YUV matrix) → byte-exact.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_grey_stale_read() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
dma_recycle_stale_read_check(
w,
h,
PixelFormat::Grey,
&vec![50u8; w * h],
&vec![200u8; w * h],
0,
);
}
/// NV12 source (EXTERNAL_OES Path A on Vivante / R8 texelFetch Path B on
/// V3D/Mali). YUV→Rgba carries a small color-matrix rounding → tolerance 4.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_nv12_stale_read() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
let make_nv12 = |y: u8| {
let mut buf = vec![y; w * h];
buf.extend(std::iter::repeat_n(128u8, w * h / 2)); // neutral chroma
buf
};
dma_recycle_stale_read_check(w, h, PixelFormat::Nv12, &make_nv12(50), &make_nv12(200), 4);
}
/// NV16 source (full-res chroma; R8 texelFetch Path B). tolerance 4.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_nv16_stale_read() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
let make_nv16 = |y: u8| {
let mut buf = vec![y; w * h];
buf.extend(std::iter::repeat_n(128u8, w * h)); // full-res neutral chroma
buf
};
dma_recycle_stale_read_check(w, h, PixelFormat::Nv16, &make_nv16(50), &make_nv16(200), 4);
}
/// Small-pool recycle: 2 DMA-BUF sources round-robined over 5 distinct
/// solid-fill frames; every GPU output must equal a fresh-source convert of
/// the same frame. Exercises the cache/LRU interaction across more than one
/// recycled identity.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_pool_recycle_all_frames_match_oracle() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
let lumas: [u8; 5] = [20, 70, 130, 180, 240];
let pool = [
TensorDyn::image(
w,
h,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap(),
TensorDyn::image(
w,
h,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap(),
];
let mut gl = GLProcessorThreaded::new(None).unwrap();
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(s, d, None).unwrap();
};
for (frame, &luma) in lumas.iter().enumerate() {
let buf = &pool[frame % pool.len()];
overwrite_in_place(buf, &vec![luma; w * h]);
let mut gpu = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, buf, &mut gpu);
// Fresh-source oracle for this exact frame.
let fresh = load_raw_image(
w,
h,
PixelFormat::Grey,
Some(TensorMemory::DmaBuf),
&vec![luma; w * h],
)
.unwrap();
let mut oracle = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &fresh, &mut oracle);
let oracle_map = oracle.as_u8().unwrap().map().unwrap();
let gpu_map = gpu.as_u8().unwrap().map().unwrap();
assert_pixels_match(oracle_map.as_slice(), gpu_map.as_slice(), 0);
}
}
/// Fill `[h][w]` of `t`'s buffer with a non-uniform 2D pattern at the
/// tensor's effective row stride. Non-uniform content is essential: a solid
/// fill survives any stride/geometry misread, so it could not detect the
/// cache-key bug.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn fill_grey_pattern(t: &TensorDyn, w: usize, h: usize, salt: u8) {
let stride = t.effective_row_stride().unwrap_or(w);
let mut map = t.as_u8().unwrap().map().unwrap();
let buf = map.as_mut_slice();
for r in 0..h {
for c in 0..w {
buf[r * stride + c] = ((r * 13 + c * 7) as u8).wrapping_add(salt);
}
}
}
/// THE faithful profiler repro. One oversized DMA pool buffer is recycled
/// across frames of DIFFERENT geometry via `configure_image()` (exactly what
/// the JPEG decoder does into `create_decode_source_pool`). Each frame's GPU
/// convert must equal a fresh-source convert of the same geometry+content.
///
/// Pre-fix: frame N hits the cached EGLImage built for an earlier frame's
/// stride and samples the buffer at the wrong pitch → mismatch. This test
/// FAILS on buggy main and passes once the cache key carries geometry.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_geometry_change_stale_read() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
// Oversized pool (like the profiler's pool_w x 3*max_h R8 surface),
// recycled in place via configure_image — keeps ONE BufferIdentity.
let mut pool = TensorDyn::image(
128,
128,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(s, d, None).unwrap();
};
// A sequence of DISTINCT geometries (varying width → varying stride),
// each with distinct content. Reusing the same buffer means every frame
// shares the pool's BufferIdentity but needs its own EGLImage geometry.
let frames: [(usize, usize, u8); 4] =
[(128, 96, 0), (96, 128, 40), (120, 100, 80), (64, 128, 120)];
for (i, &(w, h, salt)) in frames.iter().enumerate() {
// Recycled pool: reconfigure to this frame's geometry, write, convert.
pool.configure_image(w, h, PixelFormat::Grey).unwrap();
fill_grey_pattern(&pool, w, h, salt);
let mut dst_recycled = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &pool, &mut dst_recycled);
let recycled_bytes = dst_recycled.as_u8().unwrap().map().unwrap().to_vec();
// Fresh-source oracle: new buffer, same geometry+content.
let fresh = TensorDyn::image(
w,
h,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_grey_pattern(&fresh, w, h, salt);
let mut dst_fresh = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &fresh, &mut dst_fresh);
let fresh_bytes = dst_fresh.as_u8().unwrap().map().unwrap().to_vec();
assert_eq!(
recycled_bytes.len(),
fresh_bytes.len(),
"frame {i} ({w}x{h}): output size mismatch"
);
assert_pixels_match(&fresh_bytes, &recycled_bytes, 0);
}
}
/// Stronger guard for the parallel-decode manifestation: a POOL of pooled
/// buffers, each recycled through DIFFERENT geometries, INTERLEAVED on one
/// processor — the same shared-cache access pattern parallel decode threads
/// produce (which buffer+geometry populates the cache first is what varied
/// run-to-run, giving 822–833). With a geometry-aware key every
/// (buffer, geometry) has its own entry, so interleaving is order-
/// independent and every output must match its fresh-source oracle.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_pool_geometry_interleaved_stale_read() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let mut pool = [
TensorDyn::image(
128,
128,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap(),
TensorDyn::image(
128,
128,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap(),
];
let mut gl = GLProcessorThreaded::new(None).unwrap();
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(s, d, None).unwrap();
};
// Interleave buffers AND geometries: each step reuses a pool slot at a
// new size, so the cache sees the worst-case mix of identities+geometry.
let steps: [(usize, usize, usize, u8); 6] = [
(0, 128, 96, 0),
(1, 96, 128, 30),
(0, 64, 100, 60), // slot 0 reused at a 3rd geometry
(1, 120, 64, 90), // slot 1 reused at a 2nd geometry
(0, 128, 96, 120), // slot 0 back to its 1st geometry, new content
(1, 96, 128, 150),
];
for &(slot, w, h, salt) in steps.iter() {
pool[slot].configure_image(w, h, PixelFormat::Grey).unwrap();
fill_grey_pattern(&pool[slot], w, h, salt);
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &pool[slot], &mut dst);
let fresh = TensorDyn::image(
w,
h,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_grey_pattern(&fresh, w, h, salt);
let mut oracle = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &fresh, &mut oracle);
let dst_map = dst.as_u8().unwrap().map().unwrap();
let oracle_map = oracle.as_u8().unwrap().map().unwrap();
assert_pixels_match(oracle_map.as_slice(), dst_map.as_slice(), 0);
}
}
/// Regression guard: a single-shot (non-recycled) DMA source must equal a
/// fresh-source convert — the fix must not break the first-frame path.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_single_shot_grey_matches_fresh() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
let bytes = vec![128u8; w * h];
let mut gl = GLProcessorThreaded::new(None).unwrap();
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(s, d, None).unwrap();
};
let src =
load_raw_image(w, h, PixelFormat::Grey, Some(TensorMemory::DmaBuf), &bytes).unwrap();
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &src, &mut dst);
let fresh =
load_raw_image(w, h, PixelFormat::Grey, Some(TensorMemory::DmaBuf), &bytes).unwrap();
let mut oracle = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
convert(&mut gl, &fresh, &mut oracle);
let oracle_map = oracle.as_u8().unwrap().map().unwrap();
let dst_map = dst.as_u8().unwrap().map().unwrap();
assert_pixels_match(oracle_map.as_slice(), dst_map.as_slice(), 0);
}
// =========================================================================
// EGL Display Probe & Override Tests
// =========================================================================
/// Validate that probe_egl_displays() discovers available display types
/// and returns them in priority order (GBM first).
///
/// On headless i.MX hardware, GBM and PlatformDevice are typically
/// available. Default requires a running compositor (Wayland/X11) and
/// may not be present on headless targets.
#[test]
#[cfg(target_os = "linux")] // Linux display probing
fn test_probe_egl_displays() {
let displays = match probe_egl_displays() {
Ok(d) => d,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - EGL not available: {e:?}",
function!()
));
return;
}
};
if displays.is_empty() {
crate::test_support::report_skip(&format!(
"{} - No EGL displays available",
function!()
));
return;
}
let kinds: Vec<_> = displays.iter().map(|d| d.kind).collect();
eprintln!("Probed EGL displays: {kinds:?}");
for d in &displays {
eprintln!(" {:?}: {}", d.kind, d.description);
}
// Verify priority ordering: PlatformDevice > GBM > Default.
// Not all display types are available on every system, but the
// ones that are present must appear in this order.
let priority = |k: &EglDisplayKind| match k {
EglDisplayKind::PlatformDevice => 0,
EglDisplayKind::Gbm => 1,
EglDisplayKind::Default => 2,
};
for w in kinds.windows(2) {
assert!(
priority(&w[0]) < priority(&w[1]),
"Display ordering violated: {:?} should come after {:?}",
w[1],
w[0],
);
}
}
/// Validate that probe_egl_displays() populates the shared display and
/// that a subsequent GLProcessorThreaded::new() reuses it without
/// deadlocking.
#[test]
#[cfg(target_os = "linux")] // Linux display probing
fn test_probe_then_create_gl_context() {
let displays = match probe_egl_displays() {
Ok(d) => d,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - EGL not available: {e:?}",
function!()
));
return;
}
};
if displays.is_empty() {
crate::test_support::report_skip(&format!(
"{} - No EGL displays available",
function!()
));
return;
}
eprintln!(
"Probed displays: {:?}",
displays.iter().map(|d| d.kind).collect::<Vec<_>>()
);
// Now create a GL processor — should reuse the shared display
let mut gl = match GLProcessorThreaded::new(None) {
Ok(gl) => gl,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GLProcessorThreaded failed: {e:?}",
function!()
));
return;
}
};
// Verify it works by doing a simple convert
let src = edgefirst_tensor::TensorDyn::image(
64,
64,
edgefirst_tensor::PixelFormat::Rgba,
edgefirst_tensor::DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("create src failed");
let mut dst = edgefirst_tensor::TensorDyn::image(
32,
32,
edgefirst_tensor::PixelFormat::Rgba,
edgefirst_tensor::DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("create dst failed");
gl.convert(&src, &mut dst, None).expect("convert failed");
assert_eq!(dst.width(), Some(32));
assert_eq!(dst.height(), Some(32));
}
/// Validate that explicitly selecting each available display kind via
/// GLProcessorThreaded::new(Some(kind)) succeeds and produces a working
/// converter.
#[test]
#[cfg(target_os = "linux")] // Linux display probing
fn test_override_each_display_kind() {
let displays = match probe_egl_displays() {
Ok(d) => d,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - EGL not available: {e:?}",
function!()
));
return;
}
};
if displays.is_empty() {
crate::test_support::report_skip(&format!(
"{} - No EGL displays available",
function!()
));
return;
}
for display in &displays {
eprintln!(
"Testing override: {:?} ({})",
display.kind, display.description
);
let mut gl = match GLProcessorThreaded::new(Some(display.kind)) {
Ok(gl) => gl,
// Hosted Ubuntu 24.04 exposes Mesa llvmpipe as PlatformDevice.
// Production rejects software GL unless EDGEFIRST_ALLOW_SOFTWARE_GL=1
// (the Full software-GL lane). Skip that kind here instead of panicking.
Err(crate::Error::NotSupported(msg))
if msg.contains("software OpenGL renderer") =>
{
crate::test_support::report_skip(&format!(
"{} - {:?}: {msg}",
function!(),
display.kind
));
continue;
}
Err(e) => panic!(
"GLProcessorThreaded::new(Some({:?})) failed: {e:?}",
display.kind
),
};
// Smoke test: do a simple PixelFormat::Rgba → PixelFormat::Rgba conversion to verify the
// GL context is fully functional.
let src = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("zidane.jpg"),
Some(PixelFormat::Rgba),
None,
)
.unwrap();
let dst = TensorDyn::image(
320,
240,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_dyn = src;
let mut dst_dyn = dst;
gl.convert(&src_dyn, &mut dst_dyn, None)
.unwrap_or_else(|e| {
panic!("convert() with {:?} display failed: {e:?}", display.kind)
});
eprintln!(" {:?} display: convert OK", display.kind);
}
}
/// Validate that requesting a display kind that doesn't exist on the
/// system returns an error rather than falling back silently.
#[test]
#[cfg(target_os = "linux")] // Linux display probing
fn test_override_unavailable_display_errors() {
let displays = match probe_egl_displays() {
Ok(d) => d,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - EGL not available: {e:?}",
function!()
));
return;
}
};
let available_kinds: Vec<_> = displays.iter().map(|d| d.kind).collect();
// Find a kind that is NOT available; if all three are available,
// this test has nothing to verify — skip it.
let unavailable = [
EglDisplayKind::PlatformDevice,
EglDisplayKind::Gbm,
EglDisplayKind::Default,
]
.into_iter()
.find(|k| !available_kinds.contains(k));
if let Some(kind) = unavailable {
eprintln!("Testing override with unavailable kind: {kind:?}");
let result = GLProcessorThreaded::new(Some(kind));
assert!(
result.is_err(),
"Expected error for unavailable display kind {kind:?}, got Ok"
);
eprintln!(" Correctly returned error: {:?}", result.unwrap_err());
} else {
crate::test_support::report_skip(&format!(
"{} - All three display kinds are available",
function!()
));
}
}
/// Validate that auto-detection (None) still works — this is the existing
/// default behaviour and must not regress.
#[test]
#[cfg(target_os = "linux")] // Linux display probing
fn test_auto_detect_display() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = GLProcessorThreaded::new(None).expect("auto-detect should succeed");
let src = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("zidane.jpg"),
Some(PixelFormat::Rgba),
None,
)
.unwrap();
let dst = TensorDyn::image(
320,
240,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_dyn = src;
let mut dst_dyn = dst;
gl.convert(&src_dyn, &mut dst_dyn, None)
.expect("auto-detect convert should succeed");
}
#[test]
fn test_packed_rgb_width_constraint() {
// Standard ML model input widths — all satisfy W*3 % 4 == 0
assert_eq!((640usize * 3) % 4, 0);
assert_eq!((320usize * 3) % 4, 0);
assert_eq!((1280usize * 3) % 4, 0);
// Non-divisible widths should be rejected
assert_ne!((322usize * 3) % 4, 0);
assert_ne!((333usize * 3) % 4, 0);
}
// =========================================================================
// Packed PixelFormat::Rgb Correctness Tests (two-pass pipeline)
// These tests compare GL PixelFormat::Rgba output (alpha stripped) against GL packed
// PixelFormat::Rgb output. Both use the same GPU color conversion, so differences
// isolate packing shader bugs rather than CPU-vs-GPU YUV conversion.
// They require DMA + OpenGL hardware (on-target only).
// =========================================================================
/// Compare two byte slices pixel-by-pixel with tolerance.
/// Panics with details if any byte differs by more than `tolerance`.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn assert_pixels_match(expected: &[u8], actual: &[u8], tolerance: u8) {
assert_eq!(expected.len(), actual.len(), "Buffer size mismatch");
let mut max_diff: u8 = 0;
let mut diff_count: usize = 0;
let mut first_diff_idx = None;
for (i, (&e, &a)) in expected.iter().zip(actual.iter()).enumerate() {
let diff = (e as i16 - a as i16).unsigned_abs() as u8;
if diff > tolerance {
diff_count += 1;
if first_diff_idx.is_none() {
first_diff_idx = Some(i);
}
}
max_diff = max_diff.max(diff);
}
assert!(
diff_count == 0,
"Pixel mismatch: {diff_count} bytes differ (max_diff={max_diff}, first at index {})",
first_diff_idx.unwrap_or(0)
);
}
/// Build a letterbox crop that fits src into dst_w x dst_h, preserving aspect ratio.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn letterbox_crop(_src_w: usize, _src_h: usize, _dst_w: usize, _dst_h: usize) -> Crop {
// Letterbox placement is now computed by the backend from the actual
// src/dst dims (identical centred aspect-fit math); the helper just
// selects the pad colour.
Crop::letterbox([114, 114, 114, 255])
}
/// Strip alpha from PixelFormat::Rgba bytes → packed PixelFormat::Rgb bytes.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn rgba_to_rgb(rgba: &[u8]) -> Vec<u8> {
assert_eq!(
rgba.len() % 4,
0,
"PixelFormat::Rgba buffer length must be divisible by 4"
);
let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);
for pixel in rgba.as_chunks::<4>().0 {
rgb.push(pixel[0]);
rgb.push(pixel[1]);
rgb.push(pixel[2]);
}
rgb
}
/// Convert uint8 PixelFormat::Rgb bytes to int8 (XOR 0x80 each byte).
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn uint8_to_int8(data: &[u8]) -> Vec<u8> {
data.iter().map(|&b| b ^ 0x80).collect()
}
/// PixelFormat::Yuyv 1080p → PixelFormat::Rgb 640x640 with letterbox (two-pass packed PixelFormat::Rgb pipeline).
/// Compares GL PixelFormat::Rgba (alpha-stripped) against GL packed PixelFormat::Rgb to validate packing.
#[test]
// Portable since packed-RGB u8 gained its RGBA8888 IOSurface mapping
// (`packed_rgb888_layout`): the fixture allocates on macOS too, and the
// two-pass packed-RGB pipeline runs zero-copy on both backends.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_opengl_rgb_correctness() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(
"test_opengl_rgb_correctness - zero-copy GPU image buffers not available",
);
return;
}
let src_dma = load_raw_image(
1920,
1080,
PixelFormat::Yuyv,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera1080p.yuyv"),
)
.unwrap();
let crop = letterbox_crop(1920, 1080, 640, 640);
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src_dma;
// GL PixelFormat::Rgba reference
let dst_rgba = TensorDyn::image(
640,
640,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dst_rgba_dyn = dst_rgba;
gl.convert(
&src_dyn,
&mut dst_rgba_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
// GL packed PixelFormat::Rgb output
let dst_rgb = TensorDyn::image(
640,
640,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dst_rgb_dyn = dst_rgb;
gl.convert(
&src_dyn,
&mut dst_rgb_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let rgba_data = dst_rgba_dyn.as_u8().unwrap().map().unwrap();
let expected_rgb = rgba_to_rgb(rgba_data.as_slice());
let gl_data = dst_rgb_dyn.as_u8().unwrap().map().unwrap();
assert_pixels_match(&expected_rgb, gl_data.as_slice(), 1);
}
/// PixelFormat::Yuyv 1080p → PixelFormat::Rgb 640x640 with letterbox.
/// Compares GL PixelFormat::Rgba (alpha-stripped, XOR 0x80) against GL packed PixelFormat::Rgb.
#[test]
// Portable since packed-RGB u8 gained its RGBA8888 IOSurface mapping
// (see test_opengl_rgb_correctness).
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_opengl_rgb_int8_correctness() {
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(
"test_opengl_rgb_int8_correctness - zero-copy GPU image buffers not available",
);
return;
}
let src_dma = load_raw_image(
1920,
1080,
PixelFormat::Yuyv,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera1080p.yuyv"),
)
.unwrap();
let crop = letterbox_crop(1920, 1080, 640, 640);
// GLProcessorThreaded (not ST) so the test runs portably on
// macOS/ANGLE too — same shape as the sibling u8 test.
let mut gl = match GLProcessorThreaded::new(None) {
Ok(gl) => gl,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// Two-pass packed RGB is now supported on the DMA backend.
let src_dyn = src_dma;
// GL PixelFormat::Rgba reference
let dst_rgba = TensorDyn::image(
640,
640,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dst_rgba_dyn = dst_rgba;
gl.convert(
&src_dyn,
&mut dst_rgba_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
// GL packed PixelFormat::Rgb int8 output (two-pass path with XOR 0x80 bias)
let dst_rgb = TensorDyn::image(
640,
640,
PixelFormat::Rgb,
DType::I8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dst_rgb_dyn = dst_rgb;
gl.convert(
&src_dyn,
&mut dst_rgb_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let rgba_data = dst_rgba_dyn.as_u8().unwrap().map().unwrap();
let expected_rgb = uint8_to_int8(&rgba_to_rgb(rgba_data.as_slice()));
// Map raw i8 bytes as u8 for comparison — the XOR 0x80 bias is in the data.
let gl_data = dst_rgb_dyn.as_i8().unwrap().map().unwrap();
let gl_bytes: &[u8] = unsafe {
std::slice::from_raw_parts(gl_data.as_slice().as_ptr().cast(), gl_data.len())
};
assert_pixels_match(&expected_rgb, gl_bytes, 1);
}
/// PixelFormat::Yuyv 1080p → PixelFormat::Rgb 1920x1080 (no letterbox, same size).
/// Compares GL PixelFormat::Rgba (alpha-stripped) against GL packed PixelFormat::Rgb without scaling.
#[test]
// Portable since packed-RGB u8 gained its RGBA8888 IOSurface mapping
// (`packed_rgb888_layout`): the fixture allocates on macOS too, and the
// two-pass packed-RGB pipeline runs zero-copy on both backends.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_opengl_rgb_no_letterbox_correctness() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip("test_opengl_rgb_no_letterbox_correctness - zero-copy GPU image buffers not available");
return;
}
let src_dma = load_raw_image(
1920,
1080,
PixelFormat::Yuyv,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera1080p.yuyv"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src_dma;
// GL PixelFormat::Rgba reference (no letterbox — 1920 satisfies W*3 % 4 == 0)
let dst_rgba = TensorDyn::image(
1920,
1080,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dst_rgba_dyn = dst_rgba;
gl.convert(&src_dyn, &mut dst_rgba_dyn, None).unwrap();
// GL packed PixelFormat::Rgb output
let dst_rgb = TensorDyn::image(
1920,
1080,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dst_rgb_dyn = dst_rgb;
gl.convert(&src_dyn, &mut dst_rgb_dyn, None).unwrap();
let rgba_data = dst_rgba_dyn.as_u8().unwrap().map().unwrap();
let expected_rgb = rgba_to_rgb(rgba_data.as_slice());
let gl_data = dst_rgb_dyn.as_u8().unwrap().map().unwrap();
assert_pixels_match(&expected_rgb, gl_data.as_slice(), 1);
}
// ---- PixelFormat::Bgra destination tests ----
/// Test OpenGL PixelFormat::Nv12→PixelFormat::Bgra conversion with DMA buffers.
/// Compares against PixelFormat::Nv12→PixelFormat::Rgba by verifying R↔B swap.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_opengl_nv12_to_bgra() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(
"test_opengl_nv12_to_bgra - no zero-copy GPU buffers or OpenGL",
);
return;
}
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src;
// Convert to PixelFormat::Rgba as reference
let rgba_dst = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut rgba_dst_dyn = rgba_dst;
gl.convert(&src_dyn, &mut rgba_dst_dyn, None).unwrap();
// Convert to PixelFormat::Bgra
let bgra_dst = TensorDyn::image(
1280,
720,
PixelFormat::Bgra,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut bgra_dst_dyn = bgra_dst;
gl.convert(&src_dyn, &mut bgra_dst_dyn, None).unwrap();
// Compare: PixelFormat::Bgra[B,G,R,A] should match PixelFormat::Rgba[R,G,B,A] with R↔B swapped
let bgra_map = bgra_dst_dyn.as_u8().unwrap().map().unwrap();
let rgba_map = rgba_dst_dyn.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());
let mut max_diff = 0i32;
for (bc, rc) in bgra_buf
.as_chunks::<4>()
.0
.iter()
.zip(rgba_buf.as_chunks::<4>().0)
{
max_diff = max_diff.max((bc[0] as i32 - rc[2] as i32).abs()); // B
max_diff = max_diff.max((bc[1] as i32 - rc[1] as i32).abs()); // G
max_diff = max_diff.max((bc[2] as i32 - rc[0] as i32).abs()); // R
max_diff = max_diff.max((bc[3] as i32 - rc[3] as i32).abs()); // A
}
eprintln!("PixelFormat::Nv12→PixelFormat::Bgra vs PixelFormat::Nv12→PixelFormat::Rgba max channel diff: {max_diff}");
assert!(
max_diff <= 1,
"PixelFormat::Bgra/PixelFormat::Rgba channel mismatch > 1: max_diff={max_diff}"
);
}
/// Test OpenGL PixelFormat::Yuyv→PixelFormat::Bgra conversion with DMA buffers.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_opengl_yuyv_to_bgra() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(
"test_opengl_yuyv_to_bgra - no zero-copy GPU buffers or OpenGL",
);
return;
}
let src = load_raw_image(
1280,
720,
PixelFormat::Yuyv,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.yuyv"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src;
let rgba_dst = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut rgba_dst_dyn = rgba_dst;
gl.convert(&src_dyn, &mut rgba_dst_dyn, None).unwrap();
let bgra_dst = TensorDyn::image(
1280,
720,
PixelFormat::Bgra,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut bgra_dst_dyn = bgra_dst;
gl.convert(&src_dyn, &mut bgra_dst_dyn, None).unwrap();
let bgra_map = bgra_dst_dyn.as_u8().unwrap().map().unwrap();
let rgba_map = rgba_dst_dyn.as_u8().unwrap().map().unwrap();
let bgra_buf = bgra_map.as_slice();
let rgba_buf = rgba_map.as_slice();
let mut max_diff = 0i32;
for (bc, rc) in bgra_buf
.as_chunks::<4>()
.0
.iter()
.zip(rgba_buf.as_chunks::<4>().0)
{
max_diff = max_diff.max((bc[0] as i32 - rc[2] as i32).abs());
max_diff = max_diff.max((bc[1] as i32 - rc[1] as i32).abs());
max_diff = max_diff.max((bc[2] as i32 - rc[0] as i32).abs());
max_diff = max_diff.max((bc[3] as i32 - rc[3] as i32).abs());
}
eprintln!("PixelFormat::Yuyv→PixelFormat::Bgra vs PixelFormat::Yuyv→PixelFormat::Rgba max channel diff: {max_diff}");
assert!(
max_diff <= 1,
"PixelFormat::Bgra/PixelFormat::Rgba channel mismatch > 1: max_diff={max_diff}"
);
}
/// Test draw_decoded_masks() with PixelFormat::Bgra destination (segmentation).
/// Draws the same masks to both PixelFormat::Rgba and PixelFormat::Bgra, then verifies R↔B swap.
#[test]
fn test_draw_decoded_masks_bgra() {
use edgefirst_tensor::Segmentation;
if !is_opengl_available() {
crate::test_support::report_skip("test_draw_decoded_masks_bgra - OpenGL not available");
return;
}
let seg_bytes = edgefirst_bench::testdata::read("modelpack_seg_2x160x160.bin").to_vec();
// Build segmentation data (shared between both renders)
let make_seg = || {
let mut s = Array3::from_shape_vec((2, 160, 160), seg_bytes.clone()).unwrap();
s.swap_axes(0, 1);
s.swap_axes(1, 2);
let s = s.as_standard_layout().to_owned();
Segmentation {
segmentation: edgefirst_tensor::Tensor::from_arrayview3(s.view())
.unwrap()
.into(),
xmin: 0.0,
ymin: 0.0,
xmax: 1.0,
ymax: 1.0,
}
};
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Render to PixelFormat::Rgba
let rgba_img = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
None,
)
.unwrap();
let mut rgba_img_dyn = rgba_img;
gl.draw_decoded_masks(&mut rgba_img_dyn, &[], &[make_seg()], Default::default())
.unwrap();
// Render to PixelFormat::Bgra (convert source to PixelFormat::Bgra first)
let rgba_src = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
None,
)
.unwrap();
let bgra_img = TensorDyn::image(
rgba_src.width().unwrap(),
rgba_src.height().unwrap(),
PixelFormat::Bgra,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let rgba_src_dyn = rgba_src;
let mut bgra_img_dyn = bgra_img;
gl.convert(&rgba_src_dyn, &mut bgra_img_dyn, None).unwrap();
gl.draw_decoded_masks(&mut bgra_img_dyn, &[], &[make_seg()], Default::default())
.unwrap();
// Verify PixelFormat::Bgra output matches PixelFormat::Rgba output with R↔B swapped
let rgba_map = rgba_img_dyn.as_u8().unwrap().map().unwrap();
let bgra_map = bgra_img_dyn.as_u8().unwrap().map().unwrap();
let rgba_buf = rgba_map.as_slice();
let bgra_buf = bgra_map.as_slice();
assert_eq!(rgba_buf.len(), bgra_buf.len());
let mut max_diff = 0i32;
for (rc, bc) in rgba_buf
.as_chunks::<4>()
.0
.iter()
.zip(bgra_buf.as_chunks::<4>().0)
{
max_diff = max_diff.max((rc[0] as i32 - bc[2] as i32).abs()); // R
max_diff = max_diff.max((rc[1] as i32 - bc[1] as i32).abs()); // G
max_diff = max_diff.max((rc[2] as i32 - bc[0] as i32).abs()); // B
max_diff = max_diff.max((rc[3] as i32 - bc[3] as i32).abs()); // A
}
eprintln!("draw_decoded_masks PixelFormat::Bgra vs PixelFormat::Rgba max channel diff: {max_diff}");
assert!(
max_diff <= 1,
"draw_decoded_masks PixelFormat::Bgra/PixelFormat::Rgba channel mismatch > 1: max_diff={max_diff}"
);
}
/// Test draw_decoded_masks() with PixelFormat::Bgra destination using Mem memory (boxes).
/// Draws same boxes to PixelFormat::Rgba and PixelFormat::Bgra, then verifies R↔B swap.
#[test]
fn test_draw_decoded_masks_bgra_mem() {
use edgefirst_tensor::DetectBox;
if !is_opengl_available() {
crate::test_support::report_skip(
"test_draw_decoded_masks_bgra_mem - OpenGL not available",
);
return;
}
let detect = DetectBox {
bbox: [0.59375, 0.25, 0.9375, 0.725].into(),
score: 0.99,
label: 0,
};
let colors = [[255, 255, 0, 233], [128, 128, 255, 100]];
let mut gl = GLProcessorThreaded::new(None).unwrap();
gl.set_class_colors(&colors).unwrap();
// Render boxes to PixelFormat::Rgba
let rgba_img = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
Some(edgefirst_tensor::TensorMemory::Mem),
)
.unwrap();
let mut rgba_img_dyn = rgba_img;
gl.draw_decoded_masks(&mut rgba_img_dyn, &[detect], &[], Default::default())
.unwrap();
// Render boxes to PixelFormat::Bgra
let rgba_src = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
Some(edgefirst_tensor::TensorMemory::Mem),
)
.unwrap();
let bgra_img = TensorDyn::image(
rgba_src.width().unwrap(),
rgba_src.height().unwrap(),
PixelFormat::Bgra,
DType::U8,
Some(edgefirst_tensor::TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let rgba_src_dyn = rgba_src;
let mut bgra_img_dyn = bgra_img;
gl.convert(&rgba_src_dyn, &mut bgra_img_dyn, None).unwrap();
gl.draw_decoded_masks(&mut bgra_img_dyn, &[detect], &[], Default::default())
.unwrap();
// Verify PixelFormat::Bgra output matches PixelFormat::Rgba output with R↔B swapped
let rgba_map = rgba_img_dyn.as_u8().unwrap().map().unwrap();
let bgra_map = bgra_img_dyn.as_u8().unwrap().map().unwrap();
let rgba_buf = rgba_map.as_slice();
let bgra_buf = bgra_map.as_slice();
let mut max_diff = 0i32;
for (rc, bc) in rgba_buf
.as_chunks::<4>()
.0
.iter()
.zip(bgra_buf.as_chunks::<4>().0)
{
max_diff = max_diff.max((rc[0] as i32 - bc[2] as i32).abs());
max_diff = max_diff.max((rc[1] as i32 - bc[1] as i32).abs());
max_diff = max_diff.max((rc[2] as i32 - bc[0] as i32).abs());
max_diff = max_diff.max((rc[3] as i32 - bc[3] as i32).abs());
}
eprintln!(
"draw_decoded_masks_mem PixelFormat::Bgra vs PixelFormat::Rgba max channel diff: {max_diff}"
);
assert!(
max_diff <= 1,
"draw_decoded_masks_mem PixelFormat::Bgra/PixelFormat::Rgba channel mismatch > 1: max_diff={max_diff}"
);
}
// ========================================================================
// GL smoke tests for mask rendering and PBO destinations
// ========================================================================
#[test]
fn test_gl_mask_render_smoke() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = GLProcessorThreaded::new(None).unwrap();
let image = TensorDyn::image(
64,
64,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut image_dyn = image;
// Render with empty detections and segmentations — should succeed trivially
let result = gl.draw_decoded_masks(&mut image_dyn, &[], &[], Default::default());
assert!(
result.is_ok(),
"GL mask render with empty data should succeed: {result:?}"
);
// Verify output dimensions are unchanged
assert_eq!(image_dyn.width(), Some(64));
assert_eq!(image_dyn.height(), Some(64));
}
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn test_gl_pbo_destination_smoke() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let gl = GLProcessorThreaded::new(None).unwrap();
// PBOs are core GLES 3.0, so a live GL processor always serves one.
let pbo_img = gl
.create_pbo_image(64, 64, PixelFormat::Rgba)
.expect("allocate an RGBA8 PBO on the GL thread");
assert_eq!(pbo_img.width(), Some(64));
assert_eq!(pbo_img.height(), Some(64));
assert_eq!(pbo_img.format().unwrap(), PixelFormat::Rgba);
}
/// Regression test for the PBO deadlock fix in `convert_any_to_pbo`
/// (commit c494fae). Before the fix, the GL thread called
/// `tensor.map()` on the PBO destination, which sent a message back to
/// the very same GL thread and deadlocked the channel. The fix uses
/// `setup_renderbuffer_from_pbo` to bind the PBO via the GL buffer-
/// binding path, never reaching back through `map()`.
///
/// This test would hang indefinitely (or, with the channel
/// instrumentation, panic with "GL converter thread exited") if the
/// deadlock returned. A successful return proves the round-trip
/// completed.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn test_gl_convert_any_to_pbo_no_deadlock() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = GLProcessorThreaded::new(None).unwrap();
let pbo_dst = gl
.create_pbo_image(64, 64, PixelFormat::Rgba)
.expect("allocate the PBO destination");
let src = Tensor::<u8>::image(
64,
64,
PixelFormat::Rgba,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("Mem source tensor");
// Fill source with a deterministic pattern so a regression that
// produces a black/empty PBO would be detectable downstream.
{
let mut map = src.map().unwrap();
let slice: &mut [u8] = &mut map;
for (i, b) in slice.iter_mut().enumerate() {
*b = (i & 0xFF) as u8;
}
}
let src_dyn = TensorDyn::from(src);
let mut dst_dyn = TensorDyn::from(pbo_dst);
// The convert call is the deadlock site. If it returns at all the
// fix is intact. We do not assert pixel-perfect contents here —
// that is covered by other GL tests; this is a liveness regression
// gate.
let res = gl.convert(&src_dyn, &mut dst_dyn, None);
match res {
Ok(()) => {
assert_eq!(dst_dyn.width(), Some(64));
assert_eq!(dst_dyn.height(), Some(64));
}
Err(e) => {
// GL convert may legitimately fail on this CI host for
// reasons unrelated to the deadlock (e.g. missing
// extensions). Only fail the test on the deadlock
// signature itself.
let msg = format!("{e:?}");
assert!(
!msg.contains("GL converter thread exited"),
"PBO destination convert deadlocked: {msg}"
);
crate::test_support::report_skip(&format!(
"{} - convert failed unrelated: {msg}",
function!()
));
}
}
}
/// Regression test for the `convert_pbo_to_pbo` deadlock path. Same
/// underlying defect as `convert_any_to_pbo`; both sites were patched
/// in commit c494fae and both need explicit coverage.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn test_gl_convert_pbo_to_pbo_no_deadlock() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = GLProcessorThreaded::new(None).unwrap();
let pbo_src = gl
.create_pbo_image(64, 64, PixelFormat::Rgba)
.expect("allocate the PBO source");
let pbo_dst = gl
.create_pbo_image(64, 64, PixelFormat::Rgba)
.expect("allocate the PBO destination");
let src_dyn = TensorDyn::from(pbo_src);
let mut dst_dyn = TensorDyn::from(pbo_dst);
let res = gl.convert(&src_dyn, &mut dst_dyn, None);
match res {
Ok(()) => {
assert_eq!(dst_dyn.width(), Some(64));
}
Err(e) => {
let msg = format!("{e:?}");
assert!(
!msg.contains("GL converter thread exited"),
"PBO→PBO convert deadlocked: {msg}"
);
crate::test_support::report_skip(&format!(
"{} - convert failed unrelated: {msg}",
function!()
));
}
}
}
/// A PBO-backed SOURCE into a PLANAR destination: the route that once
/// hung the GL worker.
///
/// A planar destination takes `convert_nv_to_planar_two_pass` ->
/// `convert_to` -> `convert_to_dims` -> `draw_src_texture`. That upload
/// once read a PBO source through `src.map_read()`, which is
/// `GlPboOps::map_buffer` on the worker thread that owns the queue, and
/// `blocking_send`-ed to the capacity-1 channel it alone drains. The
/// upload now reads the buffer through `PIXEL_UNPACK_BUFFER` on every
/// route and never maps it.
///
/// `src_pbo_uploads` is asserted so this cannot pass by taking some other
/// route, and `src_uploads` so a regression to the map is caught even
/// when the inline map keeps it from hanging.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO sources: Linux + Windows
fn test_gl_convert_pbo_src_to_planar_no_deadlock() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = GLProcessorThreaded::new(None).unwrap();
let pbo_src = gl
.create_pbo_image(64, 64, PixelFormat::Rgba)
.expect("allocate the PBO source");
let dst = Tensor::<u8>::image(
64,
64,
PixelFormat::PlanarRgb,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("planar destination tensor");
let before = gl.convert_stats().expect("convert stats before");
let src_dyn = TensorDyn::from(pbo_src);
let mut dst_dyn = TensorDyn::from(dst);
let res = gl.convert(&src_dyn, &mut dst_dyn, None);
match res {
Ok(()) => {
let after = gl.convert_stats().expect("convert stats after");
assert_eq!(
after.src_pbo_uploads - before.src_pbo_uploads,
1,
"the planar route did not feed its source from the PBO"
);
assert_eq!(
after.src_uploads, before.src_uploads,
"the planar route mapped its PBO source instead of reading \
it through PIXEL_UNPACK_BUFFER"
);
}
Err(e) => {
let msg = format!("{e:?}");
assert!(
!msg.contains("GL converter thread exited"),
"PBO source to planar convert deadlocked: {msg}"
);
crate::test_support::report_skip(&format!(
"{} - convert failed unrelated: {msg}",
function!()
));
}
}
}
/// The lock every GL-environment guard below holds while its variable is
/// set: the environment is process state and tests run in parallel.
fn lock_gl_env() -> std::sync::MutexGuard<'static, ()> {
static GL_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
GL_ENV.lock().unwrap_or_else(|e| e.into_inner())
}
/// Sets `EDGEFIRST_GL_SERIALIZE` until dropped, holding [`lock_gl_env`]:
/// two tests forcing different policies would otherwise each start their
/// processors under whichever value was written last.
#[cfg(any(target_os = "linux", target_os = "windows"))]
struct SerializeEnvGuard(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);
#[cfg(any(target_os = "linux", target_os = "windows"))]
impl SerializeEnvGuard {
fn set(v: &str) -> Self {
let held = lock_gl_env();
std::env::set_var("EDGEFIRST_GL_SERIALIZE", v);
SerializeEnvGuard(held)
}
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
impl Drop for SerializeEnvGuard {
fn drop(&mut self) {
std::env::remove_var("EDGEFIRST_GL_SERIALIZE");
}
}
/// A PBO source owned by a DIFFERENT processor's context, converted under
/// the `Full` serialization policy.
///
/// This deadlock predates the inline-map fix and is not cured by it: under
/// `Full` the worker holds a process-wide lock for the whole message, so a
/// map sent to the owning worker waits on a reply that worker cannot send
/// until the lock is released. It is refused now instead of hanging.
/// `LifecycleOnly` platforms are unaffected — there is no lock to hold, and
/// the cross-context map still goes through the channel normally.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn test_gl_cross_context_pbo_source_refused_not_deadlocked() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
// Must precede both processors: the policy is read at worker startup.
let _serialize = SerializeEnvGuard::set("full");
let mut gl_a = GLProcessorThreaded::new(None).unwrap();
let gl_b = GLProcessorThreaded::new(None).unwrap();
let pbo_src = gl_b
.create_pbo_image(64, 64, PixelFormat::Rgba)
.expect("allocate the PBO source on the other processor");
let dst = Tensor::<u8>::image(
64,
64,
PixelFormat::PlanarRgb,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("planar destination tensor");
let src_dyn = TensorDyn::from(pbo_src);
let mut dst_dyn = TensorDyn::from(dst);
// The planar destination is what routes the source through
// `draw_src_texture`'s mapping arm; see the PBO-source test above.
let res = gl_a.convert(&src_dyn, &mut dst_dyn, None);
let msg = format!(
"{:?}",
res.expect_err("a cross-context PBO map under Full serialization must be refused")
);
assert!(
msg.contains("another GL context"),
"must be refused by the cross-context guard, not some other error path: {msg}"
);
}
/// A PBO owned by ANOTHER processor's context converts correctly through
/// its owner's map instead of being bound here.
///
/// GL buffer names belong to a context, and HAL's contexts share nothing:
/// binding the other processor's buffer id in this context names a
/// different buffer, or none. Only the processor that allocated a PBO
/// reads it through `PIXEL_UNPACK_BUFFER`; any other maps it, which the
/// owning worker serves when no process-wide lock is held.
#[test]
#[cfg(target_os = "linux")]
fn a_foreign_pbo_source_is_mapped_not_bound() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
// Must precede both processors: the policy is read at worker startup.
let _serialize = SerializeEnvGuard::set("lifecycle");
let mut gl_a = GLProcessorThreaded::new(None).unwrap();
let gl_b = GLProcessorThreaded::new(None).unwrap();
let (w, h) = (320usize, 240usize);
let foreign = rgba8_pbo(&gl_b, w, h);
stamp_rgba8_positionally(&foreign, w, h);
let rgba = || {
TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap()
};
let want = rgba();
stamp_rgba8_positionally(&want, w, h);
let mut got = rgba();
let before = gl_a.convert_stats().expect("convert stats before");
gl_a.convert(&foreign, &mut got, None)
.expect("a foreign PBO source converts through its owner's map");
let after = gl_a.convert_stats().expect("convert stats after");
assert_eq!(
after.src_pbo_uploads, before.src_pbo_uploads,
"another context's buffer id was bound in this context"
);
assert_eq!(after.src_uploads - before.src_uploads, 1);
let (worst, first) = image_max_diff(&got, &want, 1);
assert!(
first.is_none(),
"foreign PBO source differs from its own pixels by up to {worst} at {first:?}"
);
}
/// The destination twin of [`a_foreign_pbo_source_is_mapped_not_bound`]:
/// a PBO destination owned by another processor is written through its
/// owner's map, not read back into this context's buffer of the same
/// name.
#[test]
#[cfg(target_os = "linux")]
fn a_foreign_pbo_destination_is_mapped_not_bound() {
use crate::cpu::CPUProcessor;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let _serialize = SerializeEnvGuard::set("lifecycle");
let mut gl_a = GLProcessorThreaded::new(None).unwrap();
let gl_b = GLProcessorThreaded::new(None).unwrap();
let (w, h) = (320usize, 240usize);
let access = edgefirst_tensor::CpuAccess::ReadWrite;
let cm = edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full);
let mut src = TensorDyn::image(
w,
h,
PixelFormat::Nv12,
DType::U8,
Some(TensorMemory::Mem),
access,
)
.unwrap();
stamp_yuv_gradient(&src, PixelFormat::Nv12, w, h);
src.set_colorimetry(Some(cm));
let mut want = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
access,
)
.unwrap();
CPUProcessor::new().convert(&src, &mut want, None).unwrap();
let mut foreign: TensorDyn = gl_b
.create_pbo_image(w, h, PixelFormat::Rgba)
.expect("allocate a PBO on the other processor")
.into();
gl_a.convert(&src, &mut foreign, None)
.expect("a foreign PBO destination is written through its owner's map");
let (worst, first) = image_max_diff(&foreign, &want, 4);
assert!(
first.is_none(),
"foreign PBO destination differs from the CPU by up to {worst} at {first:?}"
);
}
// ---- Multiplane PixelFormat::Nv12 GPU tests ----
/// Whether `result` is the GL backend's documented decline of a
/// semi-planar source whose chroma is a separate DMA-BUF (Adreno imports
/// only the first buffer of a multi-fd import). Reports the skip, so a
/// test of that import on such a driver is attributed rather than green.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn declined_separate_chroma(result: &crate::Result<()>, test: &str) -> bool {
match result {
Err(crate::Error::NotSupported(m)) if m.contains("separate DMA-BUF") => {
crate::test_support::report_skip(&format!("{test} - {m}"));
true
}
_ => false,
}
}
/// Helper: load PixelFormat::Nv12 raw bytes into separate DMA-backed luma and chroma tensors,
/// returning a multiplane TensorDyn suitable for GPU EGLImage import.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn load_multiplane_nv12_dma(width: usize, height: usize, nv12_bytes: &[u8]) -> TensorDyn {
let y_size = width * height;
let uv_size = width * (height / 2);
assert_eq!(nv12_bytes.len(), y_size + uv_size);
let luma = Tensor::new(&[height, width], Some(TensorMemory::DmaBuf), Some("luma"))
.expect("DMA luma tensor");
luma.map().unwrap().as_mut_slice()[..y_size].copy_from_slice(&nv12_bytes[..y_size]);
let chroma = Tensor::new(
&[height / 2, width],
Some(TensorMemory::DmaBuf),
Some("chroma"),
)
.expect("DMA chroma tensor");
chroma.map().unwrap().as_mut_slice()[..uv_size].copy_from_slice(&nv12_bytes[y_size..]);
Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12)
.map(TensorDyn::from)
.expect("multiplane PixelFormat::Nv12")
}
/// Multiplane PixelFormat::Nv12 → PixelFormat::Rgba via OpenGL DMA-BUF EGLImage (two separate FDs).
/// Compares against contiguous PixelFormat::Nv12 → PixelFormat::Rgba to prove EGL multi-plane import works.
#[test]
#[cfg(target_os = "linux")]
fn test_multiplane_nv12_to_rgba_opengl() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let nv12_bytes: &[u8] = &edgefirst_bench::testdata::read("camera720p.nv12");
// Contiguous PixelFormat::Nv12 (single DMA-BUF)
let src_contiguous = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
nv12_bytes,
)
.unwrap();
// Multiplane PixelFormat::Nv12 (two DMA-BUFs)
let src_multiplane = load_multiplane_nv12_dma(1280, 720, nv12_bytes);
assert!(src_multiplane.as_u8().unwrap().is_multiplane());
// Pin BOTH sources to the SAME conversion path (ExternalSampler) so this
// test isolates multiplane IMPORT correctness from path *selection*.
// Under `auto` the contiguous single-plane source takes ShaderR8 (exact
// in-shader YUV→RGB) while multiplane is forced to ExternalSampler
// (driver YUV, ~6/255 off on Vivante) — a benchmark-driven split
// (ExternalSampler ≈10× faster on Vivante), not an import bug. With both
// on ExternalSampler, two imports of identical bytes must yield identical
// pixels on every GPU, so the compare is byte-exact on all DMA boards.
let _nv_path = NvPathEnvGuard::set("sampler");
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Convert contiguous
let dst_contig = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_contiguous_dyn = src_contiguous;
let mut dst_contig_dyn = dst_contig;
gl.convert(&src_contiguous_dyn, &mut dst_contig_dyn, None)
.unwrap();
// Convert multiplane
let dst_multi = TensorDyn::image(
1280,
720,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_multiplane_dyn = src_multiplane;
let mut dst_multi_dyn = dst_multi;
let result = gl.convert(&src_multiplane_dyn, &mut dst_multi_dyn, None);
if declined_separate_chroma(&result, function!()) {
return;
}
result.unwrap();
// Same bytes, two import paths, one conversion path → byte-identical.
let map_contig = dst_contig_dyn.as_u8().unwrap().map().unwrap();
let map_multi = dst_multi_dyn.as_u8().unwrap().map().unwrap();
assert_pixels_match(map_contig.as_slice(), map_multi.as_slice(), 0);
}
/// Same-fd multiplane NV12: both Y and UV planes live in the same
/// DMA-BUF, imported via `import_image` with two PlaneDescriptors that
/// share the same underlying fd (dup'd). This mirrors V4L2 / GStreamer
/// pipelines where the camera driver exports a single DMA-BUF for both
/// planes with the chroma at an offset.
///
/// Exercises the full eglCreateImage → convert() render path.
/// If this fails on one GPU but passes on others it is a driver
/// limitation; if it fails everywhere the HAL attribute construction
/// is wrong.
#[test]
#[cfg(target_os = "linux")]
fn test_same_fd_multiplane_nv12_to_rgba_opengl() {
use edgefirst_tensor::PlaneDescriptor;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let nv12_bytes: &[u8] = &edgefirst_bench::testdata::read("camera720p.nv12");
let width: usize = 1280;
let height: usize = 720;
let stride: usize = width; // NV12 Y plane: 1 byte per pixel
let y_size = stride * height;
let uv_size = stride * (height / 2);
let total_bytes = y_size + uv_size;
assert_eq!(nv12_bytes.len(), total_bytes);
// Single DMA-BUF holding both planes contiguously
let Some(buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(
&[total_bytes],
Some(TensorMemory::DmaBuf),
Some("same_fd_nv12"),
),
"same-fd NV12 DMA buffer",
) else {
return;
};
// Fill with real NV12 camera data
buf.map().unwrap().as_mut_slice()[..total_bytes].copy_from_slice(nv12_bytes);
// Import as multiplane: two PlaneDescriptors, same fd, different offsets
let fd = buf.dmabuf().unwrap();
let luma_pd = PlaneDescriptor::new(fd)
.unwrap()
.with_stride(stride)
.with_offset(0);
let chroma_pd = PlaneDescriptor::new(fd)
.unwrap()
.with_stride(stride)
.with_offset(y_size);
// Force both the same-fd multiplane and contiguous sources onto the
// ExternalSampler path so the comparison tests import correctness, not
// path selection (see test_multiplane_nv12_to_rgba_opengl for the
// benchmark-driven rationale). Byte-exact on every DMA board.
let _nv_path = NvPathEnvGuard::set("sampler");
let proc = crate::ImageProcessor::new().unwrap();
let src = proc
.import_image(
luma_pd,
Some(chroma_pd),
width,
height,
PixelFormat::Nv12,
DType::U8,
None,
)
.unwrap();
assert!(src.is_multiplane(), "must be multiplane after import");
// Also build contiguous reference for comparison
let src_contig = load_raw_image(
width,
height,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
nv12_bytes,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Render same-fd multiplane through full EGL pipeline
let mut dst_same_fd = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut dst_same_fd, None).unwrap();
// Render contiguous reference
let mut dst_contig = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src_contig, &mut dst_contig, None).unwrap();
// Same-fd multiplane and contiguous must produce identical pixels.
let map_same = dst_same_fd.as_u8().unwrap().map().unwrap();
let map_contig = dst_contig.as_u8().unwrap().map().unwrap();
assert_pixels_match(map_same.as_slice(), map_contig.as_slice(), 0);
}
/// Multiplane PixelFormat::Nv12 720p → packed PixelFormat::Rgb 640x640 with letterbox resize via GL.
/// Validates the packing shader works with multiplane EGLImage source.
#[test]
#[cfg(target_os = "linux")]
fn test_multiplane_nv12_to_rgb_letterbox_opengl() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
// Pin both sources to ExternalSampler so the packed-RGB letterbox compare
// tests multiplane import correctness, not path selection (see
// test_multiplane_nv12_to_rgba_opengl). Byte-exact on every DMA board.
let _nv_path = NvPathEnvGuard::set("sampler");
let nv12_bytes: &[u8] = &edgefirst_bench::testdata::read("camera720p.nv12");
let src_contiguous = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
nv12_bytes,
)
.unwrap();
let src_multiplane = load_multiplane_nv12_dma(1280, 720, nv12_bytes);
let crop = letterbox_crop(1280, 720, 640, 640);
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Contiguous → packed PixelFormat::Rgb with letterbox
let dst_contig = TensorDyn::image(
640,
640,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_contiguous_dyn = src_contiguous;
let mut dst_contig_dyn = dst_contig;
gl.convert(
&src_contiguous_dyn,
&mut dst_contig_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
// Multiplane → packed PixelFormat::Rgb with letterbox
let dst_multi = TensorDyn::image(
640,
640,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_multiplane_dyn = src_multiplane;
let mut dst_multi_dyn = dst_multi;
let result = gl.convert(
&src_multiplane_dyn,
&mut dst_multi_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
);
if declined_separate_chroma(&result, function!()) {
return;
}
result.unwrap();
let map_contig = dst_contig_dyn.as_u8().unwrap().map().unwrap();
let map_multi = dst_multi_dyn.as_u8().unwrap().map().unwrap();
assert_pixels_match(map_contig.as_slice(), map_multi.as_slice(), 0);
}
/// Multiplane PixelFormat::Nv12 720p → packed PixelFormat::Rgb 640x640 with letterbox resize via GL.
/// Validates the int8 packing shader (XOR 0x80) works with multiplane source.
#[test]
#[cfg(target_os = "linux")]
fn test_multiplane_nv12_to_rgb_int8_letterbox_opengl() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
// Pin both sources to ExternalSampler. Critical for int8: the XOR-0x80
// packing amplifies any path-selection color delta straddling 0x80 into a
// ~250-unit byte diff (e.g. 126↔132 → 254↔2), so the two sources MUST
// share one conversion path. This tests multiplane import correctness;
// see test_multiplane_nv12_to_rgba_opengl for the benchmark rationale.
let _nv_path = NvPathEnvGuard::set("sampler");
let nv12_bytes: &[u8] = &edgefirst_bench::testdata::read("camera720p.nv12");
let src_contiguous = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
nv12_bytes,
)
.unwrap();
let src_multiplane = load_multiplane_nv12_dma(1280, 720, nv12_bytes);
let crop = letterbox_crop(1280, 720, 640, 640);
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Contiguous → packed PixelFormat::Rgb int8 with letterbox
let dst_contig = TensorDyn::image(
640,
640,
PixelFormat::Rgb,
DType::I8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_contiguous_dyn = src_contiguous;
let mut dst_contig_dyn = dst_contig;
gl.convert(
&src_contiguous_dyn,
&mut dst_contig_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
// Multiplane → packed PixelFormat::Rgb int8 with letterbox
let dst_multi = TensorDyn::image(
640,
640,
PixelFormat::Rgb,
DType::I8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_multiplane_dyn = src_multiplane;
let mut dst_multi_dyn = dst_multi;
let result = gl.convert(
&src_multiplane_dyn,
&mut dst_multi_dyn,
Some(crate::ConvertOptions::new().crop(crop)),
);
if declined_separate_chroma(&result, function!()) {
return;
}
result.unwrap();
// Map raw i8 bytes as u8 for comparison — both have XOR 0x80 bias.
let map_contig = dst_contig_dyn.as_i8().unwrap().map().unwrap();
let contig_bytes: &[u8] = unsafe {
std::slice::from_raw_parts(map_contig.as_slice().as_ptr().cast(), map_contig.len())
};
let map_multi = dst_multi_dyn.as_i8().unwrap().map().unwrap();
let multi_bytes: &[u8] = unsafe {
std::slice::from_raw_parts(map_multi.as_slice().as_ptr().cast(), map_multi.len())
};
assert_pixels_match(contig_bytes, multi_bytes, 0);
}
/// Regression for the two-pass double letterbox (PR #107): pass 2 of the
/// zero-copy NV→planar plan re-applied `dst_rect`, mapping the
/// already-letterboxed intermediate into the content sub-region a second
/// time and shrinking the image by the letterbox content fraction twice.
///
/// A synthetic grey NV12 frame letterboxed 1280x720 → 640x640 must place
/// content rows at exactly [140, 500); the double-applied bug squeezed
/// them to ~[218, 422). Probing rows just inside the correct band (150 /
/// 490) is therefore a deterministic kill-shot with no oracle tolerance
/// to hide behind — and it equally catches the inverse bug (letterbox
/// dropped entirely: pad rows would hold content). Covers PlanarRgb /
/// PlanarRgba × u8 / i8 × Dma (the GL TwoPassNvPlanar plan) and Mem
/// destinations, guarding the whole dispatch surface against the bug
/// class. (The platform gate matches the helpers it uses; the Mem legs
/// run on the llvmpipe coverage lane.)
///
/// **Each leg asserts its own route** (issue #179).
/// `ComputeBackend::OpenGl` leaves `forced_backend` at `None`, so a GL
/// decline logs at debug and the CPU serves the same convert — and the
/// CPU places the content band correctly, so a silent decline reads as
/// a pass here. `dst_format_renderable` accepts both planar formats
/// on the zero-copy DMA arm and the texture arm, so every leg must stay
/// on GL and `convert_fallback_count()` must not move across it.
#[test]
#[cfg(target_os = "linux")]
fn letterbox_nv_to_planar_content_band_geometry() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
// Without this the route assertions below go vacuous: with no GL
// backend at all nothing ever declines, so every leg would pass
// having run on the CPU.
if proc.opengl.is_none() {
crate::test_support::report_skip(&format!(
"{} - ImageProcessor resolved no GL backend",
function!()
));
return;
}
// Synthetic NV12: Y=200, U=V=128 is neutral grey, so BT.601 vs BT.709
// coefficients cancel and the converted RGB is ~200 (full range) to
// ~214 (limited): comfortably above the 114 pad in every colorimetry
// mode. Threshold at >=170 content / <=140 pad.
let (sw, sh) = (1280usize, 720usize);
let mut nv12 = vec![0u8; sw * sh * 3 / 2];
nv12[..sw * sh].fill(200);
nv12[sw * sh..].fill(128);
let src_mem = if is_dma_available() {
Some(TensorMemory::DmaBuf)
} else {
Some(TensorMemory::Mem)
};
let src = load_raw_image(sw, sh, PixelFormat::Nv12, src_mem, &nv12).unwrap();
// 1280x720 → 640x640: scale 0.5, content 640x360 centred → rows
// [140, 500). Probe ≥10 px from the boundary to stay clear of
// bilinear edge blending.
const CONTENT_ROWS: [usize; 3] = [150, 320, 490];
const PAD_ROWS: [usize; 4] = [0, 130, 510, 639];
let (dw, dh) = (640usize, 640usize);
let lb = Crop::letterbox([114, 114, 114, 255]);
let mut dst_memories = vec![TensorMemory::Mem];
if is_dma_available() {
dst_memories.push(TensorMemory::DmaBuf);
}
for dst_mem in dst_memories {
for dst_fmt in [PixelFormat::PlanarRgb, PixelFormat::PlanarRgba] {
for dtype in [DType::U8, DType::I8] {
let label = format!("nv12->{dst_fmt}.{dtype:?}@{dst_mem:?}");
let mut dst = proc
.create_image(
dw,
dh,
dst_fmt,
dtype,
Some(dst_mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&src, &mut dst, Some(crate::ConvertOptions::new().crop(lb)))
.unwrap_or_else(|e| panic!("{label}: convert failed: {e}"));
let declines = proc.convert_fallback_count() - fallbacks_before;
assert_eq!(
declines, 0,
"{label}: the GL backend declined this convert and the \
CPU served it — the band probes below would pass on the \
CPU answer, so this leg proved nothing about the GL \
two-pass plan"
);
let raw: Vec<u8> = match dtype {
DType::U8 => dst.as_u8().unwrap().map().unwrap().as_slice().to_vec(),
_ => dst
.as_i8()
.unwrap()
.map()
.unwrap()
.as_slice()
.iter()
.map(|&v| v as u8)
.collect(),
};
// The alpha plane is 255 everywhere (content and pad) and
// stays the raw byte for i8 too.
if dst_fmt == PixelFormat::PlanarRgba {
let alpha = &raw[3 * dh * dw..4 * dh * dw];
if let Some(i) = alpha.iter().position(|&a| a != 255) {
panic!("{label}: alpha plane byte {i} = {}, expected 255", alpha[i]);
}
}
// Undo the int8 XOR-0x80 bias so both dtypes share one set
// of thresholds.
let unbias = if dtype == DType::I8 { 0x80u8 } else { 0 };
let bytes: Vec<u8> = raw.iter().map(|&v| v ^ unbias).collect();
for plane in 0..3 {
let plane_base = plane * dh * dw;
for row in CONTENT_ROWS {
for col in (5..dw - 5).step_by(13) {
let v = bytes[plane_base + row * dw + col];
assert!(
v >= 170,
"{label}: plane {plane} row {row} col {col} = {v}, \
expected content (>=170) — letterbox content band \
misplaced (double-letterbox regression?)"
);
}
}
for row in PAD_ROWS {
for col in (5..dw - 5).step_by(13) {
let v = bytes[plane_base + row * dw + col];
assert!(
v <= 140,
"{label}: plane {plane} row {row} col {col} = {v}, \
expected pad (<=140) — content leaked into the \
letterbox band"
);
}
}
}
}
}
}
}
/// Letterboxed PixelFormat::Nv12 → planar against the verified RGBA
/// reference: the same processor letterboxes camera NV12 720p → RGBA
/// 640x640, the reference is channel-split on the CPU, and the GL planar
/// output (PlanarRgb/PlanarRgba@Dma — the TwoPassNvPlanar plan) must
/// match it. Catches placement, scale, and content
/// drift in the two-pass plan at full resolution — the per-pixel
/// complement to the content-band geometry probe above.
#[test]
#[cfg(target_os = "linux")]
fn letterbox_nv12_to_planar_matches_rgba_reference() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let crop = letterbox_crop(1280, 720, 640, 640);
let (dw, dh) = (640usize, 640usize);
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Reference: the verified packed-RGBA letterbox path.
let mut dst_rgba = TensorDyn::image(
dw,
dh,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(
&src,
&mut dst_rgba,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let rgba = dst_rgba.as_u8().unwrap().map().unwrap();
let rgba = rgba.as_slice();
for fmt in [PixelFormat::PlanarRgb, PixelFormat::PlanarRgba] {
// Channel-split the RGBA reference into the planar layout.
let planes = fmt.channels();
let mut expected = vec![0u8; planes * dh * dw];
for (i, px) in rgba.as_chunks::<4>().0.iter().enumerate() {
for (plane, &channel) in px.iter().take(planes).enumerate() {
expected[plane * dh * dw + i] = channel;
}
}
let mut dst = TensorDyn::image(
dw,
dh,
fmt,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap_or_else(|e| panic!("nv12->{fmt}@Dma: convert failed: {e}"));
let map = dst.as_u8().unwrap().map().unwrap();
assert_pixels_match(&expected, map.as_slice(), 1);
}
}
/// Build a heap-memory (`TensorMemory::Mem`) NV12 image from a raw fixture.
/// Portable (no platform gate): distinct from `load_raw_image`, which is
/// gated to the desktop platforms the `@Dma` tiers allocate on.
fn mem_nv12_image(width: usize, height: usize, bytes: &[u8]) -> TensorDyn {
let img = TensorDyn::image(
width,
height,
PixelFormat::Nv12,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut map = img.as_u8().unwrap().map().unwrap();
map.as_mut_slice()[..bytes.len()].copy_from_slice(bytes);
drop(map);
img
}
/// GL destination lowering for a `TensorMemory::Mem` PlanarRgb tensor is
/// `DstLowering::TextureMem` — never a two-pass zero-copy plan — so this
/// exercises the SinglePass `convert_to_planar` render + the new heap
/// readback branch directly (Task 5, Component (a)). Before this task
/// `dst_format_renderable`'s non-DMA arm rejected `PlanarRgb`
/// outright and the whole convert fell back to CPU; the motivating
/// profile showed 2485/2485 planar converts missing GL for exactly this
/// reason on hosts without DMA destinations.
#[test]
fn gl_planar_heap_matches_cpu() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (sw, sh) = (1280usize, 720usize);
let src = mem_nv12_image(sw, sh, &edgefirst_bench::testdata::read("camera720p.nv12"));
let crop = Crop::letterbox([114, 114, 114, 255]);
let (dw, dh) = (640usize, 640usize);
let mut gl = match GLProcessorThreaded::new(None) {
Ok(gl) => gl,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
for fmt in [PixelFormat::PlanarRgb, PixelFormat::PlanarRgba] {
let mut gl_dst = TensorDyn::image(
dw,
dh,
fmt,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(
&src,
&mut gl_dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap_or_else(|e| panic!("nv12->{fmt}@Mem: GL convert failed: {e}"));
// CPU reference — the Task 3/4 fused NV->planar + halo-resize path.
let mut cpu_dst = TensorDyn::image(
dw,
dh,
fmt,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(
&src,
&mut cpu_dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
// GL is not bit-exact vs CPU (bilinear rounding, matrix precision) —
// reuse the 0.95 structural-similarity threshold the existing
// GL-vs-CPU planar oracle (`test_nv12_to_planar_rgb_uses_shader_path`)
// and the mask-render suite (`test_segmentation_yolo`) both use.
compare_images(&gl_dst, &cpu_dst, 0.95, function!());
}
}
/// Steady-state companion to [`gl_planar_heap_matches_cpu`]: once the gate
/// relaxation lands, the SAME convert must stay on GL every iteration
/// through the public `ImageProcessor` auto fallback chain — no silent
/// drop to CPU. `convert_fallback_count()` only increments when the GL
/// leg of the chain declines (see `ImageProcessor::convert_fallback_count`
/// doc), so a flat delta across repeats is the steady-state proof.
#[test]
fn gl_planar_heap_does_not_fall_back() {
use crate::ImageProcessor;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut proc = ImageProcessor::new().unwrap();
if proc.opengl.is_none() {
crate::test_support::report_skip(&format!(
"{} - ImageProcessor resolved no GL backend",
function!()
));
return;
}
let (sw, sh) = (1280usize, 720usize);
let src = mem_nv12_image(sw, sh, &edgefirst_bench::testdata::read("camera720p.nv12"));
let crop = Crop::letterbox([114, 114, 114, 255]);
let (dw, dh) = (640usize, 640usize);
let mut dst = proc
.create_image(
dw,
dh,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let before = proc.convert_fallback_count();
for i in 0..10 {
proc.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap_or_else(|e| panic!("nv12->PlanarRgb@Mem: convert failed on iter {i}: {e}"));
}
let after = proc.convert_fallback_count();
assert_eq!(
after - before,
0,
"GL planar heap convert fell back {} time(s) over 10 iterations \
(before={before}, after={after})",
after - before
);
}
/// Non-NV companion to [`gl_planar_heap_matches_cpu`]: a packed Rgba
/// source into a heap PlanarRgb destination. Before the `plan_convert`
/// generalization (Task 5 fix round 1) this combination hit the
/// single-pass planar shader, which is unavailable on ANGLE/Android
/// (`Platform::EXTERNAL_OES == false` — see `ConvertPlan::TwoPassNvPlanar`'s
/// doc) and DMA-source-only on Linux — a heap Rgba source could reach
/// neither. Now routed through the same two-pass plan as the NV pair.
#[test]
fn gl_planar_heap_rgba_src_matches_cpu() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let src = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
Some(TensorMemory::Mem),
)
.unwrap();
let crop = Crop::letterbox([114, 114, 114, 255]);
let (dw, dh) = (640usize, 640usize);
let mut gl = match GLProcessorThreaded::new(None) {
Ok(gl) => gl,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
let mut gl_dst = TensorDyn::image(
dw,
dh,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(
&src,
&mut gl_dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap_or_else(|e| panic!("rgba->PlanarRgb@Mem: GL convert failed: {e}"));
let mut cpu_dst = TensorDyn::image(
dw,
dh,
PixelFormat::PlanarRgb,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(
&src,
&mut cpu_dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
compare_images(&gl_dst, &cpu_dst, 0.95, function!());
}
/// Steady-state companion to [`gl_planar_heap_rgba_src_matches_cpu`],
/// mirroring [`gl_planar_heap_does_not_fall_back`] for the non-NV source.
#[test]
fn gl_planar_heap_rgba_src_does_not_fall_back() {
use crate::ImageProcessor;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut proc = ImageProcessor::new().unwrap();
if proc.opengl.is_none() {
crate::test_support::report_skip(&format!(
"{} - ImageProcessor resolved no GL backend",
function!()
));
return;
}
let src = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
Some(TensorMemory::Mem),
)
.unwrap();
let crop = Crop::letterbox([114, 114, 114, 255]);
let (dw, dh) = (640usize, 640usize);
let mut dst = proc
.create_image(
dw,
dh,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let before = proc.convert_fallback_count();
for i in 0..10 {
proc.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap_or_else(|e| panic!("rgba->PlanarRgb@Mem: convert failed on iter {i}: {e}"));
}
let after = proc.convert_fallback_count();
assert_eq!(
after - before,
0,
"GL planar heap (Rgba src) convert fell back {} time(s) over 10 iterations \
(before={before}, after={after})",
after - before
);
}
/// Compare fused GL proto rendering against hybrid (CPU materialize + GL overlay).
///
/// Both paths should produce visually similar output. Differences arise from
/// bilinear interpolation (GPU vs CPU) and mask threshold rounding.
#[test]
fn test_proto_fused_vs_hybrid_ssim() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (output_boxes, proto_data) = decode_yolov8_proto_fixture();
// Materialize masks on CPU for the hybrid path
let cpu_proc = crate::CPUProcessor::new();
let segmentation = cpu_proc
.materialize_segmentations(&output_boxes, &proto_data, None)
.unwrap();
// Create two identical RGBA canvases
let mut gl = GLProcessorThreaded::new(None).unwrap();
let mut dst_hybrid = TensorDyn::from(
edgefirst_tensor::Tensor::<u8>::image(
640,
640,
PixelFormat::Rgba,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap(),
);
let mut dst_fused = TensorDyn::from(
edgefirst_tensor::Tensor::<u8>::image(
640,
640,
PixelFormat::Rgba,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap(),
);
// Render via hybrid path (pre-decoded masks)
gl.draw_decoded_masks(
&mut dst_hybrid,
&output_boxes,
&segmentation,
Default::default(),
)
.unwrap();
// Render via fused GL proto path
gl.draw_proto_masks(
&mut dst_fused,
&output_boxes,
&proto_data,
Default::default(),
)
.unwrap();
// Compare — threshold 0.90 to allow bilinear interpolation differences
// between GPU proto rendering and CPU materialization
compare_images(&dst_hybrid, &dst_fused, 0.90, function!());
}
/// Decode the cached YOLOv8-seg fixture outputs (int8 boxes + protos)
/// into post-NMS detections and the int8 `ProtoData`. Shared scaffolding
/// for every proto-rendering test.
fn decode_yolov8_proto_fixture() -> (Vec<DetectBox>, ProtoData) {
use edgefirst_decoder::{configs, ConfigOutput, DecoderBuilder, Nms};
let boxes_raw: &[u8] = &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 =
edgefirst_tensor::Tensor::<i8>::from_slice(boxes_i8, &[1, 116, 8400])
.expect("boxes tensor")
.into();
let protos_raw: &[u8] = &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 =
edgefirst_tensor::Tensor::<i8>::from_slice(protos_i8, &[1, 160, 160, 32])
.expect("protos tensor")
.into();
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 test decoder must build");
let inputs: Vec<&TensorDyn> = vec![&boxes_tensor, &protos_tensor];
let mut output_boxes = Vec::with_capacity(50);
let proto_data = decoder
.decode_proto(&inputs, &mut output_boxes)
.expect("decode_proto must succeed")
.expect("yolov8-seg config produces ProtoData");
assert!(!output_boxes.is_empty(), "No detections from model");
(output_boxes, proto_data)
}
/// Build F32 and F16 `ProtoData` by dequantizing the int8 fixture — the
/// same synthesis the mask bench uses for its float dtype cells.
fn proto_fixture_as_float(proto_i8: &ProtoData, n_det: usize) -> (ProtoData, ProtoData) {
use half::f16;
let (protos_f32, proto_shape) = match proto_i8.protos.dtype() {
DType::I8 => {
let t = proto_i8.protos.as_typed::<i8>().expect("dtype checked");
let shape = t.shape().to_vec();
let q = t.quantization().expect("i8 protos must carry quant");
let scale = q.scale()[0];
let zp = q.zero_point().map(|z| z[0]).unwrap_or(0) as f32;
let m = t.map().unwrap();
let v: Vec<f32> = m
.as_slice()
.iter()
.map(|v| (*v as f32 - zp) * scale)
.collect();
(v, shape)
}
other => panic!("expected i8 protos in fixture, got {other:?}"),
};
let num_protos = *proto_shape.last().unwrap();
let coeffs_f32: Vec<f32> = match proto_i8.mask_coefficients.dtype() {
DType::F32 => proto_i8
.mask_coefficients
.as_typed::<f32>()
.expect("dtype checked")
.map()
.unwrap()
.as_slice()
.to_vec(),
DType::F16 => proto_i8
.mask_coefficients
.as_typed::<f16>()
.expect("dtype checked")
.map()
.unwrap()
.as_slice()
.iter()
.map(|v: &f16| v.to_f32())
.collect(),
DType::I8 => {
let t = proto_i8
.mask_coefficients
.as_typed::<i8>()
.expect("dtype checked");
let q = t
.quantization()
.expect("i8 mask coefficients must carry quant");
let scale = q.scale()[0];
let zp = q.zero_point().map(|z| z[0]).unwrap_or(0) as f32;
let m = t.map().unwrap();
m.as_slice()
.iter()
.map(|v| (*v as f32 - zp) * scale)
.collect()
}
other => panic!("unexpected coefficient dtype {other:?}"),
};
let coeff_shape = [n_det, num_protos];
let proto_f32 = ProtoData {
mask_coefficients: Tensor::<f32>::from_slice(&coeffs_f32, &coeff_shape)
.unwrap()
.into(),
protos: Tensor::<f32>::from_slice(&protos_f32, &proto_shape)
.unwrap()
.into(),
layout: ProtoLayout::Nhwc,
};
let protos_f16: Vec<f16> = protos_f32.iter().map(|v| f16::from_f32(*v)).collect();
let coeffs_f16: Vec<f16> = coeffs_f32.iter().map(|v| f16::from_f32(*v)).collect();
let proto_f16 = ProtoData {
mask_coefficients: Tensor::<f16>::from_slice(&coeffs_f16, &coeff_shape)
.unwrap()
.into(),
protos: Tensor::<f16>::from_slice(&protos_f16, &proto_shape)
.unwrap()
.into(),
layout: ProtoLayout::Nhwc,
};
(proto_f32, proto_f16)
}
/// Keep only the first `keep` proto layers (and matching coefficients)
/// of an F32 `ProtoData` — HWC layout, so channels are sliced per pixel.
fn slice_proto_layers_f32(pd: &ProtoData, keep: usize, n_det: usize) -> ProtoData {
let (protos, shape) = match pd.protos.dtype() {
DType::F32 => {
let t = pd.protos.as_typed::<f32>().expect("dtype checked");
(t.map().unwrap().as_slice().to_vec(), t.shape().to_vec())
}
other => panic!("expected f32 protos, got {other:?}"),
};
let (h, w, c) = (shape[0], shape[1], shape[2]);
assert!(keep <= c);
let mut sliced = Vec::with_capacity(h * w * keep);
for px in protos.chunks_exact(c) {
sliced.extend_from_slice(&px[..keep]);
}
let coeffs = match pd.mask_coefficients.dtype() {
DType::F32 => pd
.mask_coefficients
.as_typed::<f32>()
.expect("dtype checked")
.map()
.unwrap()
.as_slice()
.to_vec(),
other => panic!("expected f32 coefficients, got {other:?}"),
};
let mut sliced_coeffs = Vec::with_capacity(n_det * keep);
for det in coeffs.chunks_exact(c) {
sliced_coeffs.extend_from_slice(&det[..keep]);
}
ProtoData {
mask_coefficients: Tensor::<f32>::from_slice(&sliced_coeffs, &[n_det, keep])
.unwrap()
.into(),
protos: Tensor::<f32>::from_slice(&sliced, &[h, w, keep])
.unwrap()
.into(),
layout: ProtoLayout::Nhwc,
}
}
/// Render the fused GL proto path into a fresh 640x640 RGBA canvas.
fn render_proto_to_rgba(
gl: &mut GLProcessorThreaded,
boxes: &[DetectBox],
pd: &ProtoData,
) -> TensorDyn {
let mut dst = TensorDyn::from(
edgefirst_tensor::Tensor::<u8>::image(
640,
640,
PixelFormat::Rgba,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap(),
);
gl.draw_proto_masks(&mut dst, boxes, pd, Default::default())
.unwrap();
dst
}
/// Forces `has_float_linear` off for processors created in scope —
/// makes the f32→f16-repack proto fallback reachable on float-linear
/// GPUs (no CI lane has a GPU without the extension).
struct FloatLinearEnvGuard(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);
impl FloatLinearEnvGuard {
fn set() -> Self {
let held = lock_gl_env();
std::env::set_var("EDGEFIRST_GL_NO_FLOAT_LINEAR", "1");
FloatLinearEnvGuard(held)
}
}
impl Drop for FloatLinearEnvGuard {
fn drop(&mut self) {
std::env::remove_var("EDGEFIRST_GL_NO_FLOAT_LINEAR");
}
}
/// Opts processors created in scope into the GLES 3.1 compute-shader
/// proto repack (otherwise env-gated off — it has zero coverage without
/// this).
struct ProtoComputeEnvGuard(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);
impl ProtoComputeEnvGuard {
fn set() -> Self {
let held = lock_gl_env();
std::env::set_var("EDGEFIRST_PROTO_COMPUTE", "1");
ProtoComputeEnvGuard(held)
}
}
impl Drop for ProtoComputeEnvGuard {
fn drop(&mut self) {
std::env::remove_var("EDGEFIRST_PROTO_COMPUTE");
}
}
/// The float proto-render paths must agree with the int8 fused reference:
/// F32 (R32F, hardware bilinear where float-linear exists) and F16-native
/// (RGBA16F packed) render the SAME dequantized data, so int8-vs-f32 may
/// differ only by quantization + interpolation (default int8 mode is
/// shader bilinear ≈ hardware bilinear), and f32-vs-f16 only by f16
/// rounding. Before this test the three float variants had no direct
/// coverage at all.
#[test]
fn proto_float_dtypes_match_int8_reference() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (boxes, proto_i8) = decode_yolov8_proto_fixture();
let (proto_f32, proto_f16) = proto_fixture_as_float(&proto_i8, boxes.len());
let mut gl = GLProcessorThreaded::new(None).unwrap();
let dst_i8 = render_proto_to_rgba(&mut gl, &boxes, &proto_i8);
let dst_f32 = render_proto_to_rgba(&mut gl, &boxes, &proto_f32);
let dst_f16 = render_proto_to_rgba(&mut gl, &boxes, &proto_f16);
compare_images(&dst_i8, &dst_f32, 0.90, function!());
compare_images(&dst_f32, &dst_f16, 0.98, function!());
}
/// The `!has_float_linear` f32 arm repacks F32 protos into RGBA16F and
/// renders through the f16 shader — a capability fallback no CI lane's
/// GPU exercises naturally. Force the capability off and pin the
/// fallback's output against the native R32F render: same data, only
/// RGBA16F precision and packing differ.
#[test]
fn proto_f32_no_float_linear_fallback_matches() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (boxes, proto_i8) = decode_yolov8_proto_fixture();
let (proto_f32, _) = proto_fixture_as_float(&proto_i8, boxes.len());
let dst_native = {
let mut gl = GLProcessorThreaded::new(None).unwrap();
render_proto_to_rgba(&mut gl, &boxes, &proto_f32)
};
let dst_fallback = {
let _guard = FloatLinearEnvGuard::set();
let mut gl = GLProcessorThreaded::new(None).unwrap();
render_proto_to_rgba(&mut gl, &boxes, &proto_f32)
};
compare_images(&dst_native, &dst_fallback, 0.98, function!());
}
/// The GLES 3.1 compute-shader HWC→CHW proto repack must produce the
/// same masks as the CPU repack — only the transposition strategy
/// differs, not the data or sampling. The compute path is env-gated
/// (EDGEFIRST_PROTO_COMPUTE=1); where the GPU lacks GLES 3.1 compute the
/// guard is a no-op and both renders take the CPU repack (still a valid,
/// if vacuous, comparison).
#[test]
fn proto_compute_repack_matches_cpu_repack() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (boxes, proto_i8) = decode_yolov8_proto_fixture();
let dst_cpu_repack = {
let mut gl = GLProcessorThreaded::new(None).unwrap();
render_proto_to_rgba(&mut gl, &boxes, &proto_i8)
};
let dst_compute = {
let _guard = ProtoComputeEnvGuard::set();
let mut gl = GLProcessorThreaded::new(None).unwrap();
render_proto_to_rgba(&mut gl, &boxes, &proto_i8)
};
compare_images(&dst_cpu_repack, &dst_compute, 0.99, function!());
}
/// All three int8 proto interpolation modes must agree on the rendered
/// masks: Bilinear (shader-computed weights) and TwoPass (dequant to
/// RGBA16F + hardware GL_LINEAR) sample the same data with equivalent
/// filtering, and Nearest only loses the sub-texel blend. TwoPass had
/// no test on any lane before this — it is the path with the cached
/// dequant FBO, the gated immutable dequant texture, and the shared
/// fullscreen quad. Switching modes on ONE processor also exercises
/// per-draw plan changes against the persistent proto/dequant textures.
#[test]
fn proto_int8_interpolation_modes_agree() {
use crate::Int8InterpolationMode;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (boxes, proto_i8) = decode_yolov8_proto_fixture();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let mut render_mode = |mode: Int8InterpolationMode| {
gl.set_int8_interpolation_mode(mode).unwrap();
render_proto_to_rgba(&mut gl, &boxes, &proto_i8)
};
let bilinear = render_mode(Int8InterpolationMode::Bilinear);
let two_pass = render_mode(Int8InterpolationMode::TwoPass);
let nearest = render_mode(Int8InterpolationMode::Nearest);
// And back to bilinear on the same processor: must reproduce the
// first render despite the dequant texture/FBO created in between.
let bilinear_again = render_mode(Int8InterpolationMode::Bilinear);
// Measured actuals, all bit-identical across three isolated runs
// per board: Vivante GC7000UL 0.9957, Mali G310 0.9982, V3D 7.1
// 0.9962 against TwoPass; 0.9602 / 0.9599 / 0.9601 against Nearest.
//
// The Mali figure used to read 0.8153 and was attributed to that
// driver's coarser fixed-point f16 texture interpolation. It was
// not a driver difference at all — it was issue #184, the overlay's
// `GL_BLEND` leaking into the two-pass dequantization render, which
// made every TwoPass mask partly a function of uninitialised GPU
// memory. With blending off for that pass the three GPUs agree to
// better than 0.995.
//
// The thresholds stay loose deliberately. What these modes owe each
// other is equivalent filtering, not bit-exactness, and no lane
// measures Tegra or the ANGLE backends, so the margin is headroom
// for a GPU none of the three boards represents. They still catch
// structural breakage by a wide margin: the broken compute-repack
// upload scored ~0.77, and #184's blended dequant scored 0.74–0.75.
compare_images(&bilinear, &two_pass, 0.80, function!());
compare_images(&bilinear, &nearest, 0.90, function!());
let a = bilinear.as_u8().unwrap().map().unwrap();
let b = bilinear_again.as_u8().unwrap().map().unwrap();
assert_eq!(
a.as_slice(),
b.as_slice(),
"bilinear render diverged after mode churn"
);
}
/// Proto texture uploads must stay correct across dims/format churn on
/// ONE processor: int8 (R8I) → f32 (R32F, same dims — internal-format
/// churn) → f32 with 30 layers (layer-count churn, deliberately not a
/// multiple of 4) → int8 again. Each render must byte-match a fresh
/// processor rendering the same input once. This is the regression test
/// for the proto dims gate: a gate keyed on dims-without-ifmt, or a
/// SubImage3D into a stale allocation, breaks one of these legs.
#[test]
fn proto_dims_and_format_churn_uploads_correctly() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (boxes, proto_i8) = decode_yolov8_proto_fixture();
let (proto_f32, _) = proto_fixture_as_float(&proto_i8, boxes.len());
let proto_f32_30 = slice_proto_layers_f32(&proto_f32, 30, boxes.len());
let oracle = |pd: &ProtoData| {
let mut gl = GLProcessorThreaded::new(None).unwrap();
render_proto_to_rgba(&mut gl, &boxes, pd)
};
let oracle_i8 = oracle(&proto_i8);
let oracle_f32 = oracle(&proto_f32);
let oracle_f32_30 = oracle(&proto_f32_30);
let mut gl = GLProcessorThreaded::new(None).unwrap();
for (step, (pd, expected)) in [
(&proto_i8, &oracle_i8),
(&proto_f32, &oracle_f32),
(&proto_f32_30, &oracle_f32_30),
(&proto_i8, &oracle_i8),
]
.into_iter()
.enumerate()
{
let out = render_proto_to_rgba(&mut gl, &boxes, pd);
let a = expected.as_u8().unwrap().map().unwrap();
let b = out.as_u8().unwrap().map().unwrap();
let (a, b) = (a.as_slice(), b.as_slice());
let diffs = a.iter().zip(b).filter(|(x, y)| x != y).count();
let max_diff = a
.iter()
.zip(b)
.map(|(x, y)| x.abs_diff(*y))
.max()
.unwrap_or(0);
assert!(
diffs == 0,
"churn step {step}: {diffs}/{} bytes diverged from the \
fresh-processor oracle (max |diff| {max_diff})",
a.len()
);
}
}
// =========================================================================
// Destination DMA-BUF plane_offset tests
//
// These verify that create_egl_image_with_dims correctly passes
// plane_offset to EGL, so the GPU renders at the right position within
// a shared DMA-BUF (critical for NPU buffers where a single allocation
// serves the entire accelerator).
// =========================================================================
/// Regression: destination with explicit offset=0 must produce the same
/// output as a destination with no offset set.
#[test]
#[cfg(target_os = "linux")]
fn test_opengl_dst_offset_zero_regression() {
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Destination without offset
let dst_no_off = TensorDyn::image(
640,
480,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_dyn = src;
let mut dst_no_off_dyn = dst_no_off;
gl.convert(&src_dyn, &mut dst_no_off_dyn, None).unwrap();
// Destination with explicit offset=0
let mut dst_zero = Tensor::<u8>::image(
640,
480,
PixelFormat::Rgba,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
dst_zero.set_plane_offset(0);
let mut dst_zero_dyn = TensorDyn::from(dst_zero);
gl.convert(&src_dyn, &mut dst_zero_dyn, None).unwrap();
let a = dst_no_off_dyn.as_u8().unwrap().map().unwrap();
let b = dst_zero_dyn.as_u8().unwrap().map().unwrap();
assert_pixels_match(a.as_slice(), b.as_slice(), 0);
}
/// Functional: allocate an oversized DMA buffer, import the second half
/// as a destination via PlaneDescriptor with offset, convert, and verify
/// the GPU wrote at the offset — not at byte 0.
#[test]
#[cfg(target_os = "linux")]
fn test_opengl_dst_nonzero_offset() {
use edgefirst_tensor::PlaneDescriptor;
use std::os::fd::AsFd;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let width = 640;
let height = 480;
let image_bytes = width * height * 4; // RGBA
let offset = image_bytes; // put image in the second half
// Allocate a DMA buffer twice the image size and fill with a sentinel
let large_buf =
Tensor::<u8>::new(&[image_bytes * 2], Some(TensorMemory::DmaBuf), None).unwrap();
large_buf.map().unwrap().as_mut_slice().fill(0xAA);
// Import the second half as an RGBA destination via PlaneDescriptor
let fd = large_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(offset);
let proc = crate::ImageProcessor::new().unwrap();
let mut dst = proc
.import_image(
plane,
None,
width,
height,
PixelFormat::Rgba,
DType::U8,
None,
)
.unwrap();
// Source: NV12 camera frame
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src;
gl.convert(&src_dyn, &mut dst, None).unwrap();
// Verify: the first half (before offset) must still be our sentinel
let map = large_buf.map().unwrap();
let buf = map.as_slice();
let untouched = &buf[..offset];
assert!(
untouched.iter().all(|&b| b == 0xAA),
"GPU wrote before the offset boundary — offset not applied"
);
// Verify: the second half (at offset) should contain rendered data,
// not all sentinels
let rendered = &buf[offset..];
assert!(
rendered.iter().any(|&b| b != 0xAA),
"GPU did not write at the offset position — destination is still sentinel"
);
}
/// Destination with offset=0 via PlaneDescriptor import (same path as NPU
/// workflow) must produce identical output to a normal DMA allocation.
#[test]
#[cfg(target_os = "linux")]
fn test_opengl_dst_imported_offset_zero() {
use edgefirst_tensor::PlaneDescriptor;
use std::os::fd::AsFd;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let width = 640;
let height = 480;
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Reference: normal DMA destination
let dst_ref = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let src_dyn = src;
let mut dst_ref_dyn = dst_ref;
gl.convert(&src_dyn, &mut dst_ref_dyn, None).unwrap();
// Imported: PlaneDescriptor with offset=0
let dst_buf = Tensor::<u8>::image(
width,
height,
PixelFormat::Rgba,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let fd = dst_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(0);
let proc = crate::ImageProcessor::new().unwrap();
let mut dst_imported = proc
.import_image(
plane,
None,
width,
height,
PixelFormat::Rgba,
DType::U8,
None,
)
.unwrap();
gl.convert(&src_dyn, &mut dst_imported, None).unwrap();
let a = dst_ref_dyn.as_u8().unwrap().map().unwrap();
let b = dst_buf.map().unwrap();
assert_pixels_match(a.as_slice(), b.as_slice(), 1);
}
/// Functional: packed RGB destination with nonzero offset. This exercises
/// `create_egl_image_with_dims` (the two-pass RGB pipeline), which was the
/// specific function that had the hardcoded offset=0 bug.
#[test]
#[cfg(target_os = "linux")]
fn test_opengl_dst_nonzero_offset_rgb() {
use edgefirst_tensor::PlaneDescriptor;
use std::os::fd::AsFd;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let width = 640;
let height = 480;
let image_bytes = width * height * 3; // RGB
let offset = image_bytes; // put image in the second half
// Allocate a DMA buffer twice the image size and fill with a sentinel
let large_buf =
Tensor::<u8>::new(&[image_bytes * 2], Some(TensorMemory::DmaBuf), None).unwrap();
large_buf.map().unwrap().as_mut_slice().fill(0xAA);
// Import the second half as an RGB destination via PlaneDescriptor
let fd = large_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(offset);
let proc = crate::ImageProcessor::new().unwrap();
let mut dst = proc
.import_image(
plane,
None,
width,
height,
PixelFormat::Rgb,
DType::U8,
None,
)
.unwrap();
// Source: NV12 camera frame
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let src_dyn = src;
gl.convert(&src_dyn, &mut dst, None).unwrap();
// Verify: the first half (before offset) must still be our sentinel
let map = large_buf.map().unwrap();
let buf = map.as_slice();
let untouched = &buf[..offset];
assert!(
untouched.iter().all(|&b| b == 0xAA),
"GPU wrote before the offset boundary — RGB offset not applied"
);
// Verify: the second half (at offset) should contain rendered data
let rendered = &buf[offset..];
assert!(
rendered.iter().any(|&b| b != 0xAA),
"GPU did not write at the RGB offset position — destination is still sentinel"
);
}
// ---------------------------------------------------------------
// Neutron-scenario tests: large buffer + large offset
//
// These replicate the geometry of the EDGEAI-1192 bug (Neutron NPU
// DMA-BUF at offset 3,450,400 in a 10 MB buffer) using standard
// dma_heap allocations — no NPU driver required.
//
// The tests are gated on is_neutron_available() (/dev/neutron0) because
// the large-offset EGLImage import path works on Mali (i.MX 95) but
// fails with EGL(BadAccess) on Vivante (i.MX 8MP), confirmed by hardware
// testing. The gate is a platform discriminator, not an NPU check.
// ---------------------------------------------------------------
/// Direct reproduction of the Neutron scenario: 640×640 RGB int8
/// destination at offset 3,450,400 inside a ~10 MB DMA buffer.
/// Exercises the two-pass `convert_to_packed_rgb` with `is_int8=true`.
#[test]
#[cfg(target_os = "linux")]
fn test_neutron_scenario_large_offset_rgb_int8() {
use edgefirst_tensor::PlaneDescriptor;
use std::os::fd::AsFd;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
if !is_neutron_available() {
crate::test_support::report_skip(&format!(
"{} - Neutron not available (/dev/neutron0 not found)",
function!()
));
return;
}
let total_size: usize = 10_276_864; // Neutron shared buffer size
let offset: usize = 3_450_400; // Neutron input tensor offset
let image_bytes: usize = 640 * 640 * 3; // RGB
let Some(large_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[total_size], Some(TensorMemory::DmaBuf), None),
"Neutron-sized DMA buffer",
) else {
return;
};
large_buf.map().unwrap().as_mut_slice().fill(0xAA);
let fd = large_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(offset);
let proc = crate::ImageProcessor::new().unwrap();
let mut dst = proc
.import_image(plane, None, 640, 640, PixelFormat::Rgb, DType::I8, None)
.unwrap();
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
gl.convert(&src, &mut dst, None).unwrap();
// Verify: sentinel intact before offset
let map = large_buf.map().unwrap();
let buf = map.as_slice();
let untouched = &buf[..offset];
assert!(
untouched.iter().all(|&b| b == 0xAA),
"GPU wrote before the offset boundary"
);
// Verify: rendered data at offset
let rendered = &buf[offset..offset + image_bytes];
assert!(
rendered.iter().any(|&b| b != 0xAA),
"GPU did not write at the offset position — destination is still sentinel"
);
}
/// Isolate two-pass vs single-pass: same large offset, RGBA U8
/// (single-pass EGLImage) vs RGB I8 (two-pass convert_to_packed_rgb).
/// If RGBA succeeds and RGB fails, the bug is in the two-pass path.
#[test]
#[cfg(target_os = "linux")]
fn test_neutron_scenario_rgba_vs_rgb_isolation() {
use edgefirst_tensor::PlaneDescriptor;
use std::os::fd::AsFd;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
if !is_neutron_available() {
crate::test_support::report_skip(&format!(
"{} - Neutron not available (/dev/neutron0 not found)",
function!()
));
return;
}
let total_size: usize = 10_276_864;
let offset: usize = 3_450_400;
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
// --- RGBA U8 at large offset (single-pass path) ---
let Some(rgba_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[total_size], Some(TensorMemory::DmaBuf), None),
"Neutron-sized DMA buffer",
) else {
return;
};
rgba_buf.map().unwrap().as_mut_slice().fill(0xAA);
let fd = rgba_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(offset);
let proc = crate::ImageProcessor::new().unwrap();
let mut dst_rgba = proc
.import_image(plane, None, 640, 640, PixelFormat::Rgba, DType::U8, None)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
let rgba_result = gl.convert(&src, &mut dst_rgba, None);
assert!(
rgba_result.is_ok(),
"RGBA U8 single-pass at large offset failed: {:?}",
rgba_result.err()
);
// --- RGB I8 at same large offset (two-pass path) ---
let Some(rgb_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[total_size], Some(TensorMemory::DmaBuf), None),
"Neutron-sized DMA buffer",
) else {
return;
};
rgb_buf.map().unwrap().as_mut_slice().fill(0xAA);
let fd = rgb_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(offset);
let mut dst_rgb = proc
.import_image(plane, None, 640, 640, PixelFormat::Rgb, DType::I8, None)
.unwrap();
let rgb_result = gl.convert(&src, &mut dst_rgb, None);
assert!(
rgb_result.is_ok(),
"RGB I8 two-pass at large offset failed (RGBA succeeded): {:?}",
rgb_result.err()
);
}
/// Isolate int8 shader: same two-pass RGB path, but U8 vs I8 dtype.
/// If RGB U8 succeeds and RGB I8 fails, the int8 shader interacts
/// poorly with large-offset FBOs.
#[test]
#[cfg(target_os = "linux")]
fn test_neutron_scenario_rgb_u8_vs_int8() {
use edgefirst_tensor::PlaneDescriptor;
use std::os::fd::AsFd;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
if !is_neutron_available() {
crate::test_support::report_skip(&format!(
"{} - Neutron not available (/dev/neutron0 not found)",
function!()
));
return;
}
let total_size: usize = 10_276_864;
let offset: usize = 3_450_400;
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let proc = crate::ImageProcessor::new().unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// --- RGB U8 at large offset (two-pass, packed_rgba8_program_2d) ---
let Some(u8_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[total_size], Some(TensorMemory::DmaBuf), None),
"Neutron-sized DMA buffer",
) else {
return;
};
u8_buf.map().unwrap().as_mut_slice().fill(0xAA);
let fd = u8_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(offset);
let mut dst_u8 = proc
.import_image(plane, None, 640, 640, PixelFormat::Rgb, DType::U8, None)
.unwrap();
let u8_result = gl.convert(&src, &mut dst_u8, None);
assert!(
u8_result.is_ok(),
"RGB U8 two-pass at large offset failed: {:?}",
u8_result.err()
);
// --- RGB I8 at same large offset (two-pass, packed_rgba8_int8_program_2d) ---
let Some(i8_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[total_size], Some(TensorMemory::DmaBuf), None),
"Neutron-sized DMA buffer",
) else {
return;
};
i8_buf.map().unwrap().as_mut_slice().fill(0xAA);
let fd = i8_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd).unwrap().with_offset(offset);
let mut dst_i8 = proc
.import_image(plane, None, 640, 640, PixelFormat::Rgb, DType::I8, None)
.unwrap();
let i8_result = gl.convert(&src, &mut dst_i8, None);
assert!(
i8_result.is_ok(),
"RGB I8 two-pass at large offset failed (U8 succeeded): {:?}",
i8_result.err()
);
}
/// Check if Mali requires page-aligned EGL offsets. The Neutron offset
/// 3,450,400 is NOT page-aligned (3,450,400 % 4096 = 3488). Compare
/// against the nearest page-aligned offset below it.
#[test]
#[cfg(target_os = "linux")]
fn test_neutron_scenario_offset_alignment() {
use edgefirst_tensor::PlaneDescriptor;
use std::os::fd::AsFd;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
if !is_neutron_available() {
crate::test_support::report_skip(&format!(
"{} - Neutron not available (/dev/neutron0 not found)",
function!()
));
return;
}
let total_size: usize = 10_276_864;
let page_aligned_offset: usize = 3_448_832; // 842 * 4096
let neutron_offset: usize = 3_450_400; // actual Neutron offset
let src = load_raw_image(
1280,
720,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&edgefirst_bench::testdata::read("camera720p.nv12"),
)
.unwrap();
let proc = crate::ImageProcessor::new().unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// --- Page-aligned offset ---
let Some(aligned_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[total_size], Some(TensorMemory::DmaBuf), None),
"Neutron-sized DMA buffer",
) else {
return;
};
aligned_buf.map().unwrap().as_mut_slice().fill(0xAA);
let fd = aligned_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd)
.unwrap()
.with_offset(page_aligned_offset);
let mut dst_aligned = proc
.import_image(plane, None, 640, 640, PixelFormat::Rgb, DType::I8, None)
.unwrap();
let aligned_result = gl.convert(&src, &mut dst_aligned, None);
assert!(
aligned_result.is_ok(),
"Page-aligned offset {} failed: {:?}",
page_aligned_offset,
aligned_result.err()
);
// --- Non-page-aligned Neutron offset ---
let Some(unaligned_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[total_size], Some(TensorMemory::DmaBuf), None),
"Neutron-sized DMA buffer",
) else {
return;
};
unaligned_buf.map().unwrap().as_mut_slice().fill(0xAA);
let fd = unaligned_buf.as_dma().unwrap().fd.as_fd();
let plane = PlaneDescriptor::new(fd)
.unwrap()
.with_offset(neutron_offset);
let mut dst_unaligned = proc
.import_image(plane, None, 640, 640, PixelFormat::Rgb, DType::I8, None)
.unwrap();
let unaligned_result = gl.convert(&src, &mut dst_unaligned, None);
assert!(
unaligned_result.is_ok(),
"Non-page-aligned Neutron offset {} failed (page-aligned {} succeeded): {:?}",
neutron_offset,
page_aligned_offset,
unaligned_result.err()
);
}
// =========================================================================
// PlaneDescriptor stride/offset integration tests for import_image
// =========================================================================
/// Baseline: import a tightly-packed RGBA DMA buffer with explicit stride
/// equal to width * 4. Verifies that import_image succeeds and the
/// returned tensor has the expected dimensions and format.
#[test]
#[cfg(target_os = "linux")]
fn test_import_image_rgba_with_stride() {
use edgefirst_tensor::PlaneDescriptor;
if !is_dma_available() {
crate::test_support::report_skip(
"test_import_image_rgba_with_stride - DMA not available",
);
return;
}
let width: usize = 640;
let height: usize = 480;
let bpp: usize = 4; // RGBA
let stride = width * bpp; // 2560, tightly packed
// Allocate a DMA tensor large enough for the RGBA image
let Some(buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(
&[height, width, bpp],
Some(TensorMemory::DmaBuf),
Some("import_rgba_tight"),
),
"DMA buffer",
) else {
return;
};
let fd = buf.dmabuf().unwrap();
let plane = PlaneDescriptor::new(fd).unwrap().with_stride(stride);
let proc = crate::ImageProcessor::new().unwrap();
let imported = proc
.import_image(
plane,
None,
width,
height,
PixelFormat::Rgba,
DType::U8,
None,
)
.unwrap();
assert_eq!(imported.width(), Some(width));
assert_eq!(imported.height(), Some(height));
assert_eq!(imported.format(), Some(PixelFormat::Rgba));
assert_eq!(imported.row_stride(), Some(stride));
}
/// Import an RGBA DMA buffer with a padded stride (64-byte aligned).
/// The stride is larger than width * bpp; import_image must accept
/// the padding and report the correct shape.
#[test]
#[cfg(target_os = "linux")]
fn test_import_image_rgba_padded_stride() {
use edgefirst_tensor::PlaneDescriptor;
if !is_dma_available() {
crate::test_support::report_skip(
"test_import_image_rgba_padded_stride - DMA not available",
);
return;
}
let width: usize = 640;
let height: usize = 480;
let bpp: usize = 4;
// 64-byte aligned stride: ceil(640*4 / 64) * 64 = 2560 (already aligned)
// Use 128-byte alignment to get a genuinely padded stride.
let stride: usize = (width * bpp).div_ceil(128) * 128; // 2560 -> 2560 (already 128-aligned)
// Force a wider stride to be sure it's padded
let stride = stride + 128; // 2688
// Allocate a DMA buffer large enough for the padded rows
let total_bytes = stride * height;
let Some(buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(
&[total_bytes],
Some(TensorMemory::DmaBuf),
Some("import_rgba_padded"),
),
"DMA buffer",
) else {
return;
};
let fd = buf.dmabuf().unwrap();
let plane = PlaneDescriptor::new(fd).unwrap().with_stride(stride);
let proc = crate::ImageProcessor::new().unwrap();
let imported = proc
.import_image(
plane,
None,
width,
height,
PixelFormat::Rgba,
DType::U8,
None,
)
.unwrap();
assert_eq!(imported.width(), Some(width));
assert_eq!(imported.height(), Some(height));
assert_eq!(imported.format(), Some(PixelFormat::Rgba));
assert_eq!(imported.row_stride(), Some(stride));
}
/// Import a DMA buffer as multiplane NV12 with explicit offsets.
/// The luma plane starts at offset 0 and the chroma plane starts at
/// height * stride. This mirrors the layout produced by V4L2 camera
/// drivers that expose NV12 as two separate planes sharing one fd.
#[test]
#[cfg(target_os = "linux")]
fn test_import_image_nv12_with_offset() {
use edgefirst_tensor::PlaneDescriptor;
if !is_dma_available() {
crate::test_support::report_skip(
"test_import_image_nv12_with_offset - DMA not available",
);
return;
}
let width: usize = 640;
let height: usize = 480;
let stride: usize = 640; // NV12 luma stride = width (1 byte per pixel)
let luma_size = height * stride;
let chroma_h = height / 2;
let chroma_size = chroma_h * stride;
let total_bytes = luma_size + chroma_size;
// Single DMA buffer holding both luma and chroma planes
let Some(buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(
&[total_bytes],
Some(TensorMemory::DmaBuf),
Some("import_nv12_planes"),
),
"DMA buffer",
) else {
return;
};
let fd = buf.dmabuf().unwrap();
let luma_plane = PlaneDescriptor::new(fd)
.unwrap()
.with_stride(stride)
.with_offset(0);
let chroma_plane = PlaneDescriptor::new(fd)
.unwrap()
.with_stride(stride)
.with_offset(luma_size);
let proc = crate::ImageProcessor::new().unwrap();
let imported = proc
.import_image(
luma_plane,
Some(chroma_plane),
width,
height,
PixelFormat::Nv12,
DType::U8,
None,
)
.unwrap();
assert_eq!(imported.width(), Some(width));
assert_eq!(imported.height(), Some(height));
assert_eq!(imported.format(), Some(PixelFormat::Nv12));
}
/// True multiplane NV12 via `import_image` with separate DMA-BUFs
/// (libcamera style): full `import_image` → `eglCreateImage` →
/// `convert()` render path. Compares pixel output against contiguous
/// NV12 → RGBA reference.
#[test]
#[cfg(target_os = "linux")]
fn test_import_image_nv12_true_multiplane() {
use edgefirst_tensor::PlaneDescriptor;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
// Pin both the true-multiplane (separate fds) and contiguous sources to
// ExternalSampler so the compare tests import correctness, not path
// selection (see test_multiplane_nv12_to_rgba_opengl). Byte-exact on
// every DMA board.
let _nv_path = NvPathEnvGuard::set("sampler");
let nv12_bytes: &[u8] = &edgefirst_bench::testdata::read("camera720p.nv12");
let width: usize = 1280;
let height: usize = 720;
let stride: usize = width;
let y_size = stride * height;
let uv_size = stride * (height / 2);
assert_eq!(nv12_bytes.len(), y_size + uv_size);
// Two separate DMA allocations filled with real NV12 data
let Some(luma_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(&[y_size], Some(TensorMemory::DmaBuf), Some("true_mp_luma")),
"luma DMA buffer",
) else {
return;
};
luma_buf.map().unwrap().as_mut_slice()[..y_size].copy_from_slice(&nv12_bytes[..y_size]);
let Some(chroma_buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(
&[uv_size],
Some(TensorMemory::DmaBuf),
Some("true_mp_chroma"),
),
"chroma DMA buffer",
) else {
return;
};
chroma_buf.map().unwrap().as_mut_slice()[..uv_size].copy_from_slice(&nv12_bytes[y_size..]);
// Import via import_image with separate PlaneDescriptors
let luma_fd = luma_buf.dmabuf().unwrap();
let chroma_fd = chroma_buf.dmabuf().unwrap();
let luma_plane = PlaneDescriptor::new(luma_fd).unwrap().with_stride(stride);
let chroma_plane = PlaneDescriptor::new(chroma_fd).unwrap().with_stride(stride);
let proc = crate::ImageProcessor::new().unwrap();
let src = proc
.import_image(
luma_plane,
Some(chroma_plane),
width,
height,
PixelFormat::Nv12,
DType::U8,
None,
)
.unwrap();
assert!(src.is_multiplane(), "must be multiplane after import");
// Build contiguous reference for pixel comparison
let src_contig = load_raw_image(
width,
height,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
nv12_bytes,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Render true multiplane through full EGL pipeline
let mut dst_multi = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let result = gl.convert(&src, &mut dst_multi, None);
if declined_separate_chroma(&result, function!()) {
// The decline must still leave the caller a correct convert:
// ImageProcessor serves it on the CPU, which must match the CPU's
// answer for the same bytes held contiguously.
let mut proc = proc;
proc.convert(&src, &mut dst_multi, None).unwrap();
let mut dst_cpu = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::CPUProcessor::new()
.convert(&src_contig, &mut dst_cpu, None)
.unwrap();
let map_multi = dst_multi.as_u8().unwrap().map().unwrap();
let map_cpu = dst_cpu.as_u8().unwrap().map().unwrap();
assert_pixels_match(map_cpu.as_slice(), map_multi.as_slice(), 0);
return;
}
result.unwrap();
// Render contiguous reference
let mut dst_contig = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src_contig, &mut dst_contig, None).unwrap();
// True multiplane and contiguous must produce identical pixels.
let map_multi = dst_multi.as_u8().unwrap().map().unwrap();
let map_contig = dst_contig.as_u8().unwrap().map().unwrap();
assert_pixels_match(map_multi.as_slice(), map_contig.as_slice(), 0);
}
/// Contiguous single-fd NV12 via `import_image` (no chroma descriptor):
/// full `import_image` → `eglCreateImage` → `convert()` render path.
/// Compares pixel output against `load_raw_image` contiguous reference.
#[test]
#[cfg(target_os = "linux")]
fn test_import_image_nv12_contiguous() {
use edgefirst_tensor::PlaneDescriptor;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let nv12_bytes: &[u8] = &edgefirst_bench::testdata::read("camera720p.nv12");
let width: usize = 1280;
let height: usize = 720;
let stride: usize = width;
let total_bytes = nv12_bytes.len();
// Single DMA buffer holding Y+UV contiguously
let Some(buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(
&[total_bytes],
Some(TensorMemory::DmaBuf),
Some("nv12_contiguous"),
),
"DMA buffer",
) else {
return;
};
buf.map().unwrap().as_mut_slice()[..total_bytes].copy_from_slice(nv12_bytes);
// Import via import_image with NO chroma descriptor (contiguous path)
let fd = buf.dmabuf().unwrap();
let plane = PlaneDescriptor::new(fd).unwrap().with_stride(stride);
let proc = crate::ImageProcessor::new().unwrap();
let src = proc
.import_image(
plane,
None,
width,
height,
PixelFormat::Nv12,
DType::U8,
None,
)
.unwrap();
assert!(
!src.is_multiplane(),
"contiguous NV12 must not be multiplane"
);
// Build reference via load_raw_image (same data, same contiguous layout)
let src_ref = load_raw_image(
width,
height,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
nv12_bytes,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Render contiguous import_image path
let mut dst_imported = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut dst_imported, None).unwrap();
// Render reference
let mut dst_ref = TensorDyn::image(
width,
height,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src_ref, &mut dst_ref, None).unwrap();
// Compare: import_image contiguous and load_raw_image must produce identical pixels
let map_imported = dst_imported.as_u8().unwrap().map().unwrap();
let map_ref = dst_ref.as_u8().unwrap().map().unwrap();
assert_pixels_match(map_imported.as_slice(), map_ref.as_slice(), 0);
}
/// Attempt to import with a stride smaller than width * bpp.
/// import_image (via set_row_stride) must reject this with an error.
#[test]
#[cfg(target_os = "linux")]
fn test_import_image_stride_too_small() {
use edgefirst_tensor::PlaneDescriptor;
if !is_dma_available() {
crate::test_support::report_skip(
"test_import_image_stride_too_small - DMA not available",
);
return;
}
let width: usize = 640;
let height: usize = 480;
let bpp: usize = 4;
let bad_stride = width * bpp - 1; // one byte too narrow
let Some(buf) = crate::test_support::dma_allocated(
Tensor::<u8>::new(
&[height, width, bpp],
Some(TensorMemory::DmaBuf),
Some("import_bad_stride"),
),
"DMA buffer",
) else {
return;
};
let fd = buf.dmabuf().unwrap();
let plane = PlaneDescriptor::new(fd).unwrap().with_stride(bad_stride);
let proc = crate::ImageProcessor::new().unwrap();
let result = proc.import_image(
plane,
None,
width,
height,
PixelFormat::Rgba,
DType::U8,
None,
);
assert!(
result.is_err(),
"import_image should reject stride {bad_stride} < minimum {} for {width}x{height} RGBA",
width * bpp
);
}
// ──────────────────────────────────────────────────────────────────────
// src_rect clamping tests — verify that cropping from a larger buffer
// never samples padding pixels, even with GL_LINEAR bilinear filtering.
// ──────────────────────────────────────────────────────────────────────
/// Create a synthetic RGB tensor where the left half is pure red and the
/// right half is pure blue. Simulates a larger reused buffer where only a
/// sub-region contains the desired content.
fn make_red_blue_src(width: usize, height: usize) -> TensorDyn {
let mut t = TensorDyn::image(
width,
height,
PixelFormat::Rgb,
DType::U8,
None,
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 {
// Red
data[idx] = 255;
data[idx + 1] = 0;
data[idx + 2] = 0;
} else {
// Blue
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 output.
#[test]
fn test_src_rect_crop_no_bleed_gl() {
if !is_opengl_available() {
crate::test_support::report_skip(
"test_src_rect_crop_no_bleed_gl - OpenGL not available",
);
return;
}
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,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Crop only the right (blue) half
let crop = Crop::new().with_source(Some(crate::Region::new(
src_w / 2, // left = start of blue region
0,
src_w / 2, // width = blue half
src_h,
)));
if let Err(e) = gl.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
) {
// Vivante GL rejects RGB source textures. The src_rect no-bleed crop
// logic is still covered on RGBA-capable drivers (e.g. Mesa); Vivante
// RGB-source support is tracked for separate investigation.
if e.to_string().contains("RGB source") {
crate::test_support::report_skip(&format!("{} - {e}", function!()));
return;
}
panic!("{e}");
}
// Verify: every pixel in the output should be blue (R=0, G=0, B=255)
// with a small tolerance for GPU rounding.
let map = dst.as_u8().unwrap().map().unwrap();
let data = map.as_slice();
let pixel_count = dst_w * dst_h;
let mut max_red: u8 = 0;
for i in 0..pixel_count {
let r = data[i * 3];
let g = data[i * 3 + 1];
let b = data[i * 3 + 2];
max_red = max_red.max(r);
// Allow tiny rounding (≤2) on blue channel but no red contamination
assert!(
r <= 2 && g <= 2 && b >= 253,
"Pixel {i} has red bleed: RGB=({r},{g},{b}), expected pure blue"
);
}
assert!(
max_red <= 2,
"Max red channel value in output = {max_red}, expected 0 (no bleed from padding)"
);
}
/// Same test but with the crop at an exact colour boundary: crop starts
/// precisely at the red→blue transition. This is the worst case for
/// bilinear bleed since the leftmost sampled texel is adjacent to red.
#[test]
fn test_src_rect_boundary_crop_no_bleed_gl() {
if !is_opengl_available() {
crate::test_support::report_skip(
"test_src_rect_boundary_crop_no_bleed_gl - OpenGL not available",
);
return;
}
// Use a power-of-two size to avoid any sub-pixel alignment issues
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,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Crop the right half — the left boundary is exactly at the red→blue edge
let crop =
Crop::new().with_source(Some(crate::Region::new(src_w / 2, 0, src_w / 2, src_h)));
if let Err(e) = gl.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
) {
// Vivante GL rejects RGB source textures. The src_rect no-bleed crop
// logic is still covered on RGBA-capable drivers (e.g. Mesa); Vivante
// RGB-source support is tracked for separate investigation.
if e.to_string().contains("RGB source") {
crate::test_support::report_skip(&format!("{} - {e}", function!()));
return;
}
panic!("{e}");
}
let map = dst.as_u8().unwrap().map().unwrap();
let data = map.as_slice();
for i in 0..(dst_w * dst_h) {
let r = data[i * 3];
let g = data[i * 3 + 1];
let b = data[i * 3 + 2];
assert!(
r <= 2 && g <= 2 && b >= 253,
"Pixel {i} has contamination at boundary: RGB=({r},{g},{b})"
);
}
}
/// Crop the red (left) half and verify no blue bleeds in from the right.
/// Tests the opposite edge.
#[test]
fn test_src_rect_crop_left_half_no_bleed_gl() {
if !is_opengl_available() {
crate::test_support::report_skip(
"test_src_rect_crop_left_half_no_bleed_gl - OpenGL not available",
);
return;
}
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,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// Crop only the left (red) half
let crop = Crop::new().with_source(Some(crate::Region::new(0, 0, src_w / 2, src_h)));
if let Err(e) = gl.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
) {
// Vivante GL rejects RGB source textures. The src_rect no-bleed crop
// logic is still covered on RGBA-capable drivers (e.g. Mesa); Vivante
// RGB-source support is tracked for separate investigation.
if e.to_string().contains("RGB source") {
crate::test_support::report_skip(&format!("{} - {e}", function!()));
return;
}
panic!("{e}");
}
let map = dst.as_u8().unwrap().map().unwrap();
let data = map.as_slice();
for i in 0..(dst_w * dst_h) {
let r = data[i * 3];
let g = data[i * 3 + 1];
let b = data[i * 3 + 2];
assert!(
r >= 253 && g <= 2 && b <= 2,
"Pixel {i} has blue bleed: RGB=({r},{g},{b}), expected pure red"
);
}
}
// ── float_render_support unit tests ─────────────────────────────────────
// These are pure-logic tests; no GPU is required.
#[test]
fn vivante_disables_gl_float() {
use super::super::processor::float_render_support;
use crate::RenderDtypeSupport;
let s = float_render_support(true, false, true, true);
assert_eq!(
s,
RenderDtypeSupport {
f32: false,
f16: false
}
);
}
#[test]
fn non_vivante_reports_float_when_ext_present() {
use super::super::processor::float_render_support;
use crate::RenderDtypeSupport;
let s = float_render_support(false, false, true, true);
assert_eq!(
s,
RenderDtypeSupport {
f32: true,
f16: true
}
);
}
#[test]
fn refused_float_import_disables_gl_float() {
use super::super::processor::float_render_support;
use crate::RenderDtypeSupport;
// Adreno on a zero-copy backend: the float color buffer exists, but
// no float DMA-BUF import does, so no float destination is servable.
let s = float_render_support(false, true, true, true);
assert_eq!(
s,
RenderDtypeSupport {
f32: false,
f16: false
}
);
}
#[test]
fn no_ext_means_no_float() {
use super::super::processor::float_render_support;
use crate::RenderDtypeSupport;
let s = float_render_support(false, false, false, false);
assert_eq!(
s,
RenderDtypeSupport {
f32: false,
f16: false
}
);
}
// ── float_pbo_eligible unit tests ────────────────────────────────────────
// Pure-logic predicate; no GPU required. Compiled wherever the helper is,
// which is every platform with a GL backend: `create_image`'s zero-copy
// float gate calls it too, so it is no longer PBO-only.
#[test]
fn float_pbo_eligibility() {
use crate::{float_pbo_eligible, RenderDtypeSupport};
use edgefirst_tensor::DType;
let yes = RenderDtypeSupport {
f32: true,
f16: true,
};
let no = RenderDtypeSupport {
f32: false,
f16: false,
};
assert!(float_pbo_eligible(DType::F16, yes));
assert!(float_pbo_eligible(DType::F32, yes));
assert!(!float_pbo_eligible(DType::F16, no));
assert!(!float_pbo_eligible(DType::U8, yes));
}
// ── packed F32 NHWC shader source well-formedness ────────────────────────
// Pure string inspection; no GPU required.
#[test]
fn packed_f32_nhwc_shader_source_wellformed() {
use super::super::shaders::generate_packed_f32_nhwc_shader;
let s = generate_packed_f32_nhwc_shader();
assert!(s.contains("#version 300 es"));
assert!(s.contains("frag_value"));
assert!(s.contains("% 3")); // channel = x % 3
assert!(s.contains("src_rect_uv"));
assert!(s.contains("dst_rect_px"));
assert!(s.contains("pad_color"));
}
// ── RGBA16F-packed PlanarRgb F16 shader source well-formedness ──────────
// Pure string inspection; no GPU required.
#[test]
fn planar_rgb_f16_packed_shader_source_wellformed() {
use super::super::shaders::generate_planar_rgb_f16_packed_shader;
let s = generate_planar_rgb_f16_packed_shader();
assert!(s.contains("#version 300 es"));
assert!(s.contains("src_rect_uv"));
assert!(s.contains("dst_rect_px"));
assert!(s.contains("pad_color"));
assert!(s.contains("sample_planar_element"));
assert!(s.contains("vec4(e0, e1, e2, e3)"));
}
// ── classify_float_render unit tests ────────────────────────────────────
// Pure-logic classifier; no GPU required. The zero-copy float set is the
// one this build's leaf reports, so these read as "what this platform
// dispatches"; `float_dispatch`'s own tests pin both sets.
//
// A test here may only assert a fixed path when that path is the same
// under both sets -- the two PBO routes, which no set touches, and the
// planar F16 zero-copy render, which both sets carry. Anything else
// derives its expectation from the const below, or it fails on whichever
// leaf it was not written for.
use super::super::platform::{GlPlatform, Platform};
const ZERO_COPY_FLOAT: super::super::float_dispatch::ZeroCopyFloatSet =
<Platform as GlPlatform>::ZERO_COPY_FLOAT;
#[test]
fn dispatch_hailo_f32_pbo() {
use super::super::processor::{classify_float_render, FloatRenderPath};
use crate::RenderDtypeSupport;
let s = RenderDtypeSupport {
f32: true,
f16: true,
};
assert_eq!(
classify_float_render(
PixelFormat::Rgba,
PixelFormat::Rgb,
DType::F32,
TensorMemory::Pbo,
s,
ZERO_COPY_FLOAT,
),
FloatRenderPath::PboF32Nhwc
);
}
#[test]
fn dispatch_orin_f16_pbo() {
use super::super::processor::{classify_float_render, FloatRenderPath};
use crate::RenderDtypeSupport;
let s = RenderDtypeSupport {
f32: true,
f16: true,
};
assert_eq!(
classify_float_render(
PixelFormat::Rgba,
PixelFormat::PlanarRgb,
DType::F16,
TensorMemory::Pbo,
s,
ZERO_COPY_FLOAT,
),
FloatRenderPath::PboF16Nchw
);
}
#[test]
fn dispatch_f16_dma() {
use super::super::processor::{classify_float_render, FloatRenderPath};
use crate::RenderDtypeSupport;
let s = RenderDtypeSupport {
f32: true,
f16: true,
};
assert_eq!(
classify_float_render(
PixelFormat::Rgba,
PixelFormat::PlanarRgb,
DType::F16,
TensorMemory::DmaBuf,
s,
ZERO_COPY_FLOAT,
),
FloatRenderPath::ZeroCopyF16Nchw
);
}
// Was `dispatch_f32_dma_is_none` before Task B2: Rgba->Rgb F32 into a
// DmaBuf destination had no classified path anywhere. It is now the
// interleaved zero-copy render on a leaf that reports the full set
// (Windows) and still `None` on the leaves that report `PlanarF16`, so the
// expectation is derived from the leaf's own const rather than fixed --
// fixing it would fail this test on every non-Windows leaf.
// `float_dispatch`'s own tests pin both sets directly.
#[test]
fn dispatch_f32_dma_follows_this_leafs_zero_copy_set() {
use super::super::float_dispatch::ZeroCopyFloatSet;
use super::super::processor::{classify_float_render, FloatRenderPath};
use crate::RenderDtypeSupport;
let s = RenderDtypeSupport {
f32: true,
f16: true,
};
let expected = match ZERO_COPY_FLOAT {
ZeroCopyFloatSet::All => FloatRenderPath::ZeroCopyFloatNhwc,
ZeroCopyFloatSet::PlanarF16 => FloatRenderPath::None,
};
assert_eq!(
classify_float_render(
PixelFormat::Rgba,
PixelFormat::Rgb,
DType::F32,
TensorMemory::DmaBuf,
s,
ZERO_COPY_FLOAT,
),
expected
);
}
#[test]
fn dispatch_no_support_is_none() {
use super::super::processor::{classify_float_render, FloatRenderPath};
use crate::RenderDtypeSupport;
let s = RenderDtypeSupport {
f32: false,
f16: false,
};
assert_eq!(
classify_float_render(
PixelFormat::Rgba,
PixelFormat::Rgb,
DType::F32,
TensorMemory::Pbo,
s,
ZERO_COPY_FLOAT,
),
FloatRenderPath::None
);
}
// ── packed_planar_layout unit tests ─────────────────────────────────────
// Pure geometry helper; no GPU required.
#[test]
fn packed_planar_layout_640x640() {
use super::super::processor::packed_planar_layout;
// Logical [3,640,640] → packed surface (640/4, 3*640).
assert_eq!(packed_planar_layout(640, 640, 3), Some((160, 1920)));
}
#[test]
fn packed_planar_layout_non_multiple_of_4_rejected() {
use super::super::processor::packed_planar_layout;
// W not divisible by 4 cannot be packed into whole four-element texels.
assert_eq!(packed_planar_layout(642, 640, 3), None);
}
#[test]
fn packed_planar_layout_rectangular() {
use super::super::processor::packed_planar_layout;
// Non-square, W divisible by 4: surface (320/4, 3*240).
assert_eq!(packed_planar_layout(320, 240, 3), Some((80, 720)));
}
#[test]
fn packed_planar_layout_four_planes() {
use super::super::processor::packed_planar_layout;
// A PlanarRgba destination stacks a fourth plane onto the surface,
// which is what gives its shader a plane index of 3.
assert_eq!(packed_planar_layout(640, 480, 4), Some((160, 1920)));
assert_eq!(packed_planar_layout(640, 480, 3), Some((160, 1440)));
}
/// The int8 letterbox clear colour must be pre-biased (XOR 0x80) on EVERY
/// destination lowering: the int8 fragment shader biases rendered pixels
/// and the readback never adjusts the glClear'd letterbox region. The
/// former any→PBO and PBO→Mem paths skipped the bias, leaving their int8
/// letterbox fill 0x80 off versus the Mem→Mem result. Pin every PBO
/// src/dst combination's output byte-identical to the Mem→Mem oracle.
/// Runs only where image allocation resolves to PBO (Orin / PBO-transfer
/// targets); skipped elsewhere.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn pbo_int8_letterbox_matches_mem_oracle() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
let (sw, sh) = (64usize, 48usize);
let probe = proc
.create_image(
sw,
sh,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if probe.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!(
"{} - target does not allocate PBO images",
function!()
));
return;
}
let fill = |t: &TensorDyn| {
let mut map = t.as_u8().unwrap().map().unwrap();
for (i, px) in map
.as_mut_slice()
.as_chunks_mut::<4>()
.0
.iter_mut()
.enumerate()
{
px[0] = (i % 251) as u8;
px[1] = (i % 199) as u8;
px[2] = (i % 127) as u8;
px[3] = 255;
}
};
let src_pbo = probe;
fill(&src_pbo);
let src_mem = proc
.create_image(
sw,
sh,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill(&src_mem);
// 64×48 → 96×96 letterbox: 96×72 inner box, glClear'd bands above and
// below — the region whose int8 bias the PBO paths used to drop.
let lb = Crop::letterbox([114, 114, 114, 255]);
// Explicit `Some(Pbo)` requests are rejected (PBO backing exists only
// through auto-resolution), so the PBO destination is requested as
// `None` and the resolved memory asserted instead.
let mut convert_to_bytes = |src: &TensorDyn, dst_mem: TensorMemory, label: &str| {
let dst_req = match dst_mem {
TensorMemory::Pbo => None,
other => Some(other),
};
let mut dst = proc
.create_image(
96,
96,
PixelFormat::Rgb,
DType::I8,
dst_req,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
assert_eq!(dst.memory(), dst_mem, "{label}: dst backing not honoured");
let fallbacks_before = proc.convert_fallback_count();
proc.convert(src, &mut dst, Some(crate::ConvertOptions::new().crop(lb)))
.unwrap_or_else(|e| panic!("{label} convert failed: {e}"));
// Without this the test is vacuous on a GL-declining host: every
// convert here, oracle included, would produce the same CPU answer
// and every comparison below would pass with no GL coverage at
// all. `ComputeBackend::OpenGl` leaves `forced_backend` at `None`,
// so a decline is logged at debug and silently served by the CPU.
assert_eq!(
proc.convert_fallback_count(),
fallbacks_before,
"{label}: the GL path declined and ImageProcessor fell back to \
the CPU; the oracle would then be compared against itself"
);
dst.as_i8()
.unwrap()
.map()
.unwrap()
.as_slice()
.iter()
.map(|&v| v as u8)
.collect::<Vec<u8>>()
};
let oracle = convert_to_bytes(&src_mem, TensorMemory::Mem, "mem->mem");
for (src, src_name) in [(&src_mem, "mem"), (&src_pbo, "pbo")] {
for dst_mem in [TensorMemory::Mem, TensorMemory::Pbo] {
let label = format!("{src_name}->{dst_mem:?}");
let out = convert_to_bytes(src, dst_mem, &label);
assert_eq!(
oracle, out,
"{label}: int8 letterbox output diverged from mem->mem oracle"
);
}
}
}
/// On-GPU round-trip: RGBA8 → F32 NHWC `[H,W,3]` PBO via the GL float
/// render path, so the test genuinely exercises `convert_float_to_pbo`.
/// Uses an identity crop so the expected values are exact:
/// `dst[y,x,c] == src[y,x,c] / 255`.
///
/// **`ComputeBackend::OpenGl` does NOT disable the CPU fallback** -- it
/// leaves `forced_backend` at `None`, so a GL decline logs at debug and
/// `ImageProcessor::convert` quietly produces the CPU answer, whose
/// float widen (`b as f32 / 255.0`) is bit-exact against the GPU's. The
/// route is therefore asserted, not assumed: `convert_fallback_count()`
/// must not move across the convert.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn convert_f32_nhwc_pbo_roundtrip() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
// Force the OpenGL backend so a NotSupported from the GL float path
// surfaces as a hard error instead of being masked by CPU fallback.
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
if !proc.supported_render_dtypes().f32 {
crate::test_support::report_skip(&format!(
"{} - F32 render not supported",
function!()
));
return;
}
let w = 64usize;
let h = 64usize;
// RGBA8 source PBO with a known gradient.
let src = proc
.create_image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if src.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!(
"{} - RGBA8 src not PBO-backed",
function!()
));
return;
}
{
let mut map = src.as_u8().unwrap().map().unwrap();
for y in 0..h {
for x in 0..w {
let i = (y * w + x) * 4;
map[i] = (x * 4) as u8;
map[i + 1] = (y * 4) as u8;
map[i + 2] = 128;
map[i + 3] = 255;
}
}
}
// F32 Rgb PBO destination, same WxH (logical [H,W,3]).
let mut dst = proc
.create_image(
w,
h,
PixelFormat::Rgb,
DType::F32,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if dst.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!("{} - F32 dst not PBO-backed", function!()));
return;
}
// Run two converts on the same processor/source/dest so the second
// iteration exercises the texture size/format-cache reuse path (the
// float render target and PBO source texture are NOT reallocated on the
// 2nd call). Correctness must hold identically across both iterations.
let mut max_err = 0.0f32;
for iter in 0..2 {
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&src, &mut dst, None).unwrap();
assert_eq!(
proc.convert_fallback_count(),
fallbacks_before,
"the GL float path declined and ImageProcessor fell back to the CPU; \
this test's expectation is bit-exact against the CPU answer, so it \
would otherwise pass with no GL coverage at all"
);
let map = dst.as_f32().unwrap().map().unwrap();
assert_eq!(map.len(), w * h * 3);
for y in 0..h {
for x in 0..w {
let expect = [
(x * 4) as f32 / 255.0,
(y * 4) as f32 / 255.0,
128.0 / 255.0,
];
for c in 0..3 {
let got = map[(y * w + x) * 3 + c];
let err = (got - expect[c]).abs();
max_err = max_err.max(err);
assert!(
err < 1e-3,
"f32 dst[{y},{x},{c}]={got} expected {} (err {err}) iter {iter}",
expect[c]
);
}
}
}
}
eprintln!("convert_f32_nhwc_pbo_roundtrip: max_err={max_err} tol=1e-3 (2 iters)");
}
/// On-GPU resize: RGBA8 16x16 → F32 NHWC `[H,W,3]` PBO at 8x8 (2x
/// downscale, identity crop). The source R channel is a linear horizontal
/// ramp `R(x) = x * 16`, so the correct bilinear-resampled output at dst
/// pixel `dx` samples src at `x_src = (dx + 0.5) * 2 - 0.5 = 2*dx + 0.5`,
/// giving value `(2*dx + 0.5) * 16` normalized by `/255`. This value is
/// distinct from NEAREST (which would land on a single integer texel,
/// `2*dx * 16`), so the test discriminates bilinear vs NEAREST sampling.
///
/// The same route assertion as its siblings, for the same reason: the CPU
/// fallback resizes too, and within this tolerance its answer would pass.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn convert_f32_nhwc_pbo_resize_bilinear() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
if !proc.supported_render_dtypes().f32 {
crate::test_support::report_skip(&format!(
"{} - F32 render not supported",
function!()
));
return;
}
let sw = 16usize;
let sh = 16usize;
let dw = 8usize;
let dh = 8usize;
// RGBA8 source PBO: horizontal ramp R = x*16, G = y*16, B const.
let src = proc
.create_image(
sw,
sh,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if src.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!(
"{} - RGBA8 src not PBO-backed",
function!()
));
return;
}
{
let mut map = src.as_u8().unwrap().map().unwrap();
for y in 0..sh {
for x in 0..sw {
let i = (y * sw + x) * 4;
map[i] = (x * 16) as u8;
map[i + 1] = (y * 16) as u8;
map[i + 2] = 64;
map[i + 3] = 255;
}
}
}
// F32 Rgb PBO destination at the downscaled size (logical [dh,dw,3]).
let mut dst = proc
.create_image(
dw,
dh,
PixelFormat::Rgb,
DType::F32,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if dst.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!("{} - F32 dst not PBO-backed", function!()));
return;
}
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&src, &mut dst, None).unwrap();
assert_eq!(
proc.convert_fallback_count(),
fallbacks_before,
"the GL float path declined and ImageProcessor fell back to the CPU; \
this test's expectation is bit-exact against the CPU answer, so it \
would otherwise pass with no GL coverage at all"
);
let map = dst.as_f32().unwrap().map().unwrap();
assert_eq!(map.len(), dw * dh * 3);
// Bilinear: src sample position = (d + 0.5) * 2 - 0.5 = 2*d + 0.5.
// Edge dst pixels (d=0 sampling x_src=0.5, last d sampling beyond the
// last center) stay interior here: for dw=8, max x_src = 2*7+0.5=14.5,
// which is < 15 (last src column), so no clamping affects the ramp.
let tol = 2e-3f32;
let mut max_err = 0.0f32;
for dy in 0..dh {
for dx in 0..dw {
let x_src = 2.0 * dx as f32 + 0.5;
let y_src = 2.0 * dy as f32 + 0.5;
let expect = [(x_src * 16.0) / 255.0, (y_src * 16.0) / 255.0, 64.0 / 255.0];
for c in 0..3 {
let got = map[(dy * dw + dx) * 3 + c];
let err = (got - expect[c]).abs();
max_err = max_err.max(err);
assert!(
err < tol,
"f32 resize dst[{dy},{dx},{c}]={got} expected {} (err {err})",
expect[c]
);
}
}
}
eprintln!("convert_f32_nhwc_pbo_resize_bilinear: max_err={max_err} tol={tol}");
}
/// On-GPU round-trip: RGBA8 → F16 NCHW `[3,H,W]` PBO via the GL float
/// render path. Identity crop so `dst[c,y,x] == src[y,x,c] / 255` within
/// one f16 ULP at 1.0 (`2^-8`).
///
/// **`ComputeBackend::OpenGl` does NOT disable the CPU fallback** -- it
/// leaves `forced_backend` at `None`, so a GL decline logs at debug and
/// `ImageProcessor::convert` quietly produces the CPU answer, whose
/// float widen (`b as f32 / 255.0`) is bit-exact against the GPU's. The
/// route is therefore asserted, not assumed: `convert_fallback_count()`
/// must not move across the convert.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn convert_f16_nchw_pbo_roundtrip() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
use half::f16;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
if !proc.supported_render_dtypes().f16 {
crate::test_support::report_skip(&format!(
"{} - F16 render not supported",
function!()
));
return;
}
let w = 64usize;
let h = 64usize;
let src = proc
.create_image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if src.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!(
"{} - RGBA8 src not PBO-backed",
function!()
));
return;
}
{
let mut map = src.as_u8().unwrap().map().unwrap();
for y in 0..h {
for x in 0..w {
let i = (y * w + x) * 4;
map[i] = (x * 4) as u8;
map[i + 1] = (y * 4) as u8;
map[i + 2] = 128;
map[i + 3] = 255;
}
}
}
// F16 PlanarRgb PBO destination, logical [3,H,W].
let mut dst = proc
.create_image(
w,
h,
PixelFormat::PlanarRgb,
DType::F16,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if dst.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!("{} - F16 dst not PBO-backed", function!()));
return;
}
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&src, &mut dst, None).unwrap();
assert_eq!(
proc.convert_fallback_count(),
fallbacks_before,
"the GL float path declined and ImageProcessor fell back to the CPU; \
this test's expectation is bit-exact against the CPU answer, so it \
would otherwise pass with no GL coverage at all"
);
let map = dst.as_f16().unwrap().map().unwrap();
assert_eq!(map.len(), 3 * w * h);
let tol = 2.0f32.powi(-8);
let mut max_err = 0.0f32;
for c in 0..3 {
for y in 0..h {
for x in 0..w {
let expect = match c {
0 => (x * 4) as f32 / 255.0,
1 => (y * 4) as f32 / 255.0,
_ => 128.0 / 255.0,
};
let got: f32 = map[(c * h + y) * w + x].to_f32();
let err = (got - expect).abs();
max_err = max_err.max(err);
assert!(
err < tol,
"f16 dst[{c},{y},{x}]={got} expected {expect} (err {err})"
);
}
}
}
let _ = f16::from_f32(0.0); // silence unused import on configs without asserts
eprintln!("convert_f16_nchw_pbo_roundtrip: max_err={max_err} tol={tol}");
}
/// On-GPU round-trip: RGBA8 → F16 NCHW `[3,H,W]` DMA-BUF via the GL
/// float render path (`convert_float_to_zero_copy`). Identity crop, so
/// the expected values are exact: `dst[c,y,x] == src[y,x,c] / 255` within
/// one f16 ULP at 1.0 (`2^-8`).
///
/// **`ComputeBackend::OpenGl` does NOT disable the CPU fallback** -- it
/// leaves `forced_backend` at `None`, so a GL decline logs at debug and
/// `ImageProcessor::convert` quietly produces the CPU answer, which lands
/// within this tolerance. The route is therefore checked, not assumed:
/// `convert_fallback_count()` moving means the zero-copy import was
/// refused, and the run is reported as a skip rather than a pass.
///
/// Skip conditions (each reported as a warning):
/// 1. GL unavailable, or F16 render not supported (e.g. Vivante).
/// 2. `create_image(..., Dma)` returns `Err` on a host with no zero-copy
/// backing (e.g. dev host, Orin-nano with permission-denied); where the
/// backing exists the failure fails the test.
/// 3. The created tensor's `.memory()` is not `TensorMemory::DmaBuf` — it
/// fell back; only the real DMA path is of interest here.
/// 4. The GL path declined the destination import and the convert fell
/// back to the CPU — measured, not assumed. This desktop's NVIDIA EGL
/// refuses the import with GL 0x502, so the test used to report a pass
/// here having exercised no GL at all.
///
/// Runs on V3D/Mali targets where dma-heap and GL F16 render are both
/// available.
#[test]
fn convert_f16_nchw_dma_roundtrip() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
use half::f16;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
// Force the OpenGL backend so a GL path error (e.g. from
// convert_float_to_zero_copy) surfaces as Err instead of falling through
// to the CPU backend.
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
if !proc.supported_render_dtypes().f16 {
crate::test_support::report_skip(&format!(
"{} - F16 render not supported (Vivante?)",
function!()
));
return;
}
// Use a representative size: small dma-buf imports hit per-fourcc
// minimum-size limits on some GPUs (Mali rejects a tiny (W/4, 3H)
// RGBA16F surface), so 16x16 is unrepresentative. 256x256 matches the
// gpu-probe's validated F16 dma-buf size and the real preprocessing
// regime; sizes the GPU cannot import fall back to CPU in production.
let w = 256usize;
let h = 256usize;
// RGBA8 source with a known gradient (W%4==0 so f16 packing is valid).
let src = proc
.create_image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
{
let mut map = src.as_u8().unwrap().map().unwrap();
for y in 0..h {
for x in 0..w {
let i = (y * w + x) * 4;
map[i] = ((x * 255) / w) as u8;
map[i + 1] = ((y * 255) / h) as u8;
map[i + 2] = 128;
map[i + 3] = 255;
}
}
}
// F16 PlanarRgb DMA-BUF destination, logical [3,H,W].
let Some(mut dst) = crate::test_support::gpu_buffer_allocated(
proc.create_image(
w,
h,
PixelFormat::PlanarRgb,
DType::F16,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
),
"F16 PlanarRgb DMA destination",
) else {
return;
};
// Confirm the tensor is genuinely DMA-backed — skip if the allocator
// fell back to a different memory type.
if dst.memory() != TensorMemory::DmaBuf {
crate::test_support::report_skip(&format!(
"{} - F16 dst memory is {:?}, not Dma; DMA path not exercised",
function!(),
dst.memory()
));
return;
}
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&src, &mut dst, None).unwrap();
// Skip condition 4, and the reason it is a skip rather than an
// assertion: unlike the PBO siblings -- whose feed has no import to
// fail -- this one needs a working zero-copy EGLImage import of the
// DESTINATION, and a driver may refuse it (the NVIDIA desktop this
// was written on fails with GL 0x502). `ComputeBackend::OpenGl`
// keeps a CPU fallback, whose f16 answer is within this tolerance,
// so without the check the test reported a pass having exercised no
// GL at all.
if proc.convert_fallback_count() != fallbacks_before {
crate::test_support::report_skip(&format!(
"{} - the GL float path declined this DMA-BUF destination and \
ImageProcessor fell back to the CPU; there is no zero-copy \
coverage to check here",
function!()
));
return;
}
let map = dst.as_f16().unwrap().map().unwrap();
assert_eq!(map.len(), 3 * w * h);
let tol = 2.0f32.powi(-8);
let mut max_err = 0.0f32;
for c in 0..3 {
for y in 0..h {
for x in 0..w {
let expect = match c {
0 => ((x * 255) / w) as f32 / 255.0,
1 => ((y * 255) / h) as f32 / 255.0,
_ => 128.0 / 255.0,
};
let got: f32 = map[(c * h + y) * w + x].to_f32();
let err = (got - expect).abs();
max_err = max_err.max(err);
assert!(
err < tol,
"f16 dma dst[{c},{y},{x}]={got} expected {expect} (err {err})"
);
}
}
}
let _ = f16::from_f32(0.0); // silence unused import on configs without asserts
eprintln!("convert_f16_nchw_dma_roundtrip: max_err={max_err} tol={tol}");
}
/// GAP-3: F32 Rgb PBO destination with a `dst_rect` letterbox and
/// `dst_color` pad. Exercises the `src_rect_uv` / `dst_rect_px` /
/// `pad_color` shader uniforms that had no test coverage.
///
/// Setup:
/// - src: 4x4 RGBA8 all-solid known color (R=200, G=100, B=50, A=255)
/// - dst: 8x4 F32 Rgb PBO
/// - `dst_rect = (left:2, top:0, w:4, h:4)` → the middle 4 columns carry
/// the content; the outer 2+2 columns are filled with the pad color.
/// - `dst_color = [114, 114, 114, 255]` (standard letterbox grey)
///
/// Assertions:
/// - Pixels OUTSIDE dst_rect → ≈ 114/255 on all three channels (pad grey)
/// - Pixels INSIDE dst_rect → finite & in `[0, 1]`, representing the
/// content (exact normalization is GPU-dependent; we just need non-zero
/// and in-range)
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
fn convert_f32_pbo_letterbox_pad_color() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
if !proc.supported_render_dtypes().f32 {
crate::test_support::report_skip(&format!(
"{} - F32 render not supported",
function!()
));
return;
}
let src_w = 4usize;
let src_h = 4usize;
let dst_w = 8usize;
let dst_h = 4usize;
// RGBA8 source: solid known colour (R=200, G=100, B=50).
let src = proc
.create_image(
src_w,
src_h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if src.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!(
"{} - RGBA8 src not PBO-backed",
function!()
));
return;
}
{
let mut map = src.as_u8().unwrap().map().unwrap();
for chunk in map.as_chunks_mut::<4>().0 {
chunk[0] = 200;
chunk[1] = 100;
chunk[2] = 50;
chunk[3] = 255;
}
}
// F32 Rgb PBO destination (wider than src to create a letterbox).
let mut dst = proc
.create_image(
dst_w,
dst_h,
PixelFormat::Rgb,
DType::F32,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if dst.memory() != TensorMemory::Pbo {
crate::test_support::report_skip(&format!("{} - F32 dst not PBO-backed", function!()));
return;
}
// Letterbox: content lands in columns [2, 6); columns [0, 2) and
// [6, 8) are padded with the `dst_color`.
let crop = Crop::letterbox([114, 114, 114, 255]);
let fallbacks_before = proc.convert_fallback_count();
let result = proc.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
);
assert!(
result.is_ok(),
"F32 PBO letterbox convert must not error: {:?}",
result.err()
);
// `ComputeBackend::OpenGl` leaves `forced_backend` at `None`, so a GL
// decline is served by the CPU with only a debug log. The CPU
// letterbox writes the same pad colour, so without this the test
// passes with zero GL coverage.
assert_eq!(
proc.convert_fallback_count(),
fallbacks_before,
"the GL float path declined and ImageProcessor fell back to the \
CPU; the CPU letterbox writes the same pad colour, so this test \
would otherwise pass without exercising the GL path at all"
);
let map = dst.as_f32().unwrap().map().unwrap();
assert_eq!(map.len(), dst_w * dst_h * 3, "unexpected element count");
let pad_expected = 114.0f32 / 255.0;
let pad_tol = 4.0 / 255.0; // generous: GPU blend precision
// Columns 0 and 1 are outside dst_rect → should carry the pad color.
for row in 0..dst_h {
for col in [0usize, 1usize, 6usize, 7usize] {
let base = (row * dst_w + col) * 3;
for c in 0..3 {
let v = map[base + c];
assert!(
(v - pad_expected).abs() < pad_tol,
"pad pixel ({row},{col}) ch{c}={v} expected ≈{pad_expected} (tol {pad_tol})"
);
}
}
}
// Columns 2..6 are inside dst_rect → content, finite & in [0, 1].
for row in 0..dst_h {
for col in 2..6usize {
let base = (row * dst_w + col) * 3;
for c in 0..3 {
let v = map[base + c];
assert!(
v.is_finite() && (0.0..=1.0).contains(&v),
"content pixel ({row},{col}) ch{c}={v} is not finite or not in [0,1]"
);
}
}
}
eprintln!("convert_f32_pbo_letterbox_pad_color: PASS");
}
#[test]
#[cfg(target_os = "linux")] // CUDA interop is Tegra/Linux-only
fn convert_f32_pbo_cuda_map_roundtrip() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
if !crate::opengl_headless::cuda_policy::cuda_available_or_skip(
"convert_f32_pbo_cuda_map_roundtrip",
) {
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(_) => {
crate::opengl_headless::cuda_policy::require_or_skip(
false,
"convert_f32_pbo_cuda_map_roundtrip",
"no GL",
);
return;
}
};
if !crate::opengl_headless::cuda_policy::require_or_skip(
proc.supported_render_dtypes().f32,
"convert_f32_pbo_cuda_map_roundtrip",
"no f32 render",
) {
return;
}
let (w, h) = (64usize, 64usize);
let src = proc
.create_image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
{
let mut m = src.as_u8().unwrap().map().unwrap();
for i in 0..(w * h) {
m[i * 4] = (i % 255) as u8;
m[i * 4 + 1] = 0;
m[i * 4 + 2] = 128;
m[i * 4 + 3] = 255;
}
}
let mut dst = proc
.create_image(
w,
h,
PixelFormat::Rgb,
DType::F32,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if !crate::opengl_headless::cuda_policy::require_or_skip(
dst.memory() == TensorMemory::Pbo,
"convert_f32_pbo_cuda_map_roundtrip",
"dst not PBO (no CUDA-GL alloc here)",
) {
return;
}
// `ComputeBackend::OpenGl` leaves `forced_backend` at `None`, so a
// declined GL float path is served by the CPU into this same PBO and
// the CUDA mapping below reads the CPU's answer -- a pass with no GL
// coverage. Reported as a skip rather than a failure because the
// decline is a property of the host's driver, not of this code.
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&src, &mut dst, None).unwrap();
if proc.convert_fallback_count() != fallbacks_before {
crate::test_support::report_skip(
"convert_f32_pbo_cuda_map_roundtrip - the GL float path declined \
and the convert was served by the CPU; there is no GL coverage \
to check here",
);
return;
}
let cm = match dst.cuda_map() {
Some(cm) => cm,
None => {
crate::opengl_headless::cuda_policy::require_or_skip(
false,
"convert_f32_pbo_cuda_map_roundtrip",
"cuda_map returned None: CUDA-GL interop unavailable for this context",
);
return;
}
};
assert_eq!(
cm.len(),
w * h * 3 * 4,
"device buffer is [H,W,3] f32 bytes"
);
assert!(!cm.device_ptr().is_null());
assert_eq!(
cm.device_ptr() as usize % 256,
0,
"256-B aligned for TensorRT"
);
eprintln!(
"convert_f32_pbo_cuda_map_roundtrip: PASS device_ptr={:p} len={} align256={}",
cm.device_ptr(),
cm.len(),
(cm.device_ptr() as usize).is_multiple_of(256)
);
// drop(cm) unmaps so a subsequent convert() could reuse the PBO
}
/// C7: verify that the device pointer from `cuda_map()` holds the correct
/// NHWC float data. Copies the device buffer back to host via `cudaMemcpy`
/// and checks each `[y,x,c]` element matches the normalized source value
/// `src[y,x,c] / 255.0` within 1e-3. Uses a 16×16 identity crop so the
/// expected values are exact (no bilinear rounding).
#[test]
#[cfg(target_os = "linux")] // CUDA interop is Tegra/Linux-only
fn convert_f32_pbo_cuda_map_numeric() {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
use std::ffi::c_void;
if !crate::opengl_headless::cuda_policy::cuda_available_or_skip(
"convert_f32_pbo_cuda_map_numeric",
) {
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(_) => {
crate::opengl_headless::cuda_policy::require_or_skip(
false,
"convert_f32_pbo_cuda_map_numeric",
"no GL",
);
return;
}
};
if !crate::opengl_headless::cuda_policy::require_or_skip(
proc.supported_render_dtypes().f32,
"convert_f32_pbo_cuda_map_numeric",
"no f32 render",
) {
return;
}
let (w, h) = (16usize, 16usize);
// RGBA8 source with a known per-pixel gradient.
let src = proc
.create_image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
{
let mut m = src.as_u8().unwrap().map().unwrap();
for y in 0..h {
for x in 0..w {
let i = (y * w + x) * 4;
m[i] = ((x * 255) / w) as u8;
m[i + 1] = ((y * 255) / h) as u8;
m[i + 2] = 128;
m[i + 3] = 255;
}
}
}
// F32 Rgb PBO destination — NHWC layout [H,W,3].
let mut dst = proc
.create_image(
w,
h,
PixelFormat::Rgb,
DType::F32,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if !crate::opengl_headless::cuda_policy::require_or_skip(
dst.memory() == TensorMemory::Pbo,
"convert_f32_pbo_cuda_map_numeric",
"dst not PBO",
) {
return;
}
// `ComputeBackend::OpenGl` leaves `forced_backend` at `None`, so a
// declined GL float path is served by the CPU into this same PBO and
// the CUDA mapping below reads the CPU's answer -- a pass with no GL
// coverage. Reported as a skip rather than a failure because the
// decline is a property of the host's driver, not of this code.
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&src, &mut dst, None).unwrap();
if proc.convert_fallback_count() != fallbacks_before {
crate::test_support::report_skip(
"convert_f32_pbo_cuda_map_numeric - the GL float path declined \
and the convert was served by the CPU; there is no GL coverage \
to check here",
);
return;
}
let cm = match dst.cuda_map() {
Some(cm) => cm,
None => {
crate::opengl_headless::cuda_policy::require_or_skip(
false,
"convert_f32_pbo_cuda_map_numeric",
"cuda_map returned None: CUDA-GL interop unavailable for this context",
);
return;
}
};
let n = w * h * 3;
let mut host = vec![0f32; n];
// SAFETY: host has `n * 4` bytes allocated; device_ptr is valid for
// the lifetime of `cm` (cuda_map is still live here).
assert!(
unsafe {
edgefirst_tensor::memcpy_device_to_host(
host.as_mut_ptr() as *mut c_void,
cm.device_ptr() as *const c_void,
n * std::mem::size_of::<f32>(),
)
},
"cudaMemcpy device->host failed"
);
// dst is NHWC [H,W,3] f32, normalized [0,1]: dst[(y*w+x)*3 + c] ≈ src_channel/255
let mut max_err = 0f32;
for y in 0..h {
for x in 0..w {
let exp = [
((x * 255) / w) as f32 / 255.0,
((y * 255) / h) as f32 / 255.0,
128.0 / 255.0,
];
for c in 0..3 {
let got = host[(y * w + x) * 3 + c];
max_err = max_err.max((got - exp[c]).abs());
}
}
}
eprintln!("convert_f32_pbo_cuda_map_numeric: max_err={max_err}");
assert!(
max_err < 1e-3,
"device data does not match NHWC-normalized source (max_err={max_err})"
);
// drop(cm) unmaps
}
/// Full Jetson zero-copy OUTPUT flow, per native JPEG format:
/// JPEG decode → NV12/NV16/NV24/GREY source (JFIF/BT.601-full tagged) →
/// `convert()` → `Rgb` `F32` PBO output → `cuda_map()` →
/// `cudaMemcpy(D2H)` → compare to a CPU `convert()` reference.
///
/// Proves the device pointer a TensorRT client receives holds the
/// correctly-converted, colorimetry-correct pixels for every format the CPU
/// JPEG decoder emits — and that the JPEG→NVxx/GREY decode path itself works
/// end to end. On a Jetson (no `/dev/dma_heap`) the NV source has no GPU
/// path, so `convert()` runs on the CPU and writes into the CUDA-registered
/// output PBO; this test exercises exactly that CPU→PBO→CUDA hand-off.
///
/// **Exercising the CPU fallback is the point here, so this one asserts
/// no route** (issue #179). The subject and the reference are the same
/// `convert()` on the same processor, differing only in where the
/// destination lives, so whichever backend serves them serves both; the
/// claim under test is about the device pointer's contents, not about
/// which engine produced them.
#[cfg(target_os = "linux")]
fn jpeg_cuda_devptr_check(fixture: &str, expect_fmt: PixelFormat, w: usize, h: usize) {
use crate::{ComputeBackend, ImageProcessor, ImageProcessorConfig};
use edgefirst_codec::{ImageDecoder, ImageLoad};
use edgefirst_tensor::{Tensor, TensorMapTrait, TensorTrait};
use std::ffi::c_void;
if !crate::opengl_headless::cuda_policy::cuda_available_or_skip(fixture) {
return;
}
let mut proc = match ImageProcessor::with_config(ImageProcessorConfig {
backend: ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(_) => {
crate::opengl_headless::cuda_policy::require_or_skip(false, fixture, "no GL");
return;
}
};
if !crate::opengl_headless::cuda_policy::require_or_skip(
proc.supported_render_dtypes().f32,
fixture,
"no f32 render",
) {
return;
}
// Decode JPEG into its native format; the decoder tags JFIF (BT.601
// full-range), which the CPU convert below must honour.
let mut src_t = Tensor::<u8>::image(
w,
h,
expect_fmt,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dec = ImageDecoder::new();
let info = src_t
.load_image(&mut dec, &edgefirst_bench::testdata::read(fixture))
.unwrap();
assert_eq!(info.format, expect_fmt, "{fixture}: native decode format");
assert_eq!(
src_t.colorimetry(),
Some(edgefirst_tensor::Colorimetry::jfif()),
"{fixture}: decoder must tag JFIF colorimetry"
);
let src = TensorDyn::from(src_t);
// CPU reference: convert into a tight Mem Rgb F32.
let mut ref_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgb,
DType::F32,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
proc.convert(&src, &mut ref_dst, None).unwrap();
let ref_map = ref_dst.as_f32().unwrap().map().unwrap();
let ref_px = ref_map.as_slice();
// Rgb F32 PBO output → cuda_map (the buffer a TRT client binds).
let mut pbo_dst = proc
.create_image(
w,
h,
PixelFormat::Rgb,
DType::F32,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if !crate::opengl_headless::cuda_policy::require_or_skip(
pbo_dst.memory() == TensorMemory::Pbo,
fixture,
"dst not PBO",
) {
return;
}
proc.convert(&src, &mut pbo_dst, None).unwrap();
let cm = match pbo_dst.cuda_map() {
Some(cm) => cm,
None => {
crate::opengl_headless::cuda_policy::require_or_skip(
false,
fixture,
"cuda_map returned None: CUDA-GL interop unavailable for this context",
);
return;
}
};
assert!(!cm.device_ptr().is_null(), "{fixture}: null device_ptr");
assert_eq!(
cm.device_ptr() as usize % 256,
0,
"{fixture}: device_ptr must be 256-byte aligned for TensorRT"
);
let n = cm.len() / std::mem::size_of::<f32>();
let mut host = vec![0f32; n];
// SAFETY: `host` has `cm.len()` bytes; device_ptr is valid while `cm` lives.
assert!(
unsafe {
edgefirst_tensor::memcpy_device_to_host(
host.as_mut_ptr() as *mut c_void,
cm.device_ptr() as *const c_void,
cm.len(),
)
},
"{fixture}: cudaMemcpy device->host failed"
);
// Stride-aware compare: the device buffer carries the PBO's row pitch
// (`effective_row_stride`), the Mem reference is tight.
let dev_stride_elems =
pbo_dst.effective_row_stride().unwrap_or(w * 3 * 4) / std::mem::size_of::<f32>();
let mut max_err = 0f32;
for y in 0..h {
for x in 0..w {
for c in 0..3 {
let got = host[y * dev_stride_elems + x * 3 + c];
let exp = ref_px[(y * w + x) * 3 + c];
max_err = max_err.max((got - exp).abs());
}
}
}
eprintln!("jpeg_cuda_devptr {fixture} ({expect_fmt:?}): max_err={max_err}");
assert!(
max_err < 1e-3,
"{fixture}: cuda_map device buffer != CPU reference (max_err={max_err})"
);
}
#[test]
#[cfg(target_os = "linux")]
fn jpeg_nv12_convert_cuda_devptr() {
jpeg_cuda_devptr_check("zidane.jpg", PixelFormat::Nv12, 1280, 720);
}
#[test]
#[cfg(target_os = "linux")]
fn jpeg_nv16_convert_cuda_devptr() {
jpeg_cuda_devptr_check("zidane_422.jpg", PixelFormat::Nv16, 1280, 720);
}
#[test]
#[cfg(target_os = "linux")]
fn jpeg_nv24_convert_cuda_devptr() {
jpeg_cuda_devptr_check("zidane_444.jpg", PixelFormat::Nv24, 1280, 720);
}
#[test]
#[cfg(target_os = "linux")]
fn jpeg_grey_convert_cuda_devptr() {
jpeg_cuda_devptr_check("grey.jpg", PixelFormat::Grey, 1024, 681);
}
// =========================================================================
// Path B: NV16/NV24 → RGBA GPU round-trip tests
//
// Gate: Linux + runtime skip if DMA or GL unavailable (`HAL_TEST_REQUIRE_DMA=1` fails instead).
// Strategy: solid-colour sources → exact expected RGB computable from
// BT.601 full-range; assert Path B ran (no CPU fallback); assert output
// matches CPU reference within tolerance.
// =========================================================================
/// Compute expected BT.601 full-range RGB from raw Y, Cb, Cr byte values.
///
/// Matches the coefficient set used in both the CPU kernels and the
/// `generate_nv_to_rgba_shader_2d` shader (and the macOS `NV_TO_RGBA_FRAGMENT`).
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn yuv601_to_rgb(y: u8, cb: u8, cr: u8) -> [u8; 3] {
let yf = y as f32 / 255.0;
let up = cb as f32 / 255.0 - 128.0 / 255.0;
let vp = cr as f32 / 255.0 - 128.0 / 255.0;
let r = (yf + 1.402 * vp).clamp(0.0, 1.0);
let g = (yf - 0.344 * up - 0.714 * vp).clamp(0.0, 1.0);
let b = (yf + 1.772 * up).clamp(0.0, 1.0);
[
(r * 255.0 + 0.5) as u8,
(g * 255.0 + 0.5) as u8,
(b * 255.0 + 0.5) as u8,
]
}
/// Build a solid-colour NV16 (4:2:2) buffer of dimensions `(w, h)`.
///
/// Layout: `[H rows of Y][H rows of interleaved CbCr]` (contiguous, width-aligned).
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn make_nv16_solid(w: usize, h: usize, y: u8, cb: u8, cr: u8) -> Vec<u8> {
let y_plane = vec![y; w * h];
// NV16: H rows of UV, each row has w/2 pairs → w bytes/row.
let uv_plane: Vec<u8> = std::iter::repeat_n([cb, cr], w * h / 2).flatten().collect();
[y_plane, uv_plane].concat()
}
/// Build a solid-colour NV24 (4:4:4) buffer of dimensions `(w, h)`.
///
/// Layout: `[H rows of Y][H rows of interleaved CbCr full-res]`.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn make_nv24_solid(w: usize, h: usize, y: u8, cb: u8, cr: u8) -> Vec<u8> {
let y_plane = vec![y; w * h];
// NV24: H rows of UV, each row has w pairs → 2w bytes/row.
let uv_plane: Vec<u8> = std::iter::repeat_n([cb, cr], w * h).flatten().collect();
[y_plane, uv_plane].concat()
}
/// Verify NV16→RGBA via Path B (R8 texelFetch shader) on DMA buffers.
///
/// Checks:
/// (a) `last_nv_convert_path` == `ShaderR8` — no CPU fallback.
/// (b) Every output pixel matches the expected BT.601 full-range RGB
/// within ±2 (rounding from f32 shader arithmetic).
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_gpu_nv16_to_rgba_path_b() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
// Solid YCbCr: Y=100, Cb=150, Cr=80 → deterministic RGB.
let (yv, cb, cr) = (100u8, 150u8, 80u8);
let expected = yuv601_to_rgb(yv, cb, cr);
let mut src = load_raw_image(
w,
h,
PixelFormat::Nv16,
Some(TensorMemory::DmaBuf),
&make_nv16_solid(w, h, yv, cb, cr),
)
.unwrap();
// `yuv601_to_rgb` is the full-range BT.601 reference, so tag the source
// full-range; otherwise the heuristic resolves untagged → limited.
src.set_colorimetry(Some(
edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full),
));
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src, &mut dst, None).unwrap();
// (a) Assert Path B ran — no CPU fallback for a DMA NV16 source.
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"NV16 DMA convert must use Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
// (b) Check pixel values against BT.601 reference within ±2.
let map = dst.as_u8().unwrap().map().unwrap();
let pixels = map.as_slice();
for i in 0..(w * h) {
let r = pixels[i * 4];
let g = pixels[i * 4 + 1];
let b = pixels[i * 4 + 2];
let diff_r = (r as i32 - expected[0] as i32).unsigned_abs();
let diff_g = (g as i32 - expected[1] as i32).unsigned_abs();
let diff_b = (b as i32 - expected[2] as i32).unsigned_abs();
assert!(
diff_r <= 2 && diff_g <= 2 && diff_b <= 2,
"pixel {i}: got ({r},{g},{b}) expected ({},{},{}) — diff ({diff_r},{diff_g},{diff_b})",
expected[0], expected[1], expected[2]
);
}
}
/// RAII guard: sets `EDGEFIRST_NV_CONVERT_PATH` and removes it on drop, so a
/// panic in `GLProcessorST::new` cannot leak the override to later tests.
/// GL tests run `--test-threads=1` (CI), so there is no concurrent reader.
#[cfg(target_os = "linux")]
struct NvPathEnvGuard;
#[cfg(target_os = "linux")]
impl NvPathEnvGuard {
fn set(v: &str) -> Self {
std::env::set_var("EDGEFIRST_NV_CONVERT_PATH", v);
NvPathEnvGuard
}
}
#[cfg(target_os = "linux")]
impl Drop for NvPathEnvGuard {
fn drop(&mut self) {
std::env::remove_var("EDGEFIRST_NV_CONVERT_PATH");
}
}
#[cfg(target_os = "linux")]
struct ColorimetryEnvGuard;
#[cfg(target_os = "linux")]
impl ColorimetryEnvGuard {
fn set(v: &str) -> Self {
std::env::set_var("EDGEFIRST_COLORIMETRY", v);
ColorimetryEnvGuard
}
}
#[cfg(target_os = "linux")]
impl Drop for ColorimetryEnvGuard {
fn drop(&mut self) {
std::env::remove_var("EDGEFIRST_COLORIMETRY");
}
}
/// HIGH-PERFORMANCE-default colorimetry policy (issue #106): under `auto`
/// a non-BT.601-limited single-plane NV12 DMA source takes the hardware
/// sampler on Vivante in the default [`ColorimetryMode::Fast`] (~12×
/// faster, driver's approximate fixed matrix) and the exact in-shader
/// path under the [`ColorimetryMode::Exact`] opt-in. On every other GPU
/// the in-shader path IS the fast path, so both modes pick it. Also pins:
/// BT.601-limited sources keep the sampler under Exact on Vivante (the
/// driver matrix matches exactly), and `EDGEFIRST_COLORIMETRY` wins over
/// the setter.
#[test]
#[cfg(target_os = "linux")]
fn colorimetry_mode_policy_nv12_auto() {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - GL not available", function!()));
return;
}
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
use crate::ColorimetryMode;
use edgefirst_tensor::{ColorEncoding, ColorRange, Colorimetry};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
let (w, h) = (64usize, 64usize);
let mut nv12 = vec![128u8; w * h * 3 / 2];
nv12[..w * h].fill(100);
let make_src = |enc: ColorEncoding, range: ColorRange| {
let mut src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::DmaBuf), &nv12).unwrap();
src.set_colorimetry(Some(
Colorimetry::default().with_encoding(enc).with_range(range),
));
src
};
let src_709 = make_src(ColorEncoding::Bt709, ColorRange::Full);
let src_601 = make_src(ColorEncoding::Bt601, ColorRange::Limited);
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut path_for = |gl: &mut GLProcessorST, src: &TensorDyn| {
gl.convert(src, &mut dst, None).unwrap();
gl.last_nv_convert_path
};
// Fast (default): sampler on Vivante regardless of colorimetry,
// in-shader matrix everywhere else.
let expect_fast = if gl.is_vivante {
NvConvertPath::ExternalSampler
} else {
NvConvertPath::ShaderR8
};
assert_eq!(
path_for(&mut gl, &src_709),
expect_fast,
"Fast mode, BT.709-full NV12"
);
// Exact opt-in: the approximate sampler is off the table for a
// non-matching colorimetry — in-shader matrix everywhere…
gl.set_colorimetry_mode(ColorimetryMode::Exact);
assert_eq!(
path_for(&mut gl, &src_709),
NvConvertPath::ShaderR8,
"Exact mode, BT.709-full NV12"
);
// …but a BT.601-limited source matches the Vivante driver matrix
// exactly, so the sampler carve-out survives Exact mode.
assert_eq!(
path_for(&mut gl, &src_601),
expect_fast,
"Exact mode, BT.601-limited NV12"
);
// A Grey destination must NEVER take the sampler, in either mode and
// for any colorimetry: samplerExternalOES → R8 render target wedges
// the Vivante GC7000UL (EDGEAI-1180 hang class; found when the Fast
// policy first routed nv12@dma→grey@dma to the sampler). ShaderR8 on
// every GPU. NOTE: this leg HANGS the board rather than failing if
// the gate regresses — keep it last-resort observable via the suite
// timeout.
let mut grey_dst = TensorDyn::image(
w,
h,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut grey_path = |gl: &mut GLProcessorST, src: &TensorDyn| {
gl.convert(src, &mut grey_dst, None).unwrap();
gl.last_nv_convert_path
};
gl.set_colorimetry_mode(ColorimetryMode::Fast);
assert_eq!(
grey_path(&mut gl, &src_709),
NvConvertPath::ShaderR8,
"Fast mode, BT.709 NV12 → Grey must avoid the sampler (R8 target)"
);
gl.set_colorimetry_mode(ColorimetryMode::Exact);
assert_eq!(
grey_path(&mut gl, &src_601),
NvConvertPath::ShaderR8,
"Exact mode, BT.601-limited NV12 → Grey must avoid the sampler (R8 target)"
);
// EDGEFIRST_COLORIMETRY pins the mode for the processor's lifetime:
// a Fast request on an exact-pinned processor is kept at Exact.
drop(gl);
let _env = ColorimetryEnvGuard::set("exact");
let mut gl = GLProcessorST::new(None, None).unwrap();
gl.set_colorimetry_mode(ColorimetryMode::Fast);
assert_eq!(
path_for(&mut gl, &src_709),
NvConvertPath::ShaderR8,
"env-pinned Exact must override set_colorimetry_mode(Fast)"
);
}
/// `EDGEFIRST_NV_CONVERT_PATH` selects the NV12 GPU conversion path.
///
/// - `auto` (default) follows the `ColorimetryMode::Fast` policy:
/// `ExternalSampler` on Vivante (12× faster), `ShaderR8` everywhere
/// else (the exact path is already the fast path). The full policy
/// matrix is covered by `colorimetry_mode_policy_nv12_auto`.
/// - `shader` → `ShaderR8` always.
/// - `sampler` → the driver `ExternalSampler` path is selected; the actual
/// recorded path is `ExternalSampler` on success or `Cpu` if the driver
/// rejects the NV12 EGLImage import — never `ShaderR8`.
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_path_env_override() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (64usize, 64usize); // width % 4 == 0 so the sampler import is accepted
let mut bytes = vec![100u8; w * h]; // Y plane
for _ in 0..(w * h / 4) {
bytes.push(150); // Cb
bytes.push(80); // Cr
}
let run = |env: Option<&str>| -> Option<(NvConvertPath, bool)> {
// The env var is read once in `GLProcessorST::new`; the guard sets it
// for exactly that construction and removes it on drop (panic-safe).
let gl = {
std::env::remove_var("EDGEFIRST_NV_CONVERT_PATH");
let _guard = env.map(NvPathEnvGuard::set);
GLProcessorST::new(None, None)
};
let mut gl = match gl {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return None;
}
};
let mut src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::DmaBuf), &bytes)
.unwrap();
// Tag full-range (not BT.601-limited) so the `auto` leg exercises
// the colorimetry-mode policy: the default Fast mode still takes
// the sampler on Vivante, ShaderR8 everywhere else.
src.set_colorimetry(Some(
edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt709)
.with_range(edgefirst_tensor::ColorRange::Full),
));
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut dst, None).unwrap();
Some((gl.last_nv_convert_path, gl.is_vivante))
};
if let Some((p, is_vivante)) = run(None) {
let expect = if is_vivante {
// ColorimetryMode::Fast default: the 12×-faster sampler.
NvConvertPath::ExternalSampler
} else {
NvConvertPath::ShaderR8
};
assert_eq!(
p, expect,
"auto default: single-plane full-range NV12 policy pick"
);
}
if let Some((p, _)) = run(Some("shader")) {
assert_eq!(
p,
NvConvertPath::ShaderR8,
"forced shader must use ShaderR8"
);
}
if let Some((p, _)) = run(Some("sampler")) {
assert_ne!(
p,
NvConvertPath::ShaderR8,
"forced sampler must NOT use ShaderR8 (got ExternalSampler or Cpu)"
);
}
}
/// Phase 4b: a NON-DMA (heap/PBO) NV12 source must be GPU-converted via the
/// R8-UPLOAD `ShaderR8` path — not the CPU fallback. This is the path that
/// gives orin (no DMA-BUF EGLImage import) GPU NV conversion. Gated on
/// OpenGL only (NOT DMA), so it runs on orin.
///
/// Asserts: (a) `last_nv_convert_path == ShaderR8` for a `Mem` NV12 source;
/// (b) the GPU upload output matches the `CPUProcessor` reference within ±2
/// (same in-shader matrix as DMA `ShaderR8`).
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_nondma_upload_uses_shader() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (w, h) = (64usize, 64usize);
// Patterned NV12 (luma gradient + neutral chroma) — exercises the shader.
let mut bytes = vec![0u8; w * h];
for r in 0..h {
for c in 0..w {
bytes[r * w + c] = ((r + c) * 255 / (w + h)) as u8;
}
}
bytes.extend(std::iter::repeat_n(128u8, w * h / 2)); // neutral chroma
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// Non-DMA (Mem) NV12 source → must take the R8-upload ShaderR8 path.
let mem_src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::Mem), &bytes).unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&mem_src, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"non-DMA NV12 must use the R8-upload ShaderR8 path, not CPU (got {:?})",
gl.last_nv_convert_path
);
// CPU reference (same matrix) — outputs must agree within ±2.
let cpu_src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::Mem), &bytes).unwrap();
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&cpu_src, &mut cpu_dst, None)
.unwrap();
let gpu_map = gpu_dst.as_u8().unwrap().map().unwrap();
let cpu_map = cpu_dst.as_u8().unwrap().map().unwrap();
assert_pixels_match(cpu_map.as_slice(), gpu_map.as_slice(), 2);
}
/// Regression for the planar `select_nv_path` fix: NV12 (DMA) → PlanarRgb
/// must route through the colorimetry-exact `ShaderR8` two-pass — NOT the
/// driver `samplerExternalOES` the single-pass `convert_to_planar` used,
/// which diverged on chroma edges (V3D/Mali) and had no path for NV16/NV24.
/// Full-range tag keeps the path deterministic (avoids the Vivante carve-out).
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_to_planar_rgb_uses_shader_path() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (64usize, 64usize);
// NV12 with a vertical chroma edge — where the driver sampler diverged.
let mut bytes = Vec::with_capacity(w * h * 3 / 2);
for r in 0..h {
for c in 0..w {
bytes.push(((r + c) * 255 / (w + h)) as u8);
}
}
for _ in 0..h / 2 {
for c in 0..w / 2 {
let (cb, cr) = if c < w / 4 { (90, 160) } else { (200, 40) };
bytes.push(cb);
bytes.push(cr);
}
}
fn tag(t: &mut TensorDyn) {
t.set_colorimetry(Some(
edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt709)
.with_range(edgefirst_tensor::ColorRange::Full),
));
}
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// This test pins the EXACT pipeline (in-shader matrix matching the
// CPU reference at chroma edges), so it opts into
// ColorimetryMode::Exact — under the default Fast policy a Vivante
// board would legitimately take the approximate driver sampler
// (covered by colorimetry_mode_policy_nv12_auto).
gl.set_colorimetry_mode(crate::ColorimetryMode::Exact);
let mut src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::DmaBuf), &bytes).unwrap();
tag(&mut src);
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"NV12→PlanarRgb in Exact mode must use the ShaderR8 two-pass, not the driver sampler"
);
// Correctness: matches the CPU planar reference (the sampler did not).
let mut cpu_src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::Mem), &bytes).unwrap();
tag(&mut cpu_src);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::PlanarRgb,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&cpu_src, &mut cpu_dst, None)
.unwrap();
compare_images(&cpu_dst, &dst, 0.95, "nv12_to_planar_rgb_shader");
}
/// A 1280x720 NV12 frame whose luma and chroma vary over a few pixels,
/// like dense small objects: nearest and bilinear resampling differ by
/// 16-24 grey levels on it.
#[cfg(target_os = "linux")]
fn detailed_nv12() -> (usize, usize, Vec<u8>) {
let (w, h) = (1280usize, 720usize);
let mut nv12 = Vec::with_capacity(w * h * 3 / 2);
for y in 0..h {
for x in 0..w {
nv12.push((128.0 + 100.0 * (x as f32 * 0.9).sin() * (y as f32 * 0.7).cos()) as u8);
}
}
for y in 0..h / 2 {
for x in 0..w / 2 {
nv12.push((128.0 + 60.0 * (x as f32 * 1.3).sin()) as u8);
nv12.push((128.0 + 60.0 * (y as f32 * 1.1).cos()) as u8);
}
}
(w, h, nv12)
}
/// Float reference for the GL NV programs on a tight NV12 frame, sampling
/// a source crop `(x, y, w, h)` into `dw`x`dh` planar RGB bytes.
#[cfg(target_os = "linux")]
struct NvOracle<'a> {
nv12: &'a [u8],
w: usize,
h: usize,
k: crate::colorimetry::YuvToRgbCoeffs,
}
#[cfg(target_os = "linux")]
impl<'a> NvOracle<'a> {
fn new(nv12: &'a [u8], w: usize, h: usize, src: &TensorDyn) -> Self {
let cm = crate::colorimetry::resolve_colorimetry(src.colorimetry(), src.height());
let k = crate::colorimetry::yuv_to_rgb_coeffs(
cm.encoding
.unwrap_or(edgefirst_tensor::ColorEncoding::Bt709),
cm.range.unwrap_or(edgefirst_tensor::ColorRange::Limited),
);
NvOracle { nv12, w, h, k }
}
/// Luma, U or V (`plane` 0, 1, 2) at a clamped grid position.
fn sample(&self, plane: usize, x: isize, y: isize, r: (usize, usize, usize, usize)) -> f32 {
let (cx, cy, cw, ch) = r;
let byte = if plane == 0 {
let x = x.clamp(cx as isize, (cx + cw) as isize - 1) as usize;
let y = y.clamp(cy as isize, (cy + ch) as isize - 1) as usize;
self.nv12[y * self.w + x]
} else {
let x = x.clamp((cx / 2) as isize, (cx + cw).div_ceil(2) as isize - 1) as usize;
let y = y.clamp((cy / 2) as isize, (cy + ch).div_ceil(2) as isize - 1) as usize;
self.nv12[self.w * self.h + y * self.w + 2 * x + plane - 1]
};
byte as f32 / 255.0
}
fn rgb(&self, y: f32, u: f32, v: f32) -> [f32; 3] {
let k = &self.k;
let y = ((y - k.y_offset) * k.y_scale).max(0.0);
let (u, v) = (u - 128.0 / 255.0, v - 128.0 / 255.0);
[y + k.c_vr * v, y - k.c_ug * u - k.c_vg * v, y + k.c_ub * u].map(|c| c.clamp(0.0, 1.0))
}
/// The converted pixel at luma texel (x, y), with its co-sited chroma.
fn texel(&self, x: isize, y: isize, r: (usize, usize, usize, usize)) -> [f32; 3] {
let (cx, cy, cw, ch) = r;
let x = x.clamp(cx as isize, (cx + cw) as isize - 1);
let y = y.clamp(cy as isize, (cy + ch) as isize - 1);
self.rgb(
self.sample(0, x, y, r),
self.sample(1, x >> 1, y >> 1, r),
self.sample(2, x >> 1, y >> 1, r),
)
}
/// `NvSampling::Hardware`, `NvSampling::Shader` or nearest: the
/// source position of output pixel (dx, dy) is `(d + 0.5) * scale`.
fn render(
&self,
r: (usize, usize, usize, usize),
dw: usize,
dh: usize,
mode: &str,
) -> Vec<u8> {
let (cx, cy, cw, ch) = r;
let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
let mut out = vec![0u8; 3 * dw * dh];
for dy in 0..dh {
for dx in 0..dw {
let lx = cx as f32 + (dx as f32 + 0.5) * cw as f32 / dw as f32;
let ly = cy as f32 + (dy as f32 + 0.5) * ch as f32 / dh as f32;
let rgb = match mode {
"nearest" => self.texel(lx.floor() as isize, ly.floor() as isize, r),
"shader" => {
let (px, py) = (lx - 0.5, ly - 0.5);
let (x0, y0) = (px.floor() as isize, py.floor() as isize);
let (fx, fy) = (px - px.floor(), py - py.floor());
let t = |x, y| self.texel(x, y, r);
let (a, b, c, d) =
(t(x0, y0), t(x0 + 1, y0), t(x0, y0 + 1), t(x0 + 1, y0 + 1));
[0, 1, 2].map(|i| lerp(lerp(a[i], b[i], fx), lerp(c[i], d[i], fx), fy))
}
_ => {
let bil = |plane: usize, px: f32, py: f32| {
let (x0, y0) = (px.floor() as isize, py.floor() as isize);
let (fx, fy) = (px - px.floor(), py - py.floor());
let s = |x, y| self.sample(plane, x, y, r);
lerp(
lerp(s(x0, y0), s(x0 + 1, y0), fx),
lerp(s(x0, y0 + 1), s(x0 + 1, y0 + 1), fx),
fy,
)
};
let (cxp, cyp) = (lx / 2.0 - 0.5, ly / 2.0 - 0.5);
self.rgb(
bil(0, lx - 0.5, ly - 0.5),
bil(1, cxp, cyp),
bil(2, cxp, cyp),
)
}
};
for (c, v) in rgb.iter().enumerate() {
out[c * dw * dh + dy * dw + dx] = (v * 255.0).round() as u8;
}
}
}
out
}
}
#[cfg(target_os = "linux")]
fn planar_bytes(t: &TensorDyn) -> Vec<u8> {
match t.dtype() {
DType::I8 => t
.as_i8()
.unwrap()
.map()
.unwrap()
.as_slice()
.iter()
.map(|&v| v as u8 ^ 0x80)
.collect(),
_ => t.as_u8().unwrap().map().unwrap().as_slice().to_vec(),
}
}
#[cfg(target_os = "linux")]
fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
assert_eq!(a.len(), b.len());
a.iter()
.zip(b)
.map(|(&x, &y)| x.abs_diff(y) as u64)
.sum::<u64>() as f64
/ a.len() as f64
}
#[cfg(target_os = "linux")]
fn nv_test_processor() -> Option<crate::opengl_headless::processor::GLProcessorST> {
if !is_opengl_available() {
return None;
}
let mut gl = crate::opengl_headless::processor::GLProcessorST::new(None, None).ok()?;
// Exact keeps Vivante on the NV shader programs instead of the driver sampler.
gl.set_colorimetry_mode(crate::ColorimetryMode::Exact);
Some(gl)
}
/// A resizing NV12 convert must match the reference for the sampling it
/// took: `Hardware` filters luma and chroma on their own grids, `Shader`
/// blends four single-texel conversions, both with half-pixel centres
/// (OpenCV `INTER_LINEAR`) and every tap clamped to the crop. Covers host
/// and DMA sources, whole frames and crops, up and down, u8 and int8, and
/// both samplings via the hardware-filter switch.
///
/// Nearest sampling is 16-24 grey levels off on this frame. Bilinear is
/// under 0.8 on NVIDIA, Mali, Adreno, Tegra and V3D; Vivante's in-shader
/// YUV arithmetic adds about 1.7 on its saturated chroma, at 1:1 too.
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_resize_matches_its_sampling() {
use crate::opengl_headless::processor::NvSampling;
const MAX_MEAN_ERROR: f64 = 3.0;
let Some(mut gl) = nv_test_processor() else {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
};
let (sw, sh, nv12) = detailed_nv12();
let mut memories = vec![TensorMemory::Mem];
if is_dma_available() {
memories.push(TensorMemory::DmaBuf);
}
let whole = (0, 0, sw, sh);
let tile = (101usize, 53usize, 320usize, 180usize);
for mem in memories {
let src = load_raw_image(sw, sh, PixelFormat::Nv12, Some(mem), &nv12).unwrap();
let oracle = NvOracle::new(&nv12, sw, sh, &src);
for hw in [true, false] {
gl.set_nv_hw_filter(hw);
for (r, dw, dh, dtype) in [
(whole, 1792usize, 1008usize, DType::U8),
(whole, 896, 504, DType::U8),
(whole, 640, 360, DType::U8),
(whole, 1792, 1008, DType::I8),
(tile, 448, 252, DType::U8),
] {
let crop = if r == whole {
Crop::no_crop()
} else {
Crop::new().with_source(Some(crate::Region::new(r.0, r.1, r.2, r.3)))
};
let mut gpu = TensorDyn::image(
dw,
dh,
PixelFormat::PlanarRgb,
dtype,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(
&src,
&mut gpu,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let sampling = gl.last_nv_sampling.expect("an NV draw ran");
if !hw {
assert_eq!(
sampling,
NvSampling::Shader,
"hardware filtering is switched off"
);
} else if mem == TensorMemory::Mem {
assert_eq!(
sampling,
NvSampling::Hardware,
"an upload can always bind its chroma"
);
} else if gl.has_y2y() {
assert_ne!(
sampling,
NvSampling::Shader,
"a GPU with GL_EXT_YUV_target must filter an NV12 import in hardware"
);
}
let mode = match sampling {
NvSampling::Hardware | NvSampling::HardwareYuv => "hardware",
_ => "shader",
};
let mad = mean_abs_diff(&planar_bytes(&gpu), &oracle.render(r, dw, dh, mode));
assert!(
mad < MAX_MEAN_ERROR,
"{mem:?} {r:?}->{dw}x{dh} {dtype:?} {sampling:?}: {mad:.3} grey levels from the reference"
);
}
}
}
}
/// A source crop drawn 1:1 (a SAHI tile) must reproduce the crop's
/// pixels exactly: the same bytes the whole frame converts to there.
/// Comparing against the GL whole frame isolates geometry from each GPU's
/// YUV arithmetic, so this holds bit-exactly on every driver.
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_crop_1to1_matches_whole_frame() {
use crate::opengl_headless::processor::NvSampling;
let Some(mut gl) = nv_test_processor() else {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
};
let (sw, sh, nv12) = detailed_nv12();
let src =
load_raw_image(sw, sh, PixelFormat::Nv12, Some(TensorMemory::Mem), &nv12).unwrap();
let image = |w, h| {
TensorDyn::image(
w,
h,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap()
};
let mut whole = image(sw, sh);
gl.convert(&src, &mut whole, None).unwrap();
let whole = planar_bytes(&whole);
for (cx, cy) in [(101usize, 53usize), (100, 52)] {
let (cw, ch) = (320usize, 180usize);
let mut tile = image(cw, ch);
let crop = Crop::new().with_source(Some(crate::Region::new(cx, cy, cw, ch)));
gl.convert(
&src,
&mut tile,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
assert_eq!(gl.last_nv_sampling, Some(NvSampling::Single));
let tile = planar_bytes(&tile);
for c in 0..3 {
for y in 0..ch {
let got = &tile[c * cw * ch + y * cw..][..cw];
let want = &whole[c * sw * sh + (cy + y) * sw + cx..][..cw];
assert_eq!(got, want, "crop ({cx}, {cy}) channel {c} row {y} differs");
}
}
}
}
/// `Interpolation::Nearest` resizes NV12 through the single-tap program,
/// copying the source pixel under each output pixel's centre. The scales
/// (7/5 up, 3/5 down, odd numerators in lowest terms) keep every centre off
/// the boundary between two source pixels, where nearest has no unique
/// answer and GPU rounding may take either side.
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_nearest_interpolation() {
use crate::opengl_headless::processor::NvSampling;
let Some(mut gl) = nv_test_processor() else {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
};
gl.set_interpolation(crate::Interpolation::Nearest);
let (sw, sh, nv12) = detailed_nv12();
let src =
load_raw_image(sw, sh, PixelFormat::Nv12, Some(TensorMemory::Mem), &nv12).unwrap();
let oracle = NvOracle::new(&nv12, sw, sh, &src);
for (dw, dh) in [(1792usize, 1008usize), (768, 432)] {
let mut gpu = TensorDyn::image(
dw,
dh,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut gpu, None).unwrap();
assert_eq!(gl.last_nv_sampling, Some(NvSampling::Single));
let mad = mean_abs_diff(
&planar_bytes(&gpu),
&oracle.render((0, 0, sw, sh), dw, dh, "nearest"),
);
assert!(
mad < 3.0,
"{dw}x{dh}: nearest GL is {mad:.3} grey levels from the reference"
);
}
}
/// The profiler's letterbox on natural content: the GL bilinear resize
/// stays close to the CPU backend's (they differ only in how chroma is
/// upsampled, which natural chroma barely shows).
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_letterbox_close_to_cpu_on_camera_frame() {
let Some(mut gl) = nv_test_processor() else {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
};
let nv12: &[u8] = &edgefirst_bench::testdata::read("camera720p.nv12");
let src =
load_raw_image(1280, 720, PixelFormat::Nv12, Some(TensorMemory::Mem), nv12).unwrap();
let crop = letterbox_crop(1280, 720, 1792, 1024);
let image = |m| {
TensorDyn::image(
1792,
1024,
PixelFormat::PlanarRgb,
DType::U8,
m,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap()
};
let mut gpu = image(Some(TensorMemory::Mem));
gl.convert(
&src,
&mut gpu,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let mut cpu = image(None);
crate::cpu::CPUProcessor::new()
.convert(
&src,
&mut cpu,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let mad = mean_abs_diff(&planar_bytes(&gpu), &planar_bytes(&cpu));
assert!(
mad < 1.5,
"letterbox upscale: GL is {mad:.3} grey levels from the CPU backend"
);
}
/// `Interpolation::Nearest` switches the packed texture path to
/// `GL_NEAREST`: a resized checkerboard copies the source pixel under
/// each output centre (a 7/5 upscale keeps every centre off a pixel
/// boundary), where `Bilinear` blends.
#[test]
#[cfg(target_os = "linux")]
fn test_gl_texture_nearest_interpolation() {
let Some(mut gl) = nv_test_processor() else {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
};
let (sw, sh, dw, dh) = (40usize, 30usize, 56usize, 42usize);
let pixel = |x: usize, y: usize| if (x + y).is_multiple_of(2) { 16u8 } else { 235 };
let mut rgba = Vec::with_capacity(sw * sh * 4);
for y in 0..sh {
for x in 0..sw {
rgba.extend_from_slice(&[pixel(x, y), 128, 255 - pixel(x, y), 255]);
}
}
let src =
load_raw_image(sw, sh, PixelFormat::Rgba, Some(TensorMemory::Mem), &rgba).unwrap();
let mut want = Vec::with_capacity(dw * dh * 4);
for dy in 0..dh {
for dx in 0..dw {
let x = (dx * 2 + 1) * sw / (dw * 2);
let y = (dy * 2 + 1) * sh / (dh * 2);
want.extend_from_slice(&rgba[(y * sw + x) * 4..][..4]);
}
}
for (mode, exact) in [
(crate::Interpolation::Nearest, true),
(crate::Interpolation::Bilinear, false),
] {
gl.set_interpolation(mode);
let mut dst = TensorDyn::image(
dw,
dh,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut dst, None).unwrap();
let got = dst.as_u8().unwrap().map().unwrap().as_slice().to_vec();
assert_eq!(
got == want,
exact,
"{mode:?}: nearest copy expected = {exact}"
);
}
// A per-convert interpolation overrides the processor's (Bilinear,
// set last above) for that convert only.
let mut convert = |options: Option<crate::ConvertOptions>| {
let mut dst = TensorDyn::image(
dw,
dh,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut dst, options).unwrap();
dst.as_u8().unwrap().map().unwrap().as_slice().to_vec()
};
let nearest = crate::ConvertOptions::new().interpolation(crate::Interpolation::Nearest);
assert_eq!(convert(Some(nearest)), want, "per-convert Nearest");
assert_ne!(convert(None), want, "the processor's Bilinear is restored");
}
/// A source crop drawn 1:1 must read each crop pixel exactly on the
/// filtered (`LINEAR`) paths: the texture path for packed sources and,
/// on DMA, the driver external sampler that NV12 takes under the default
/// `ColorimetryMode::Fast` on Vivante. A one-pixel checkerboard turns any
/// sub-texel offset into a visible blend: a half-texel inset averaged it
/// to grey (110 levels off), while interpolation and filter-weight
/// precision leave up to 6 on Mali.
#[test]
#[cfg(target_os = "linux")]
fn test_gl_crop_1to1_is_exact() {
use crate::opengl_headless::processor::GLProcessorST;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
let (sw, sh) = (640usize, 360usize);
let checker = |x: usize, y: usize| if (x + y).is_multiple_of(2) { 16u8 } else { 235 };
let mut rgba = Vec::with_capacity(sw * sh * 4);
let mut nv12 = Vec::with_capacity(sw * sh * 3 / 2);
for y in 0..sh {
for x in 0..sw {
let v = checker(x, y);
rgba.extend_from_slice(&[v, 255 - v, v, 255]);
nv12.push(v);
}
}
nv12.resize(sw * sh * 3 / 2, 128);
let crop = Crop::new().with_source(Some(crate::Region::new(101, 53, 64, 48)));
let mut memories = vec![TensorMemory::Mem];
if is_dma_available() {
memories.push(TensorMemory::DmaBuf);
}
for mem in memories {
for (src_fmt, bytes) in [(PixelFormat::Rgba, &rgba), (PixelFormat::Nv12, &nv12)] {
if src_fmt == PixelFormat::Nv12 && mem != TensorMemory::DmaBuf {
continue; // host NV12 takes ShaderR8, covered elsewhere
}
let mut src = load_raw_image(sw, sh, src_fmt, Some(mem), bytes).unwrap();
src.set_colorimetry(Some(
edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Limited),
));
for dst_fmt in [PixelFormat::Rgba, PixelFormat::PlanarRgb] {
let image = |m| {
TensorDyn::image(
64,
48,
dst_fmt,
DType::U8,
m,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap()
};
let mut gpu = image(Some(mem));
gl.convert(
&src,
&mut gpu,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let mut cpu = image(None);
crate::cpu::CPUProcessor::new()
.convert(
&src,
&mut cpu,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let g = gpu.as_u8().unwrap().map().unwrap().as_slice().to_vec();
let c = cpu.as_u8().unwrap().map().unwrap().as_slice().to_vec();
let max = g.iter().zip(&c).map(|(&a, &b)| a.abs_diff(b)).max();
assert!(
max <= Some(16),
"{mem:?} {src_fmt:?}->{dst_fmt:?} 1:1 crop: max deviation {max:?} \
(path {:?})",
gl.last_nv_convert_path
);
}
}
}
}
/// Phase 4b coverage: NV16/NV24 (not just NV12) on a non-DMA (heap) source
/// must also GPU-convert via the R8-upload `ShaderR8` path and match CPU ≤2.
#[test]
#[cfg(target_os = "linux")]
fn test_nv16_nv24_nondma_upload_uses_shader() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let (w, h) = (64usize, 64usize);
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
// (format, chroma byte count): NV16 4:2:2 = w*h UV; NV24 4:4:4 = 2*w*h UV.
for (fmt, uv) in [(PixelFormat::Nv16, w * h), (PixelFormat::Nv24, 2 * w * h)] {
let mut bytes = vec![0u8; w * h];
for r in 0..h {
for c in 0..w {
bytes[r * w + c] = ((r + c) * 255 / (w + h)) as u8; // Y gradient
}
}
bytes.extend(std::iter::repeat_n(128u8, uv)); // neutral chroma
let mem_src = load_raw_image(w, h, fmt, Some(TensorMemory::Mem), &bytes).unwrap();
let mut gpu = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&mem_src, &mut gpu, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"non-DMA {fmt:?} must use the R8-upload ShaderR8 path (got {:?})",
gl.last_nv_convert_path
);
let cpu_src = load_raw_image(w, h, fmt, Some(TensorMemory::Mem), &bytes).unwrap();
let mut cpu = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&cpu_src, &mut cpu, None)
.unwrap();
assert_pixels_match(
cpu.as_u8().unwrap().map().unwrap().as_slice(),
gpu.as_u8().unwrap().map().unwrap().as_slice(),
2,
);
}
}
/// Diagnostic probe (Phase 2): quantify *why* the driver `ExternalSampler`
/// path diverges from the exact reference, separating colorimetry/matrix
/// error (flat regions) from chroma-upsampling error (chroma edges).
///
/// Converts NV12 three ways — `ExternalSampler` (driver YUV), `ShaderR8`
/// (exact in-shader matrix), and CPU (the heap/`Mem` reference, == the
/// profiler's 841 path) — and prints per-path deltas vs CPU. Run with
/// `--nocapture` and read the `PROBE[...]` lines per platform.
///
/// Asserts only that `ShaderR8` matches CPU on a SOLID frame (pure matrix —
/// must agree); the `ExternalSampler` divergence is characterised, not
/// bounded (it is platform-dependent and is the thing under study).
#[test]
#[ignore = "diagnostic probe — run manually on-target with --nocapture --ignored"]
#[cfg(target_os = "linux")]
fn probe_nv12_sampler_vs_shader_divergence() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (64usize, 64usize); // width % 4 == 0 for the sampler import
// Build NV12 (Y plane then h/2 rows of w/2 interleaved CbCr pairs). The
// chroma closure maps a luma column to (Cb, Cr).
let build = |y: u8, chroma: &dyn Fn(usize) -> (u8, u8)| -> Vec<u8> {
let mut buf = vec![y; w * h];
for _r in 0..h / 2 {
for c in 0..w / 2 {
let (cb, cr) = chroma(c * 2);
buf.push(cb);
buf.push(cr);
}
}
buf
};
let solid = build(120, &|_| (90, 160));
let edge = build(120, &|col| if col < w / 2 { (90, 160) } else { (200, 40) });
// Force a path via the env var (read at construction), then clear it.
let convert_dma = |env: &str, bytes: &[u8]| -> Option<(NvConvertPath, Vec<u8>)> {
std::env::set_var("EDGEFIRST_NV_CONVERT_PATH", env);
let gl = GLProcessorST::new(None, None);
std::env::remove_var("EDGEFIRST_NV_CONVERT_PATH");
let mut gl = match gl {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return None;
}
};
let src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::DmaBuf), bytes).unwrap();
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
gl.convert(&src, &mut dst, None).unwrap();
let out = dst.as_u8().unwrap().map().unwrap().to_vec();
Some((gl.last_nv_convert_path, out))
};
let cpu_ref = |bytes: &[u8]| -> Vec<u8> {
let src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::Mem), bytes).unwrap();
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src, &mut dst, None)
.unwrap();
dst.as_u8().unwrap().map().unwrap().to_vec()
};
// (max, mean, max in flat regions, max within ±2 cols of the w/2 edge)
let stats = |a: &[u8], b: &[u8]| -> (u32, f64, u32, u32) {
let (mut maxd, mut sum, mut maxflat, mut maxbound) = (0u32, 0u64, 0u32, 0u32);
for i in 0..w * h {
let boundary = ((i % w) as i64 - (w as i64 / 2)).abs() <= 2;
for ch in 0..3 {
let d = (a[i * 4 + ch] as i32 - b[i * 4 + ch] as i32).unsigned_abs();
maxd = maxd.max(d);
sum += d as u64;
if boundary {
maxbound = maxbound.max(d);
} else {
maxflat = maxflat.max(d);
}
}
}
(maxd, sum as f64 / (w * h * 3) as f64, maxflat, maxbound)
};
for (name, bytes) in [("solid", &solid), ("chroma-edge", &edge)] {
let cpu = cpu_ref(bytes);
let Some((ps, sampler)) = convert_dma("sampler", bytes) else {
return;
};
let Some((pb, shader)) = convert_dma("shader", bytes) else {
return;
};
let (smax, smean, sflat, sbound) = stats(&sampler, &cpu);
let (bmax, bmean, bflat, bbound) = stats(&shader, &cpu);
eprintln!(
"PROBE[{name}] ExternalSampler({ps:?}) vs CPU: max={smax} mean={smean:.2} \
flat(matrix)={sflat} boundary(chroma)={sbound}"
);
eprintln!(
"PROBE[{name}] ShaderR8({pb:?}) vs CPU: max={bmax} mean={bmean:.2} \
flat(matrix)={bflat} boundary(chroma)={bbound}"
);
if name == "solid" {
assert!(
bmax <= 4,
"ShaderR8 must match CPU reference on a solid frame (pure matrix): max={bmax}"
);
}
}
}
/// Diagnostic probe (Phase 4): isolate where the profiler's NV12→packed-RGB
/// DMA path diverges from the CPU reference (the 830-vs-841), using the
/// profiler's EXACT letterbox (mirrors `LetterboxTransform::compute`:
/// aspect-fit + neutral-grey `[114,114,114,255]` bars).
///
/// NV12 sampling already matches CPU at same size (Phase 2). This exercises
/// the camera→model letterbox resize. Reports DMA-GL vs `CPUProcessor`:
/// - `same-size` : no resize → baseline (sampling + pack).
/// - `lb-full` : whole frame incl. grey bars (catches bar-fill diffs).
/// - `lb-content` : the resized image region only (pure resize delta).
/// - shader vs sampler shows whether the driver's LINEAR resize is closer.
#[test]
#[ignore = "diagnostic probe — run manually on-target with --nocapture --ignored"]
#[cfg(target_os = "linux")]
fn probe_nv12_packed_letterbox_divergence() {
use crate::opengl_headless::processor::GLProcessorST;
use crate::{Fit, Region};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
// 16:9 source so fitting into a square model produces top/bottom bars.
let (sw, sh) = (192usize, 108usize);
let model = 96usize;
// Patterned NV12: luma gradient + a vertical chroma edge.
let mut bytes = Vec::with_capacity(sw * sh * 3 / 2);
for r in 0..sh {
for c in 0..sw {
bytes.push(((r + c) * 255 / (sw + sh)) as u8);
}
}
for _r in 0..sh / 2 {
for c in 0..sw / 2 {
let (cb, cr) = if c < sw / 4 { (90, 160) } else { (200, 40) };
bytes.push(cb);
bytes.push(cr);
}
}
// Mirror LetterboxTransform::compute (profiler/src/pipeline.rs:1648).
let scale = (model as f32 / sw as f32).min(model as f32 / sh as f32);
let scaled_w = (sw as f32 * scale).round() as usize;
let scaled_h = (sh as f32 * scale).round() as usize;
let pad_x = (model - scaled_w) / 2;
let pad_y = (model - scaled_h) / 2;
// Letterbox is now a resize mode (`Fit::Letterbox`); the backend computes
// the aspect-fit placement (pad_x/pad_y/scaled_*) internally via
// `Crop::resolve`, so the test no longer hand-builds a destination rect.
let letterbox = || {
Crop::new()
.with_source(Some(Region::new(0, 0, sw, sh)))
.with_fit(Fit::Letterbox {
pad: [114, 114, 114, 255],
})
};
let gl_packed = |env: &str, crop: Crop, dw: usize, dh: usize| -> Option<(usize, Vec<u8>)> {
std::env::set_var("EDGEFIRST_NV_CONVERT_PATH", env);
let g = GLProcessorST::new(None, None);
std::env::remove_var("EDGEFIRST_NV_CONVERT_PATH");
let mut g = match g {
Ok(x) => x,
Err(e) => {
crate::test_support::report_skip(&format!("{} - GL: {e}", function!()));
return None;
}
};
let src = load_raw_image(
sw,
sh,
PixelFormat::Nv12,
Some(TensorMemory::DmaBuf),
&bytes,
)
.unwrap();
let mut dst = TensorDyn::image(
dw,
dh,
PixelFormat::Rgb,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
if let Err(e) = g.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
) {
crate::test_support::report_skip(&format!(
"{} - {env} convert declined: {e}",
function!()
));
return None;
}
let stride = dst
.as_u8()
.unwrap()
.effective_row_stride()
.unwrap_or(dw * 3);
Some((stride, dst.as_u8().unwrap().map().unwrap().to_vec()))
};
let cpu_packed = |crop: Crop, dw: usize, dh: usize| -> (usize, Vec<u8>) {
let src =
load_raw_image(sw, sh, PixelFormat::Nv12, Some(TensorMemory::Mem), &bytes).unwrap();
let mut dst = TensorDyn::image(
dw,
dh,
PixelFormat::Rgb,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(
&src,
&mut dst,
Some(crate::ConvertOptions::new().crop(crop)),
)
.unwrap();
let stride = dst
.as_u8()
.unwrap()
.effective_row_stride()
.unwrap_or(dw * 3);
(stride, dst.as_u8().unwrap().map().unwrap().to_vec())
};
// Stride-aware delta over a pixel region [r0..r0+rh) × [c0..c0+cw) (RGB).
let region = |a: (&[u8], usize),
b: (&[u8], usize),
(c0, r0, cw, rh): (usize, usize, usize, usize)|
-> (u32, f64) {
let (mut mx, mut sum) = (0u32, 0u64);
for r in r0..r0 + rh {
for c in (c0 * 3)..((c0 + cw) * 3) {
let d = (a.0[r * a.1 + c] as i32 - b.0[r * b.1 + c] as i32).unsigned_abs();
mx = mx.max(d);
sum += d as u64;
}
}
(mx, sum as f64 / (cw * 3 * rh) as f64)
};
// same-size baseline (no resize)
let cpu0 = cpu_packed(Crop::no_crop(), sw, sh);
if let Some(g) = gl_packed("shader", Crop::no_crop(), sw, sh) {
let (mx, mean) = region((&g.1, g.0), (&cpu0.1, cpu0.0), (0, 0, sw, sh));
eprintln!("PROBE2[same-size] ShaderR8 vs CPU: max={mx} mean={mean:.2}");
}
// letterbox (aspect-fit + grey bars), full frame + content region only
let cpu1 = cpu_packed(letterbox(), model, model);
// Decisive content-region pixel dump: flip / offset / rescale vs CPU?
if let Some(g) = gl_packed("shader", letterbox(), model, model) {
let px = |buf: &[u8], stride: usize, r: usize, c: usize| {
let o = r * stride + c * 3;
(buf[o], buf[o + 1], buf[o + 2])
};
let (ctop, cleft) = (pad_y, pad_x);
let (cbot, cright) = (pad_y + scaled_h - 1, pad_x + scaled_w - 1);
eprintln!(
"DUMP content TL cpu={:?} gl={:?} | TR cpu={:?} gl={:?} | BL cpu={:?} gl={:?} | BR cpu={:?} gl={:?}",
px(&cpu1.1, cpu1.0, ctop, cleft),
px(&g.1, g.0, ctop, cleft),
px(&cpu1.1, cpu1.0, ctop, cright),
px(&g.1, g.0, ctop, cright),
px(&cpu1.1, cpu1.0, cbot, cleft),
px(&g.1, g.0, cbot, cleft),
px(&cpu1.1, cpu1.0, cbot, cright),
px(&g.1, g.0, cbot, cright),
);
}
for env in ["shader", "sampler"] {
if let Some(g) = gl_packed(env, letterbox(), model, model) {
let (fmx, fmean) = region((&g.1, g.0), (&cpu1.1, cpu1.0), (0, 0, model, model));
let (cmx, cmean) = region(
(&g.1, g.0),
(&cpu1.1, cpu1.0),
(pad_x, pad_y, scaled_w, scaled_h),
);
eprintln!(
"PROBE2[lb-full/{env:8}] vs CPU: max={fmx} mean={fmean:.2} \
lb-content: max={cmx} mean={cmean:.2}"
);
}
}
}
/// Verify NV24→RGBA via Path B (R8 texelFetch shader) on DMA buffers.
///
/// Checks:
/// (a) `last_nv_convert_path` == `ShaderR8` — no CPU fallback.
/// (b) Every output pixel matches the expected BT.601 full-range RGB
/// within ±2.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_gpu_nv24_to_rgba_path_b() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
// Solid YCbCr: Y=180, Cb=90, Cr=200 → deterministic RGB.
let (yv, cb, cr) = (180u8, 90u8, 200u8);
let expected = yuv601_to_rgb(yv, cb, cr);
let mut src = load_raw_image(
w,
h,
PixelFormat::Nv24,
Some(TensorMemory::DmaBuf),
&make_nv24_solid(w, h, yv, cb, cr),
)
.unwrap();
// Full-range source to match the full-range `yuv601_to_rgb` reference.
src.set_colorimetry(Some(
edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full),
));
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src, &mut dst, None).unwrap();
// (a) Assert Path B ran — no CPU fallback for a DMA NV24 source.
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"NV24 DMA convert must use Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
// (b) Check pixel values against BT.601 reference within ±2.
let map = dst.as_u8().unwrap().map().unwrap();
let pixels = map.as_slice();
for i in 0..(w * h) {
let r = pixels[i * 4];
let g = pixels[i * 4 + 1];
let b = pixels[i * 4 + 2];
let diff_r = (r as i32 - expected[0] as i32).unsigned_abs();
let diff_g = (g as i32 - expected[1] as i32).unsigned_abs();
let diff_b = (b as i32 - expected[2] as i32).unsigned_abs();
assert!(
diff_r <= 2 && diff_g <= 2 && diff_b <= 2,
"pixel {i}: got ({r},{g},{b}) expected ({},{},{}) — diff ({diff_r},{diff_g},{diff_b})",
expected[0], expected[1], expected[2]
);
}
}
/// Verify NV16→RGBA Path B output matches the CPU reference converter.
///
/// Builds a patterned NV16 source, runs it through the CPU and GPU
/// converters, and asserts the GPU output matches the CPU output within ±2.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_gpu_nv16_matches_cpu_reference() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
// Build a patterned NV16 source (varying luma + fixed neutral chroma).
let mut nv16 = vec![0u8; w * h * 2]; // H luma rows + H chroma rows
for row in 0..h {
for col in 0..w {
nv16[row * w + col] = ((row * 255) / h) as u8;
}
}
// Neutral chroma: Cb=128, Cr=128 → no colour shift.
for i in 0..w * h {
nv16[w * h + i] = 128;
}
let src_dma =
load_raw_image(w, h, PixelFormat::Nv16, Some(TensorMemory::DmaBuf), &nv16).unwrap();
let src_mem =
load_raw_image(w, h, PixelFormat::Nv16, Some(TensorMemory::Mem), &nv16).unwrap();
// CPU reference.
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
{
let mut cpu = crate::cpu::CPUProcessor::new();
cpu.convert(&src_mem, &mut cpu_dst, None).unwrap();
}
// GPU Path B.
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"NV16 DMA convert must use Path B"
);
let cpu_map = cpu_dst.as_u8().unwrap().map().unwrap();
let gpu_map = gpu_dst.as_u8().unwrap().map().unwrap();
let cpu_pixels = cpu_map.as_slice();
let gpu_pixels = gpu_map.as_slice();
let mut max_diff = 0u32;
for i in 0..(w * h * 4) {
let d = (gpu_pixels[i] as i32 - cpu_pixels[i] as i32).unsigned_abs();
max_diff = max_diff.max(d);
}
assert!(
max_diff <= 2,
"NV16 GPU Path B vs CPU reference: max_diff={max_diff} (tolerance 2)"
);
}
/// Verify NV24→RGBA Path B output matches the CPU reference converter.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn test_gpu_nv24_matches_cpu_reference() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
// Patterned NV24: varying luma, fixed neutral chroma.
let mut nv24 = vec![0u8; w * h * 3]; // H luma rows + 2H chroma rows
for row in 0..h {
for col in 0..w {
nv24[row * w + col] = ((row * 255) / h) as u8;
}
}
// Neutral chroma for NV24: 2*w*h chroma bytes, all 128.
for i in 0..w * h * 2 {
nv24[w * h + i] = 128;
}
let src_dma =
load_raw_image(w, h, PixelFormat::Nv24, Some(TensorMemory::DmaBuf), &nv24).unwrap();
let src_mem =
load_raw_image(w, h, PixelFormat::Nv24, Some(TensorMemory::Mem), &nv24).unwrap();
// CPU reference.
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
{
let mut cpu = crate::cpu::CPUProcessor::new();
cpu.convert(&src_mem, &mut cpu_dst, None).unwrap();
}
// GPU Path B.
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"NV24 DMA convert must use Path B"
);
let cpu_map = cpu_dst.as_u8().unwrap().map().unwrap();
let gpu_map = gpu_dst.as_u8().unwrap().map().unwrap();
let cpu_pixels = cpu_map.as_slice();
let gpu_pixels = gpu_map.as_slice();
let mut max_diff = 0u32;
for i in 0..(w * h * 4) {
let d = (gpu_pixels[i] as i32 - cpu_pixels[i] as i32).unsigned_abs();
max_diff = max_diff.max(d);
}
assert!(
max_diff <= 2,
"NV24 GPU Path B vs CPU reference: max_diff={max_diff} (tolerance 2)"
);
}
/// Verify a DMA NV12 source converts on the GPU (ExternalSampler or
/// ShaderR8, platform-dependent) and never silently falls back to CPU.
#[test]
#[cfg(target_os = "linux")]
fn test_nv12_dma_gpu_path_no_cpu_fallback() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (64usize, 64usize);
// Solid grey NV12 (Y=128, Cb=128, Cr=128).
let mut nv12 = vec![128u8; w * h];
nv12.extend(vec![128u8; w * h / 2]); // UV plane
let src =
load_raw_image(w, h, PixelFormat::Nv12, Some(TensorMemory::DmaBuf), &nv12).unwrap();
let mut dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src, &mut dst, None).unwrap();
// NV12 must stay on a GPU path (no CPU-fallback regression). The exact
// path is GPU-dependent: Path A (ExternalSampler) on Vivante, Path B (ShaderR8)
// elsewhere — single-plane Path A YUV sampling is unreliable on Mali.
assert!(
matches!(
gl.last_nv_convert_path,
NvConvertPath::ExternalSampler | NvConvertPath::ShaderR8
),
"NV12 DMA convert must use a GPU path (ExternalSampler/ShaderR8), got {:?}",
gl.last_nv_convert_path
);
}
/// Verify NV16→RGB **int8** output via Path B exercises the `nv_r8_int8`
/// packing program (XOR 0x80 bias) and matches the CPU i8 reference. The u8
/// Path B tests never reach the int8 packing shader; the quantized NPU
/// targets (imx8mp vx / imx95 Neutron) consume exactly this i8 output.
#[test]
#[cfg(target_os = "linux")]
fn test_gpu_nv16_path_b_int8_output() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (64usize, 64usize);
// Patterned luma (vertical gradient) + a mild chroma offset so the
// int8 bias is exercised across a range of values, not a single colour.
let mut nv16 = vec![0u8; w * h * 2];
for row in 0..h {
for col in 0..w {
nv16[row * w + col] = ((row * 255) / h) as u8;
}
}
for i in 0..w * h / 2 {
nv16[w * h + 2 * i] = 110; // Cb
nv16[w * h + 2 * i + 1] = 150; // Cr
}
let mut src_dma =
load_raw_image(w, h, PixelFormat::Nv16, Some(TensorMemory::DmaBuf), &nv16).unwrap();
let mut src_mem =
load_raw_image(w, h, PixelFormat::Nv16, Some(TensorMemory::Mem), &nv16).unwrap();
// Tag both BT.601 full-range so GPU and CPU resolve the same colorimetry
// (this test isolates the int8 bias path, not the matrix/range).
let cm = edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full);
src_dma.set_colorimetry(Some(cm));
src_mem.set_colorimetry(Some(cm));
// CPU reference, int8 RGB.
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgb,
DType::I8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
{
let mut cpu = crate::cpu::CPUProcessor::new();
cpu.convert(&src_mem, &mut cpu_dst, None).unwrap();
}
// GPU Path B, int8 RGB.
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgb,
DType::I8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"NV16 int8 DMA convert must use Path B"
);
// Compare raw i8 bytes (the XOR 0x80 bias lives in the data identically
// on both paths).
let cpu_map = cpu_dst.as_i8().unwrap().map().unwrap();
let gpu_map = gpu_dst.as_i8().unwrap().map().unwrap();
let n = w * h * 3;
let mut max_diff = 0u32;
for i in 0..n {
let d = (gpu_map.as_slice()[i] as i32 - cpu_map.as_slice()[i] as i32).unsigned_abs();
max_diff = max_diff.max(d);
}
assert!(
max_diff <= 2,
"NV16 int8 GPU Path B vs CPU reference: max_diff={max_diff} (tolerance 2)"
);
}
// =========================================================================
// Odd-dimension end-to-end cells (Deliverable B)
//
// Design contract:
// • Source is built as a patterned NV tensor with a pattern varying in
// BOTH x and y (a solid would mask addressing bugs — see the NV24 3H
// regression).
// • A Dma copy (for the GPU path) and a Mem copy (for the CPU reference)
// are filled identically, each at the tensor's own `effective_row_stride`.
// • The CPU reference is the trusted oracle (proven by odd_dim_cpu.rs).
// • Both maps are read at their real `effective_row_stride` × logical
// `width() × height()` so stride-padding bytes are never compared.
// • `last_nv_convert_path` is asserted before the pixel comparison so a
// silent CPU fallback cannot pass.
// =========================================================================
/// Fill a NV16/NV24/NV12 tensor (Dma or Mem) with a patterned, stride-aware
/// synthetic image that exercises both odd-width and odd-height boundaries.
///
/// Pattern: `Y(r,c) = (r*3 + c*5) % 256`
/// Chroma column `cc`, chroma row `cr_row`:
/// `Cb = (cc*7 + cr_row*11 + 40) % 256`
/// `Cr = (cc*13 + cr_row*3 + 80) % 256`
///
/// The chroma subsampling (cw_shift, ch_shift) follows each format:
/// NV12: (1,1) — 4:2:0 NV16: (1,0) — 4:2:2 NV24: (0,0) — 4:4:4
///
/// This is intentionally the same pattern as `make_odd_both_source` in
/// `odd_dim_cpu.rs` so the two test suites share an analytic ground truth.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn fill_patterned_nv(t: &TensorDyn) {
let fmt = t.format().unwrap();
let w = t.width().unwrap();
let h = t.height().unwrap();
let stride = t.effective_row_stride().unwrap();
let (cw_shift, ch_shift): (usize, usize) = match fmt {
PixelFormat::Nv12 => (1, 1),
PixelFormat::Nv16 => (1, 0),
PixelFormat::Nv24 => (0, 0),
_ => panic!("fill_patterned_nv: unsupported format {fmt:?}"),
};
let chroma_h = h.div_ceil(1 << ch_shift);
let chroma_w = w.div_ceil(1 << cw_shift);
let bound = t.as_u8().unwrap();
let mut m = bound.map().unwrap();
let buf = m.as_mut_slice();
let uv_start = stride * h;
// Fill luma: diagonal gradient varying in both x and y.
for r in 0..h {
for c in 0..w {
buf[r * stride + c] = ((r * 3 + c * 5) % 256) as u8;
}
}
// Fill chroma (interleaved [Cb, Cr] per chroma column).
// NV12/NV16 UV row pitch == stride; NV24 UV row pitch == stride*2.
let uv_row_stride = if fmt == PixelFormat::Nv24 {
stride * 2
} else {
stride
};
for cr_row in 0..chroma_h {
for cc in 0..chroma_w {
let cb_val = ((cc * 7 + cr_row * 11 + 40) % 256) as u8;
let cr_val = ((cc * 13 + cr_row * 3 + 80) % 256) as u8;
let uv_byte = uv_start + cr_row * uv_row_stride + cc * 2;
buf[uv_byte] = cb_val;
buf[uv_byte + 1] = cr_val;
}
}
}
/// Build a pair of identically-filled NV tensors: one `Dma` (for the GPU),
/// one `Mem` (for the CPU reference). Returns `(dma_src, mem_src)`.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn make_patterned_nv_pair(w: usize, h: usize, fmt: PixelFormat) -> (TensorDyn, TensorDyn) {
let mut dma = TensorDyn::image(
w,
h,
fmt,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut mem = TensorDyn::image(
w,
h,
fmt,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_patterned_nv(&dma);
fill_patterned_nv(&mem);
// Tag both sources BT.601 full-range so the GPU (shader) and CPU
// (`yuv` crate) sides resolve the SAME colorimetry — these GPU-vs-CPU
// comparisons must isolate the *path*, not the matrix/range. (Untagged,
// the heuristic picks limited range, whose ×1.164 luma gain amplifies
// the known odd-width chroma-edge delta past the ±4 tolerance.)
let cm = edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full);
dma.set_colorimetry(Some(cm));
mem.set_colorimetry(Some(cm));
(dma, mem)
}
/// Compare a GPU RGBA/RGB `u8` output against a CPU RGBA/RGB `u8` reference,
/// reading both maps at their real `effective_row_stride`.
///
/// Returns `(max_diff, first_failing_location)`.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn compare_gpu_vs_cpu_u8(
gpu_dst: &TensorDyn,
cpu_dst: &TensorDyn,
w: usize,
h: usize,
) -> (u32, Option<(usize, usize, usize)>) {
let channels = gpu_dst.format().unwrap().channels();
let gpu_t = gpu_dst.as_u8().unwrap();
let cpu_t = cpu_dst.as_u8().unwrap();
let gpu_stride = gpu_t.effective_row_stride().unwrap_or(w * channels);
let cpu_stride = cpu_t.effective_row_stride().unwrap_or(w * channels);
let gpu_map = gpu_t.map().unwrap();
let cpu_map = cpu_t.map().unwrap();
let gpu_px = gpu_map.as_slice();
let cpu_px = cpu_map.as_slice();
let mut max_diff = 0u32;
let mut first_fail: Option<(usize, usize, usize)> = None;
for row in 0..h {
for col in 0..w {
for ch in 0..channels {
let gi = row * gpu_stride + col * channels + ch;
let ci = row * cpu_stride + col * channels + ch;
let d = (gpu_px[gi] as i32 - cpu_px[ci] as i32).unsigned_abs();
if d > max_diff {
max_diff = d;
}
if first_fail.is_none() && d > 4 {
first_fail = Some((col, row, ch));
}
}
}
}
(max_diff, first_fail)
}
/// Compare a GPU RGB `i8` output against a CPU RGB `i8` reference,
/// reading both at their real `effective_row_stride`.
#[cfg(target_os = "linux")]
fn compare_gpu_vs_cpu_i8(gpu_dst: &TensorDyn, cpu_dst: &TensorDyn, w: usize, h: usize) -> u32 {
let channels = 3usize; // RGB only (i8 output is always Rgb)
let gpu_t = gpu_dst.as_i8().unwrap();
let cpu_t = cpu_dst.as_i8().unwrap();
let gpu_stride = gpu_t.effective_row_stride().unwrap_or(w * channels);
let cpu_stride = cpu_t.effective_row_stride().unwrap_or(w * channels);
let gpu_map = gpu_t.map().unwrap();
let cpu_map = cpu_t.map().unwrap();
let gpu_px = gpu_map.as_slice();
let cpu_px = cpu_map.as_slice();
let mut max_diff = 0u32;
for row in 0..h {
for col in 0..w {
for ch in 0..channels {
let gi = row * gpu_stride + col * channels + ch;
let ci = row * cpu_stride + col * channels + ch;
let d = (gpu_px[gi] as i32 - cpu_px[ci] as i32).unsigned_abs();
if d > max_diff {
max_diff = d;
}
}
}
}
max_diff
}
// -------------------------------------------------------------------------
// G-03: NV16 odd-W (65×64) → RGBA — Path B must run, GPU ≈ CPU ±4
// -------------------------------------------------------------------------
/// G-03: NV16 odd-width (65×64) end-to-end GPU vs CPU reference.
///
/// Asserts:
/// (a) `last_nv_convert_path == ShaderR8` — no CPU fallback.
/// (b) GPU output matches CPU reference within ±4 (per-pixel, each RGBA channel).
/// Tolerance 4 absorbs f32 shader rounding; identical fill on both sides
/// rules out test-infrastructure bias.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g03_nv16_odd_w_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (321usize, 240usize); // QVGA-scale odd width (Mali rejects sub-minimum textures)
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv16);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"G-03: NV16 odd-W must use Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-03 NV16 odd-W: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"G-03: NV16 odd-W GPU vs CPU max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
// -------------------------------------------------------------------------
// G-04: NV24 odd-W (65×64) → RGBA — Path B must run, GPU ≈ CPU ±4
// -------------------------------------------------------------------------
/// G-04: NV24 odd-width (65×64) end-to-end GPU vs CPU reference.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g04_nv24_odd_w_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (321usize, 240usize); // QVGA-scale odd width (Mali rejects sub-minimum textures)
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv24);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"G-04: NV24 odd-W must use Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-04 NV24 odd-W: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"G-04: NV24 odd-W GPU vs CPU max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
// -------------------------------------------------------------------------
// G-05: NV16 odd-both (65×63) → RGBA — highest-value: strict tiled GPUs
// -------------------------------------------------------------------------
/// G-05: NV16 odd-width AND odd-height (65×63) end-to-end GPU vs CPU.
///
/// This is the highest-value cell: it exercises the row-boundary padding
/// constraint that causes incorrect reads on strict tiled GPUs (e.g. V3D)
/// when the last chroma row straddles the 64-byte alignment boundary.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g05_nv16_odd_both_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (321usize, 241usize); // QVGA-scale odd both (Mali rejects sub-minimum textures)
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv16);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"G-05: NV16 odd-both must use Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-05 NV16 odd-both (65×63): GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"G-05: NV16 odd-both GPU vs CPU max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
// -------------------------------------------------------------------------
// G-06: NV24 odd-both (65×63) → RGBA
// -------------------------------------------------------------------------
/// G-06: NV24 odd-width AND odd-height (65×63) end-to-end GPU vs CPU.
///
/// NV24 uses a UV row pitch of `2 × stride`, so odd heights place the last
/// UV row at offset `3H − 2` (0-indexed), making it a different boundary
/// from NV16. This is the regression cell for the NV24 3H height bug.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g06_nv24_odd_both_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (321usize, 241usize); // QVGA-scale odd both (Mali rejects sub-minimum textures)
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv24);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"G-06: NV24 odd-both must use Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-06 NV24 odd-both (65×63): GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"G-06: NV24 odd-both GPU vs CPU max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
// -------------------------------------------------------------------------
// G-09: odd dst with a deliberately NON-64-aligned stride — tolerant guard
// -------------------------------------------------------------------------
/// G-09: an externally-strided odd destination whose row pitch is NOT
/// 64-byte aligned. `Tensor::image` always 64-aligns, so this case can only
/// arise from an explicit `image_with_stride` (or a `from_fd` import). It
/// exercises the reactive odd-destination guard in `GLProcessorST::convert`:
///
/// * On GPUs that accept a non-aligned EGLImage pitch (V3D, Tegra) the
/// convert SUCCEEDS.
/// * On GPUs that reject it (Mali `BadAlloc`, Vivante `BadAccess`) the raw
/// EGL error is re-wrapped as a descriptive `NotSupported` naming the odd
/// dimensions — NOT leaked as a bare `EGL(BadAlloc)`.
///
/// Tolerant by design (platform-dependent), so it is CI-safe: it asserts the
/// outcome is one of those two, never a raw EGL error.
#[test]
#[cfg(target_os = "linux")]
fn g09_odd_dst_unaligned_stride_guarded() {
use crate::opengl_headless::processor::GLProcessorST;
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (321usize, 240usize);
let (src_dma, _src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv12);
// Tight, NON-64-aligned RGBA stride (321*4 = 1284; 1284 % 64 != 0).
let tight_stride = w * 4;
assert_ne!(
tight_stride % 64,
0,
"test premise: stride must be unaligned"
);
let mut gpu_dst = TensorDyn::image_with_stride(
w,
h,
PixelFormat::Rgba,
DType::U8,
tight_stride,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
match gl.convert(&src_dma, &mut gpu_dst, None) {
Ok(()) => eprintln!("G-09: platform accepts non-aligned odd dst (OK)"),
Err(crate::Error::NotSupported(msg)) => {
assert!(
msg.contains("odd dimensions"),
"G-09: NotSupported must name the odd-dimension cause, got: {msg}"
);
eprintln!("G-09: platform rejects non-aligned odd dst, guarded as: {msg}");
}
Err(other) => panic!(
"G-09: odd-dst failure must be wrapped as NotSupported, not leaked raw: {other:?}"
),
}
}
// -------------------------------------------------------------------------
// G-01: NV12 odd-W (QVGA 321×240) → RGBA — routes to Path B (width % 4 != 0)
// -------------------------------------------------------------------------
/// G-01: NV12 with width not a multiple of 4 (321×240) routes to Path B (R8
/// shader), because the NV12 samplerExternalOES EGLImage import requires
/// width % 4 == 0 on some drivers (e.g. V3D). Even/mult-4 NV12 still uses
/// Path A — see `test_nv12_still_uses_path_a` (64×64). Asserts the GPU output
/// agrees with the CPU reference ±4.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g01_nv12_odd_w_path_b_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (321usize, 240usize); // QVGA-scale odd width (Mali rejects sub-minimum textures)
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv12);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
// NV12 width 65 (not mult-4) routes to Path B (R8 shader).
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"G-01: non-mult-4 NV12 must route to Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-01 NV12 odd-W: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"G-01: NV12 odd-W GPU vs CPU max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
// -------------------------------------------------------------------------
// G-02: NV12 even-W odd-H (320×241) → RGBA — Path B must run, GPU ≈ CPU ±4
// -------------------------------------------------------------------------
/// G-02: NV12 even-width odd-height (320×241) end-to-end GPU vs CPU.
///
/// Exercises the luma/chroma row-boundary math for an odd height. With an odd
/// H the chroma plane is `ceil(H/2)` rows, and the last chroma row reads a
/// 64-byte-aligned row whose physical allocation is exactly stride bytes (no
/// half-row shortfall). Path B must be selected because this is a DMA source
/// where width (320) is a multiple of 4 but the height is odd.
///
/// Asserts:
/// (a) `last_nv_convert_path == ShaderR8` — no CPU fallback for DMA source.
/// (b) GPU output matches CPU reference within ±4.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g02_nv12_odd_h_path_b_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
// Even width, odd height — exercises odd-H chroma row boundary.
let (w, h) = (320usize, 241usize);
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv12);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
// Even-width NV12 uses a hardware GPU path: Path A (ExternalSampler,
// samplerExternalOES) on Vivante, or Path B (ShaderR8) elsewhere —
// Path A's YUV-EGLImage sampling is only reliable on Vivante (it samples
// garbage on Mali-G310). Either is correct here; what matters is that it
// stays on the GPU rather than falling back to the CPU.
assert!(
matches!(
gl.last_nv_convert_path,
NvConvertPath::ExternalSampler | NvConvertPath::ShaderR8
),
"G-02: even-W odd-H NV12 should use a GPU path (ExternalSampler/ShaderR8), got {:?}",
gl.last_nv_convert_path
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-02 NV12 odd-H (320×241): GPU vs CPU max_diff={max_diff}");
// Post-WS1 both CPU and the GL NV12 path resolve this untagged odd-H
// source to the same limited-range matrix, so the YUV-matrix delta that
// forced the loose >64 bound has closed; the residual is GPU rounding.
// Warn above a tight ±4, fail on >35 (was 64) so the odd-H stride
// handling this test really guards still trips on a real regression.
if max_diff > 4 {
eprintln!(
"WARNING: G-02 NV12 odd-H GPU vs CPU max_diff={max_diff} > 4 \
(GPU rounding; first bad at {first_fail:?})"
);
}
assert!(
max_diff <= 35,
"G-02: gross NV12 odd-H GPU vs CPU mismatch max_diff={max_diff} (>35); first bad at {first_fail:?}"
);
}
// -------------------------------------------------------------------------
// g_grey_odd_w_vs_cpu: GREY odd-W (coco_grey_odd.jpg 595×438) → RGBA
// -------------------------------------------------------------------------
/// Grey odd-width (595×438) decode + GPU convert → RGBA vs CPU reference.
///
/// Loads `coco_grey_odd.jpg` into a DMA Grey tensor (odd-W 595), converts
/// Grey→RGBA on GPU and on CPU, and asserts they agree within ±4 per pixel.
/// This guards the odd-W Grey IOSurface / EGLImage path that the macOS NV24
/// fix relies on (64-aligned pitch + physical-stride shader addressing).
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g_grey_odd_w_vs_cpu() {
use crate::opengl_headless::processor::GLProcessorST;
use edgefirst_codec::{ImageDecoder, ImageLoad};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let jpeg: &[u8] = &edgefirst_bench::testdata::read("coco_grey_odd.jpg");
let w = 595usize;
let h = 438usize;
// Decode into a DMA-backed Grey tensor (odd width, 64-aligned pitch).
let Some(mut src_grey) = crate::test_support::gpu_buffer_allocated(
Tensor::<u8>::image(
w,
h,
PixelFormat::Grey,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
),
"DMA Grey source",
) else {
return;
};
let src_dma = {
let mut dec = ImageDecoder::new();
src_grey.load_image(&mut dec, jpeg).unwrap();
TensorDyn::from(src_grey)
};
// CPU reference: decode into a Mem Grey tensor, convert Grey→RGBA via CPU.
let src_mem = {
let mut t = Tensor::<u8>::image(
w,
h,
PixelFormat::Grey,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut dec = ImageDecoder::new();
t.load_image(&mut dec, jpeg).unwrap();
TensorDyn::from(t)
};
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
// GPU convert: Grey→RGBA on GL.
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("g_grey_odd_w: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"g_grey_odd_w: Grey odd-W GPU vs CPU max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
// -------------------------------------------------------------------------
// G-07: NV12 odd-W i8 (65×64) → RGB i8
// -------------------------------------------------------------------------
/// G-07: NV12 odd-width (65×64) → RGB i8.
///
/// Exercises the `nv_r8_int8` (XOR 0x80 bias) packing shader for NV12.
/// GPU i8 output is compared to CPU i8 within ±2.
// Odd-WIDTH 3-channel RGB DMA *output* needs `width*3 % 4 == 0`. This is NOT
// the stride-alignment bug fixed for RGBA dsts (g01-g06): it is architectural
// in `convert_to_packed_rgb`, which packs the RGB buffer by reinterpreting it
// as RGBA8 at `width*3/4` pixels. That reinterpretation only tiles when
// `width*3` is a multiple of 4 — width 321 → 963 bytes/row → 240.75 RGBA8
// texels, which does not tile (independent of the 64-aligned stride). Verified
// on-target 2026-06-02: still `NotSupported("Packed RGB requires width*3
// divisible by 4")`. Supporting it needs a different packing path (e.g. an R8
// output texture or fractional-last-texel handling), not a stride change.
// Production model-input is an even/mult-4 dst; the i8 path is covered by
// `test_gpu_nv16_path_b_int8_output`.
#[test]
#[ignore = "odd-width 3-channel RGB DMA output needs width*3 % 4 == 0 (pack-as-RGBA8 architecture in convert_to_packed_rgb, NOT the stride bug); use RGBA or even/mult-4 RGB dst"]
#[cfg(target_os = "linux")]
fn g07_nv12_odd_w_i8_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (321usize, 240usize); // QVGA-scale odd width (Mali rejects sub-minimum textures)
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv12);
// CPU i8 reference.
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgb,
DType::I8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
// GPU i8 output.
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgb,
DType::I8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
// Odd-width single-plane NV12 routes to ShaderR8 (no width gate); the
// driver ExternalSampler requires even/4-aligned width. (This assert only
// runs if the #[ignore] is lifted — kept accurate per current routing.)
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"G-07: odd-W single-plane NV12 must use ShaderR8, got {:?}",
gl.last_nv_convert_path
);
let max_diff = compare_gpu_vs_cpu_i8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-07 NV12 odd-W i8: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 2,
"G-07: NV12 i8 odd-W GPU vs CPU max_diff={max_diff} > 2"
);
}
// -------------------------------------------------------------------------
// G-08: NV16 odd-both i8 (65×63) → RGB i8 — Path B + i8 bias
// -------------------------------------------------------------------------
/// G-08: NV16 odd-both (65×63) → RGB i8.
///
/// Combines the odd-dimension addressing check with the int8 XOR 0x80 bias
/// packing. This is the cell most likely to surface on NPU targets (imx8mp
/// vx / imx95 Neutron) with unusual-resolution input streams.
// Same odd-width 3-channel RGB DMA *output* constraint as g07: architectural
// in `convert_to_packed_rgb` (pack-as-RGBA8 needs width*3 % 4 == 0), NOT the
// stride bug fixed for RGBA dsts. The even-dim i8 path is covered by
// `test_gpu_nv16_path_b_int8_output`.
#[test]
#[ignore = "odd-width 3-channel RGB DMA output needs width*3 % 4 == 0 (pack-as-RGBA8 architecture in convert_to_packed_rgb, NOT the stride bug); use RGBA or even/mult-4 RGB dst"]
#[cfg(target_os = "linux")]
fn g08_nv16_odd_both_i8_vs_cpu() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_dma_available() {
crate::test_support::report_skip(&format!("{} - DMA not available", function!()));
return;
}
let (w, h) = (321usize, 241usize); // QVGA-scale odd both (Mali rejects sub-minimum textures)
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv16);
// CPU i8 reference.
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgb,
DType::I8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
// GPU i8 output.
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgb,
DType::I8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"G-08: NV16 i8 odd-both must use Path B (ShaderR8), got {:?}",
gl.last_nv_convert_path
);
let max_diff = compare_gpu_vs_cpu_i8(&gpu_dst, &cpu_dst, w, h);
eprintln!("G-08 NV16 odd-both i8: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 2,
"G-08: NV16 i8 odd-both GPU vs CPU max_diff={max_diff} > 2"
);
}
// -------------------------------------------------------------------------
// Even-dimension regression guards (ensure no regression on well-tested paths)
// -------------------------------------------------------------------------
/// Even-dim regression: NV16 64×64 → RGBA GPU vs CPU ±4.
///
/// Ensures that adding the odd-dim cells did not perturb even-dimension
/// behaviour on Path B. Uses the same patterned fill and stride-aware
/// comparison as the odd-dim cells.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g_even_nv16_64x64_regression() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv16);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"even NV16 regression: must use Path B"
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("even NV16 64×64 regression: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"even NV16 64×64 regression: max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
/// Even-dim regression: NV24 64×64 → RGBA GPU vs CPU ±4.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn g_even_nv24_64x64_regression() {
use crate::opengl_headless::processor::{GLProcessorST, NvConvertPath};
if !is_gpu_image_buffer_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers",
function!()
));
return;
}
let (w, h) = (64usize, 64usize);
let (src_dma, src_mem) = make_patterned_nv_pair(w, h, PixelFormat::Nv24);
let mut cpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
None,
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
crate::cpu::CPUProcessor::new()
.convert(&src_mem, &mut cpu_dst, None)
.unwrap();
let mut gpu_dst = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
let mut gl = match GLProcessorST::new(None, None) {
Ok(g) => g,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - GL not available: {e}",
function!()
));
return;
}
};
gl.convert(&src_dma, &mut gpu_dst, None).unwrap();
assert_eq!(
gl.last_nv_convert_path,
NvConvertPath::ShaderR8,
"even NV24 regression: must use Path B"
);
let (max_diff, first_fail) = compare_gpu_vs_cpu_u8(&gpu_dst, &cpu_dst, w, h);
eprintln!("even NV24 64×64 regression: GPU vs CPU max_diff={max_diff}");
assert!(
max_diff <= 4,
"even NV24 64×64 regression: max_diff={max_diff} > 4; first bad at {first_fail:?}"
);
}
/// Fill a YUYV tensor at its real row stride: two bytes per pixel, Y in
/// the even byte and alternating Cb/Cr in the odd one.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn fill_yuyv_pattern(t: &TensorDyn, w: usize, h: usize, salt: u8) {
let stride = t.effective_row_stride().unwrap_or(w * 2);
let bound = t.as_u8().unwrap();
let mut m = bound.map().unwrap();
let buf = m.as_mut_slice();
for r in 0..h {
for c in 0..w {
let i = r * stride + c * 2;
buf[i] = ((r * 7 + c * 3) as u8).wrapping_add(salt);
buf[i + 1] = ((r * 5 + c * 11) as u8).wrapping_add(salt);
}
}
}
/// Fill an RGBA tensor at its real row stride.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn fill_rgba_pattern(t: &TensorDyn, w: usize, h: usize, salt: u8) {
let stride = t.effective_row_stride().unwrap_or(w * 4);
let bound = t.as_u8().unwrap();
let mut m = bound.map().unwrap();
let buf = m.as_mut_slice();
for r in 0..h {
for c in 0..w {
let i = r * stride + c * 4;
buf[i] = ((r * 3 + c * 7) as u8).wrapping_add(salt);
buf[i + 1] = ((r * 11 + c * 5) as u8).wrapping_add(salt);
buf[i + 2] = ((r + c) as u8).wrapping_add(salt);
buf[i + 3] = 255;
}
}
}
/// Worst absolute channel difference between two packed outputs.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn worst_channel_diff(expected: &[u8], actual: &[u8]) -> u8 {
assert_eq!(expected.len(), actual.len(), "Buffer size mismatch");
expected
.iter()
.zip(actual)
.map(|(&e, &a)| (e as i16 - a as i16).unsigned_abs() as u8)
.max()
.unwrap_or(0)
}
/// Bytes that differ between two `w x h` packed outputs on the last row
/// or the last column.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn edge_mismatches(
expected: &[u8],
actual: &[u8],
w: usize,
h: usize,
channels: usize,
) -> usize {
assert_eq!(expected.len(), actual.len(), "Buffer size mismatch");
// A degenerate output has no last row or column; the index math
// below would underflow on it.
if w == 0 || h == 0 {
return 0;
}
let row = w * channels;
let last_row = (h - 1) * row..h * row;
let last_col = (0..h - 1).flat_map(|r| {
let start = r * row + (w - 1) * channels;
start..start + channels
});
last_row
.chain(last_col)
.filter(|&i| expected[i] != actual[i])
.count()
}
/// A *destination* pool tensor narrowed by `configure_image` renders into
/// the region its logical dimensions name, not a stretched copy of the
/// whole texture.
///
/// The mirror of the narrowed-source cases below, and the one the import
/// seam makes non-obvious on Windows: a texture import has no sub-extent
/// attribute there, so the destination's own image is the whole texture
/// and the band is viewport state. A fresh destination of the narrowed
/// size is the oracle -- the same convert with no recycling in it.
#[test]
fn recycled_narrowed_destination_matches_a_fresh_one() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let src = crate::load_image_test_helper(
&edgefirst_bench::testdata::read("giraffe.jpg"),
Some(PixelFormat::Rgba),
None,
)
.expect("decode the source fixture");
let mut gl = GLProcessorThreaded::new(None).unwrap();
let rgba_dst = |w: usize, h: usize| {
TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
};
let Some(mut pool) = crate::test_support::gpu_buffer_allocated(
rgba_dst(256, 192),
"RGBA texture destination",
) else {
return;
};
// Seed the whole texture, so anything the narrowed convert fails to
// cover reads as this rather than as the converted image.
{
let mut m = pool.as_u8().unwrap().map().unwrap();
m.as_mut_slice().fill(0x5A);
}
for (w, h) in [(160usize, 120usize), (64, 48)] {
pool.configure_image(w, h, PixelFormat::Rgba).unwrap();
gl.convert(&src, &mut pool, None).unwrap();
let mut fresh = rgba_dst(w, h).unwrap();
gl.convert(&src, &mut fresh, None).unwrap();
let (got, want) = (flat_bytes(&pool), flat_bytes(&fresh));
assert_eq!(got.len(), want.len(), "{w}x{h}: output size mismatch");
let worst = got
.iter()
.zip(&want)
.map(|(a, b)| (*a as i16 - *b as i16).unsigned_abs())
.max()
.unwrap_or(0);
// The two converts resample through differently sized textures,
// so the last bit can round differently; a mis-mapped viewport is
// off by tens or hundreds.
assert!(
worst <= 1,
"{w}x{h}: narrowed destination differs from a fresh one by up to {worst}"
);
}
}
/// Compact a destination's rows into a tight buffer.
///
/// A Windows `TensorMemory::DmaBuf` destination is a D3D11 texture whose
/// staging rows are padded to the driver's pitch (128 bytes on this
/// NVIDIA adapter), so reading the head of the mapping as a tight image
/// reads padding as pixels and shifts every row after the first.
/// `copy_to_flat` is the tensor's own compaction and degenerates to one
/// memcpy on a tight backing.
fn flat_bytes(img: &TensorDyn) -> Vec<u8> {
let t = img.as_u8().expect("u8 image");
let mut out = vec![0u8; t.shape().iter().product::<usize>()];
t.copy_to_flat(&mut out).expect("compact the padded rows");
out
}
/// The 128x128 Grey pool the narrowed-source tests recycle, seeded over
/// its whole extent so anything sampled from outside a later narrowed
/// image is unmistakable.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn seeded_grey_pool() -> TensorDyn {
let pool = TensorDyn::image(
128,
128,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_grey_pattern(&pool, 128, 128, 200);
pool
}
/// Convert a `sw x sh` Grey image to `dw x dh` RGBA twice: recycled
/// through `pool` (narrowed by `configure_image`) and from a fresh buffer
/// of exactly its size. Returns `(fresh, recycled)` output bytes.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn convert_narrowed_and_fresh_grey(
gl: &mut GLProcessorThreaded,
pool: &mut TensorDyn,
(sw, sh): (usize, usize),
(dw, dh): (usize, usize),
salt: u8,
) -> (Vec<u8>, Vec<u8>) {
convert_narrowed_and_fresh_grey_as(
gl,
pool,
(sw, sh),
(dw, dh),
salt,
crate::Rotation::None,
Crop::no_crop(),
)
}
/// [`convert_narrowed_and_fresh_grey`] with an explicit rotation and crop,
/// so a case can put the sampling rectangle's far edge on the logical edge
/// by a route other than a whole-source stretch.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn convert_narrowed_and_fresh_grey_as(
gl: &mut GLProcessorThreaded,
pool: &mut TensorDyn,
(sw, sh): (usize, usize),
(dw, dh): (usize, usize),
salt: u8,
rotation: crate::Rotation,
crop: Crop,
) -> (Vec<u8>, Vec<u8>) {
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(
s,
d,
Some(crate::ConvertOptions::new().rotation(rotation).crop(crop)),
)
.unwrap();
};
let rgba_dst = || {
TensorDyn::image(
dw,
dh,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap()
};
pool.configure_image(sw, sh, PixelFormat::Grey).unwrap();
fill_grey_pattern(pool, sw, sh, salt);
let mut recycled = rgba_dst();
convert(gl, pool, &mut recycled);
let recycled_bytes = flat_bytes(&recycled);
let fresh = TensorDyn::image(
sw,
sh,
PixelFormat::Grey,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_grey_pattern(&fresh, sw, sh, salt);
let mut oracle = rgba_dst();
convert(gl, &fresh, &mut oracle);
let oracle_bytes = flat_bytes(&oracle);
assert_eq!(
recycled_bytes.len(),
oracle_bytes.len(),
"{sw}x{sh} -> {dw}x{dh}: output size mismatch"
);
(oracle_bytes, recycled_bytes)
}
/// A pool buffer narrowed by `configure_image` imports its whole texture on
/// platforms whose import has no sub-extent attribute (Windows), so the
/// engine maps the source rectangle onto that extent. Resizing is what
/// makes a mis-mapping obvious — every sample moves, not just the edge —
/// so each case must equal a fresh-buffer convert of the same geometry.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_narrowed_source_resized_matches_fresh() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let mut pool = seeded_grey_pool();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// (src w, src h, dst w, dst h).
let cases: [(usize, usize, usize, usize); 4] = [
(128, 96, 128, 96),
(128, 96, 64, 48),
(128, 96, 192, 144),
(96, 128, 192, 256),
];
for (i, &(sw, sh, dw, dh)) in cases.iter().enumerate() {
let (oracle_bytes, recycled_bytes) = convert_narrowed_and_fresh_grey(
&mut gl,
&mut pool,
(sw, sh),
(dw, dh),
i as u8 * 10,
);
// Tolerance 1: the two converts resample through differently sized
// textures, and a software rasteriser rounds the last bit
// differently. A mis-mapped source is off by tens or hundreds.
let worst = worst_channel_diff(&oracle_bytes, &recycled_bytes);
assert!(
worst <= 1,
"case {i} ({sw}x{sh} -> {dw}x{dh}): narrowed source differs by up to {worst}"
);
}
}
/// An upscale of a narrowed pool source samples within half a texel of
/// the logical edge on its last row or column. A texture that is exactly
/// the logical image clamps to its edge texel there; one that merely
/// contains it holds the pool's previous content beyond that edge, which
/// the `LINEAR` kernel would blend in. The shaders clamp every sample to
/// the logical image's half-texel-inset rectangle (`src_extent`), so both
/// edges must equal the fresh-buffer oracle exactly.
///
/// The narrowed axis is half the pool in every case: the scaled texture
/// coordinates are then exact in float, both converts filter the same
/// texel positions, and the edge clamp is the only thing left to differ.
/// The interior keeps the sibling test's tolerance of 1.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_narrowed_source_upscaled_edges_match_fresh() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let mut pool = seeded_grey_pool();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// (src w, src h, dst w, dst h): height narrowed, width narrowed, both,
// and a non-integer upscale.
let cases: [(usize, usize, usize, usize); 4] = [
(128, 64, 256, 128),
(64, 128, 128, 256),
(64, 64, 128, 128),
(128, 64, 192, 96),
];
for (i, &(sw, sh, dw, dh)) in cases.iter().enumerate() {
let (oracle_bytes, recycled_bytes) = convert_narrowed_and_fresh_grey(
&mut gl,
&mut pool,
(sw, sh),
(dw, dh),
i as u8 * 10,
);
let edges = edge_mismatches(&oracle_bytes, &recycled_bytes, dw, dh, 4);
assert_eq!(
edges, 0,
"case {i} ({sw}x{sh} -> {dw}x{dh}): {edges} bytes differ from a fresh buffer \
on the last row or column of the upscaled narrowed source"
);
let worst = worst_channel_diff(&oracle_bytes, &recycled_bytes);
assert!(
worst <= 1,
"case {i} ({sw}x{sh} -> {dw}x{dh}): narrowed source differs by up to {worst}"
);
}
}
/// The clamp has to hold when the sampling rectangle reaches the logical
/// edge by a route other than a whole-source stretch.
///
/// Case 0 crops the source to its bottom-right quadrant, whose far edge is
/// exactly the logical edge, and upscales it 4x: the crop rect is scaled
/// onto the import by the same `logical / extent` factor, so its far edge
/// still lands half a texel short of the stale row. Case 1 rotates 90
/// degrees, which permutes which quad corner carries which texcoord — the
/// clamp is per axis in texture space and must be unaffected.
///
/// Both narrow an axis to half the pool, so the scaled coordinates are
/// exact and the edges must match the fresh-buffer oracle byte for byte.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_narrowed_source_cropped_and_rotated_edges_match_fresh() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let mut pool = seeded_grey_pool();
let mut gl = GLProcessorThreaded::new(None).unwrap();
// (src w, src h, dst w, dst h, rotation, crop).
let cases: [(usize, usize, usize, usize, crate::Rotation, Crop); 2] = [
(
128,
64,
256,
128,
crate::Rotation::None,
Crop::no_crop().with_source(Some(crate::Region::new(64, 32, 64, 32))),
),
(
64,
128,
256,
128,
crate::Rotation::Clockwise90,
Crop::no_crop(),
),
];
for (i, &(sw, sh, dw, dh, rotation, crop)) in cases.iter().enumerate() {
let (oracle_bytes, recycled_bytes) = convert_narrowed_and_fresh_grey_as(
&mut gl,
&mut pool,
(sw, sh),
(dw, dh),
i as u8 * 10,
rotation,
crop,
);
let edges = edge_mismatches(&oracle_bytes, &recycled_bytes, dw, dh, 4);
assert_eq!(
edges, 0,
"case {i} ({sw}x{sh} -> {dw}x{dh}, {rotation:?}, crop {:?}): {edges} bytes \
differ from a fresh buffer on the last row or column",
crop.source
);
let worst = worst_channel_diff(&oracle_bytes, &recycled_bytes);
assert!(
worst <= 1,
"case {i} ({sw}x{sh} -> {dw}x{dh}, {rotation:?}): narrowed source differs \
by up to {worst}"
);
}
}
/// The YUYV source program rebuilds texel coordinates from a `src_size`
/// uniform, so a narrowed pool buffer needs the texture's grid there, not
/// the logical image's: otherwise `floor(tc * src_size)` lands on the wrong
/// column and the chroma pair comes from the wrong pixel.
///
/// The last two frames upscale, which is where the u8 blit paths blend the
/// texel past a narrowed edge. This shader cannot: `floor` snaps every
/// sample to a texel centre, so it reads one texel rather than filtering
/// two, and its `src_extent` clamp only bounds that index. Both edges
/// therefore equal the fresh-buffer oracle exactly, with or without the
/// clamp — the frames pin that down rather than reproducing a bleed.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_narrowed_yuyv_source_matches_fresh() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
let mut pool = TensorDyn::image(
128,
128,
PixelFormat::Yuyv,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_yuyv_pattern(&pool, 128, 128, 200);
let mut gl = GLProcessorThreaded::new(None).unwrap();
let convert = |gl: &mut GLProcessorThreaded, s: &TensorDyn, d: &mut TensorDyn| {
gl.convert(s, d, None).unwrap();
};
let rgba_dst = |w: usize, h: usize| {
TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap()
};
// (src w, src h, dst w, dst h, salt). Even widths only: YUYV pairs two
// columns per chroma sample.
let frames: [(usize, usize, usize, usize, u8); 5] = [
(128, 96, 128, 96, 0),
(96, 128, 96, 128, 40),
(64, 100, 64, 100, 80),
(128, 64, 256, 128, 120),
(64, 128, 128, 256, 160),
];
for (i, &(w, h, dw, dh, salt)) in frames.iter().enumerate() {
pool.configure_image(w, h, PixelFormat::Yuyv).unwrap();
fill_yuyv_pattern(&pool, w, h, salt);
let mut recycled = rgba_dst(dw, dh);
convert(&mut gl, &pool, &mut recycled);
let recycled_bytes = flat_bytes(&recycled);
let fresh = TensorDyn::image(
w,
h,
PixelFormat::Yuyv,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_yuyv_pattern(&fresh, w, h, salt);
let mut oracle = rgba_dst(dw, dh);
convert(&mut gl, &fresh, &mut oracle);
let oracle_bytes = flat_bytes(&oracle);
assert_eq!(
recycled_bytes.len(),
oracle_bytes.len(),
"frame {i} ({w}x{h} -> {dw}x{dh}): output size mismatch"
);
let edges = edge_mismatches(&oracle_bytes, &recycled_bytes, dw, dh, 4);
assert_eq!(
edges, 0,
"frame {i} ({w}x{h} -> {dw}x{dh}): {edges} bytes differ from a fresh buffer \
on the last row or column"
);
assert_pixels_match(&oracle_bytes, &recycled_bytes, 0);
}
}
/// The float paths feed their source through the same zero-copy import, so
/// a narrowed pool buffer must be mapped onto its import extent there too:
/// `feed_float_src`'s import arm, whose uv comes from `float_crop_uniforms`
/// over the logical dims. Without that mapping the narrowed source renders
/// stretched and this differs from the fresh-buffer oracle by ~0.99 of
/// full scale.
///
/// Each frame drives both float destination kinds: an F32 `Rgb` PBO (the
/// readback float path) and a zero-copy F16 `PlanarRgb` texture, which
/// the packed float path renders into directly. They share the uv
/// builder, so the mapping has to hold on both. The two halves ask for
/// different render capabilities -- F32 for the PBO, F16 for the
/// zero-copy texture -- because those are what their respective
/// `float_dispatch` arms are gated on. The last frame upscales,
/// which reaches the sample clamp (`src_extent`) on the narrowed axis;
/// that axis is half the pool so the scaled coordinates are exact and the
/// clamp is the only difference from the fresh buffer.
#[test]
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn dma_recycle_narrowed_source_into_float_dst_matches_fresh() {
if !is_gpu_image_buffer_available() || !is_opengl_available() {
crate::test_support::report_skip(&format!(
"{} - no zero-copy GPU buffers or OpenGL",
function!()
));
return;
}
// A lane that has declared it has a working GL stack must not lose
// this test's zero-copy coverage to a driver decline, so the decline
// below is a failure there and a skip elsewhere. The macOS coverage
// lane sets the flag for BOTH passes but deliberately hobbles pass 1
// (unsigned binaries, the ANGLE dlopen gate closed), so pass 1 is
// excluded the same way `gl_backend_available_canary` and the
// sibling test below exclude it.
let require_gl = std::env::var("HAL_TEST_REQUIRE_GL").is_ok_and(|v| v == "1");
#[cfg(target_os = "macos")]
if require_gl && std::env::var_os("HAL_TEST_ALLOW_DLOPEN_ANGLE").is_none() {
crate::test_support::report_skip(&format!(
"{} - ANGLE dlopen gate closed (coverage pass 1)",
function!()
));
return;
}
// `ComputeBackend::OpenGl` selects the GL backend but does NOT disable
// the CPU fallback -- it leaves `forced_backend` at `None`, so a
// declined float path is served by the CPU with only a debug log, and
// both sides of every comparison below would then be the same CPU
// answer. `convert_fallback_count()` is asserted across each convert
// for that reason.
let mut proc = match crate::ImageProcessor::with_config(crate::ImageProcessorConfig {
backend: crate::ComputeBackend::OpenGl,
..Default::default()
}) {
Ok(p) => p,
Err(e) => {
crate::test_support::report_skip(&format!(
"{} - OpenGL backend unavailable: {e}",
function!()
));
return;
}
};
if !proc.supported_render_dtypes().f32 {
crate::test_support::report_skip(&format!(
"{} - F32 render not supported",
function!()
));
return;
}
// The zero-copy half below needs the F16 planar render specifically,
// which is a separate capability from the F32 the PBO half needs: a
// GPU can report one without the other. Asked once rather than per
// frame, since it cannot change between frames.
let zero_copy_float = proc.supported_render_dtypes().f16;
if !zero_copy_float {
crate::test_support::report_skip(&format!(
"(zero-copy float dst): {} - F16 render not supported",
function!()
));
}
let mut pool = TensorDyn::image(
128,
128,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_rgba_pattern(&pool, 128, 128, 200);
// (src w, src h, dst w, dst h, salt).
let frames: [(usize, usize, usize, usize, u8); 3] = [
(128, 96, 128, 96, 0),
(96, 128, 96, 128, 60),
(128, 64, 256, 128, 120),
];
for (i, &(w, h, dw, dh, salt)) in frames.iter().enumerate() {
pool.configure_image(w, h, PixelFormat::Rgba).unwrap();
fill_rgba_pattern(&pool, w, h, salt);
// An F32 destination through the PBO float render path, allocated
// on the processor's GL context: `create_image` picks a zero-copy
// texture first where the platform has one, and a PBO tensor can
// only come from the GL worker.
let float_dst = |p: &crate::ImageProcessor| {
p.opengl
.as_ref()
.expect("OpenGl backend")
.create_pbo_image_dtype(dw, dh, PixelFormat::Rgb, DType::F32)
};
let mut recycled = float_dst(&proc).expect("allocate the F32 PBO destination");
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&pool, &mut recycled, None).unwrap();
assert_eq!(
proc.convert_fallback_count(),
fallbacks_before,
"frame {i}: the GL float path declined and the convert was \
served by the CPU; the oracle below would then be the same \
CPU answer and the comparison would prove nothing"
);
let recycled_bytes = recycled.as_f32().unwrap().map().unwrap().to_vec();
let fresh = TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.unwrap();
fill_rgba_pattern(&fresh, w, h, salt);
let mut oracle = float_dst(&proc).unwrap();
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&fresh, &mut oracle, None).unwrap();
assert_eq!(
proc.convert_fallback_count(),
fallbacks_before,
"frame {i}: the oracle convert fell back to the CPU"
);
let oracle_bytes = oracle.as_f32().unwrap().map().unwrap().to_vec();
assert_eq!(
recycled_bytes.len(),
oracle_bytes.len(),
"frame {i} ({w}x{h} -> {dw}x{dh}): output size mismatch"
);
let worst = recycled_bytes
.iter()
.zip(oracle_bytes.iter())
.map(|(a, b)| (a - b).abs())
.fold(0.0f32, f32::max);
assert!(
worst == 0.0,
"frame {i} ({w}x{h} -> {dw}x{dh}): narrowed float source differs from a \
fresh buffer by up to {worst}"
);
// ── The same source into a zero-copy float destination: an F16
// PlanarRgb texture, rendered straight into by the packed float
// path rather than read back through a PBO. The extent mapping
// lives in the shared uv builder, so both destinations must show
// it; this one is the path that exists only where the platform
// renders float zero-copy.
//
// F16 rather than F32, because `(Rgba, PlanarRgb, F16, DmaBuf)` is
// the one zero-copy float tuple BOTH capability sets serve --
// `FloatRenderPath::ZeroCopyF16Nchw`. The F32 zero-copy
// destinations are gated on `ZeroCopyFloatSet::All`, which only
// the Windows leaf reports; Linux, Android and ANGLE/macOS report
// `PlanarF16`, so an F32 PlanarRgb DMA destination classifies as
// `FloatRenderPath::None` there, the u8 route rejects the dtype
// and the CPU serves the convert. `float_dispatch.rs`'s
// `the_planar_set_leaves_the_windows_only_shaders_unreachable`
// pins that decision. Allocating such a destination still succeeds
// on Mali and V3D, so a successful allocation cannot stand in for
// the routing question -- which is why this half asks the
// capability rather than inferring it from the allocator.
if !zero_copy_float {
continue;
}
let planar_dst = || {
TensorDyn::image(
dw,
dh,
PixelFormat::PlanarRgb,
DType::F16,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
};
let Some(mut zc_recycled) = crate::test_support::gpu_buffer_allocated(
planar_dst(),
"F16 PlanarRgb zero-copy destination",
) else {
continue;
};
let Some(mut zc_oracle) = crate::test_support::gpu_buffer_allocated(
planar_dst(),
"F16 PlanarRgb zero-copy oracle",
) else {
continue;
};
if zc_recycled.memory() != TensorMemory::DmaBuf {
crate::test_support::report_skip(&format!(
"(zero-copy float dst): {} - F16 PlanarRgb dst is not zero-copy",
function!()
));
continue;
}
// Both sides are read through `copy_to_flat`: a Windows texture
// destination spaces its rows at a padded pitch, whose bytes are
// not written by the render.
let flat_f16 = |t: &TensorDyn| -> Vec<u8> {
let typed = t.as_typed::<half::f16>().expect("F16 image");
let mut out = vec![0u8; typed.shape().iter().product::<usize>() * 2];
typed.copy_to_flat(&mut out).expect("compact padded rows");
out
};
let fallbacks_before = proc.convert_fallback_count();
proc.convert(&pool, &mut zc_recycled, None).unwrap();
proc.convert(&fresh, &mut zc_oracle, None).unwrap();
// A driver that refuses the zero-copy float destination has
// nothing inside GL to lower to -- there is no mapped-texture
// readback for a float DMA destination -- so the CPU serves the
// convert and both sides become the same CPU answer, which would
// make the comparison below prove nothing. That is a property of
// the host's driver and not of this code (this desktop's NVIDIA
// EGL fails its DMA-BUF roundtrip check and drops to PBO
// transfers), so it is reported as a skip -- except under
// `HAL_TEST_REQUIRE_GL=1`, where a lane that has asserted it has a
// working GL stack must not quietly lose this coverage. The boards
// run with it set.
if proc.convert_fallback_count() != fallbacks_before {
assert!(
!require_gl,
"HAL_TEST_REQUIRE_GL=1 but frame {i}'s zero-copy float destination \
convert fell back to the CPU"
);
crate::test_support::report_skip(&format!(
"(zero-copy float dst): {} - the GL float path declined and the \
CPU served the convert",
function!()
));
continue;
}
assert_eq!(
flat_f16(&zc_recycled),
flat_f16(&zc_oracle),
"frame {i} ({w}x{h} -> {dw}x{dh}): narrowed source into a zero-copy F16 \
PlanarRgb destination differs from a fresh buffer"
);
}
}
/// An NV12 DMA/IOSurface/D3D11 source at an UNALIGNED plane offset must
/// still convert through GL, on every backing that can hold one.
///
/// This is `tests/offset_source_view_alignment.rs`'s NV case as a LIB test,
/// and it is here rather than only there because the integration binaries
/// reach almost no CI lane: the Linux runners have no DMA heap, and the
/// i.MX 8M Plus hardware lane runs only the `edgefirst_image-*` lib-test
/// binary filtered on `opengl`/`g2d`. Three lanes do reach the code below,
/// each through a different one of the two NV import-failure arms:
///
/// * **macOS / Windows (ANGLE).** `import_buffer_nv_r8` refuses an offset
/// source outright (`refuse_offset_source`), so the ShaderR8 arm's
/// failure path runs.
/// * **i.MX 8M Plus (Vivante).** `select_nv_path` takes the external
/// sampler for single-plane NV12 there, and Vivante's EGL refuses the
/// unaligned offset, so the OTHER failure arm runs.
/// * **i.MX 95 (Mali).** The engine's own decline fires
/// (`rejects_unaligned_import_offset`), then the ShaderR8 arm's failure path.
///
/// V3D imports an unaligned offset correctly and takes neither arm, which
/// is why the routing assertion below is an implication rather than a flat
/// "an upload happened": what every backing must satisfy is that a
/// DECLINED zero-copy feed became an upload and not a CPU convert
/// (issue #166). `GLProcessorThreaded` is driven directly, so a CPU
/// fallback cannot pass this test at all.
#[test]
fn nv12_source_at_a_plane_offset_converts_through_gl_on_every_zero_copy_backing() {
// QVGA rather than a tiny frame: Mali has a minimum texture size that
// 64x64 tests have tripped over, and a 4-aligned width is also what
// Vivante's sampler path requires -- without it that lane would take
// the shader arm and leave the sampler arm uncovered.
const W: usize = 320;
const H: usize = 240;
const TOLERANCE: u8 = 8;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
#[cfg(target_os = "macos")]
if std::env::var("HAL_TEST_REQUIRE_GL").is_ok_and(|v| v == "1")
&& std::env::var_os("HAL_TEST_ALLOW_DLOPEN_ANGLE").is_none()
{
crate::test_support::report_skip(&format!(
"{} - ANGLE dlopen gate closed (coverage pass 1)",
function!()
));
return;
}
// Two rows taller than the logical frame, so a window starting a row
// in is still fully backed.
let Some(mut src) = crate::test_support::gpu_buffer_allocated(
TensorDyn::image(
W,
H + 2,
PixelFormat::Nv12,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
),
"zero-copy NV12 source",
) else {
return;
};
let pitch = src.effective_row_stride().unwrap_or(W);
// The same pattern `tests/offset_source_view_alignment.rs` uses, and
// for the same reasons: period 31 is coprime with the pitch and with
// 64, so a window read at the wrong offset cannot coincide with the
// right one, and the 112..=142 band keeps both the luma and the chroma
// it also feeds clear of RGB clamping, where two different reads could
// agree by saturation. Written BEFORE the re-tag, while the map still
// spans the whole allocation.
{
let mut m = src
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map the NV12 allocation");
for (i, b) in m.as_mut_slice().iter_mut().enumerate() {
*b = 112 + (i % 31) as u8;
}
}
src.set_logical_shape(&[H * 3 / 2, W])
.expect("narrow to one frame's geometry");
assert_eq!(src.height(), Some(H), "precondition: one frame is {H} rows");
assert_eq!(
src.effective_row_stride(),
Some(pitch),
"precondition: the re-tag kept the surface pitch"
);
// A row in, plus 32 bytes: rounding the row up to 64 first makes the
// result 32 (mod 64) whatever the driver's pitch is, so the offset is
// unaligned on every host rather than only on the ones whose pitch is
// already padded.
let offset = pitch.next_multiple_of(64) + 32;
src.set_plane_offset(offset);
assert_eq!(
src.plane_offset(),
Some(offset),
"precondition: the offset stuck"
);
assert_ne!(offset % 64, 0, "precondition: {offset} is unaligned");
// Full-range BT.601 so both converters resolve the same matrix by the
// tag rather than by the untagged-SD heuristic.
src.set_colorimetry(Some(
edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full),
));
let rgba_dst = || {
TensorDyn::image(
W,
H,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("RGBA destination")
};
let read = |t: &TensorDyn| {
t.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map destination")
.as_slice()
.to_vec()
};
let mut reference = rgba_dst();
crate::CPUProcessor::new()
.convert(&src, &mut reference, None)
.expect("CPU reference convert of the offset NV12 frame");
let want = read(&reference);
// A flat reference would make any wrong read agree; the pattern must
// survive into the converted pixels.
assert!(
want.chunks(4).any(|p| p != &want[..4]),
"precondition: the CPU reference is flat, so agreement would prove nothing"
);
let mut gl = GLProcessorThreaded::new(None).expect("GL processor");
let before = gl.convert_stats().expect("convert stats before");
let mut dst = rgba_dst();
gl.convert(&src, &mut dst, None).expect(
"GL refused an NV12 source at an unaligned plane offset; a declined \
zero-copy NV import must reach the R8 upload (issue #166)",
);
let after = gl.convert_stats().expect("convert stats after");
let got = read(&dst);
let bad = got
.iter()
.zip(&want)
.filter(|(g, w)| g.abs_diff(**w) > TOLERANCE)
.count();
assert_eq!(
bad,
0,
"{bad} bytes differ from the CPU reference over the same tensor; \
first got={:?} want={:?} (offset {offset}, pitch {pitch})",
&got[..4],
&want[..4]
);
// The routing contract: a zero-copy feed that was DECLINED must have
// become an upload. Vacuous where the import succeeded (V3D), which is
// why it is an implication and not an unconditional count.
let declines = after.zero_copy_declines - before.zero_copy_declines;
let uploads = after.src_uploads - before.src_uploads;
let imports = after.src_imports - before.src_imports;
// Say which route this host took, at `info` so it reaches the log even
// under libtest's output capture (which swallows `eprintln!` from a
// passing test). The whole point of this test is per-platform routing,
// and without this a green lane does not say WHICH arm it covered.
log::info!(
"{}: offset {offset} pitch {pitch} -> declines={declines} uploads={uploads} \
imports={imports}",
function!()
);
if declines > 0 {
assert!(
uploads > 0,
"the NV import was declined ({declines}) but no upload was recorded \
(uploads={uploads}, imports={imports}) -- the convert fell to a path \
issue #166 exists to prevent"
);
}
assert!(
uploads + imports > 0,
"the convert recorded neither an upload nor an import \
(declines={declines}) -- it was not fed by the GL engine at all"
);
}
/// A fresh `view()` destination at an UNALIGNED byte offset must keep the
/// zero-copy destination import.
///
/// A destination `view()` imports its PARENT and places the tile with
/// `glViewport`, so its import bases at 0 however far into the buffer its
/// own bytes start (`DmaImportAttrs::from_tensor` with `for_dst = true`,
/// `BufferImportKey::from_tensor`). Any rule about the base offset --
/// `dst_import_places` today -- must therefore be asked of
/// `view_collapsed_dst_base`, not of `plane_offset()`; asking the latter
/// fires on every tile view whose byte offset is unaligned -- an RGBA `x0`
/// of 8 is 32 bytes -- and costs the zero-copy path for an import that
/// bases at 0 and would have succeeded.
///
/// `convert_fallback_count` cannot see this: the over-fire lowers WITHIN
/// GL, to the mapped-texture readback, and never reaches the CPU backend.
/// What distinguishes the two is whether a destination import happened at
/// all, so this reads the `dst` import cache.
///
/// Self-calibrating, via a CONTROL convert into a whole zero-copy
/// destination. A host that imports nothing there cannot run the subject at
/// all -- the engine declines a `view()` destination outright unless the
/// transfer backend is zero-copy -- so it skips, which is what a desktop
/// whose EGL cannot import a DMA-BUF does. Where the control imports, the
/// unaligned view must import too, and that assertion is never vacuous.
#[test]
fn a_fresh_unaligned_view_destination_keeps_the_zero_copy_import() {
const W: usize = 320;
const H: usize = 240;
const SIDE: usize = 64;
const BPP: usize = 4;
// x0 = 8 -> 32 bytes, never 64-aligned whatever the pitch.
const X0: usize = 8;
const Y0: usize = 8;
const BLANK: u8 = 0x55;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
#[cfg(target_os = "macos")]
if std::env::var("HAL_TEST_REQUIRE_GL").is_ok_and(|v| v == "1")
&& std::env::var_os("HAL_TEST_ALLOW_DLOPEN_ANGLE").is_none()
{
crate::test_support::report_skip(&format!(
"{} - ANGLE dlopen gate closed (coverage pass 1)",
function!()
));
return;
}
let dma_rgba = |w: usize, h: usize| {
TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
};
let Some(canvas) =
crate::test_support::gpu_buffer_allocated(dma_rgba(W, H), "zero-copy RGBA canvas")
else {
return;
};
let pitch = canvas.effective_row_stride().unwrap_or(W * BPP);
let offset = Y0 * pitch + X0 * BPP;
assert_ne!(
offset % 64,
0,
"precondition: ({X0},{Y0}) at pitch {pitch} is byte offset {offset}, \
which must be unaligned for this test to mean anything"
);
let want = |x: usize, y: usize| -> [u8; BPP] {
[((y * 3) % 256) as u8, ((x * 5) % 256) as u8, 255, 255]
};
let src = TensorDyn::image(
SIDE,
SIDE,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("source");
{
let mut m = src
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map source");
let s = m.as_mut_slice();
for y in 0..SIDE {
for x in 0..SIDE {
s[(y * SIDE + x) * BPP..][..BPP].copy_from_slice(&want(X0 + x, Y0 + y));
}
}
}
let mut gl = GLProcessorThreaded::new(None).expect("GL processor");
let imports = |g: &GLProcessorThreaded| {
let c = g.egl_cache_stats().expect("cache stats").dst;
c.misses + c.hits
};
// CONTROL: a WHOLE zero-copy destination, no view and no offset. This
// is what says whether this host imports destinations at all.
let mut whole = dma_rgba(SIDE, SIDE).expect("control destination");
let before_control = imports(&gl);
gl.convert(&src, &mut whole, None)
.expect("control convert into a whole zero-copy destination");
let control = imports(&gl) - before_control;
// A view destination is only supported at all on a zero-copy transfer
// backend (`GLProcessorST::convert` declines it outright otherwise), and
// the control is exactly that question, so a host that imported nothing
// cannot run the subject. This desktop is one: its EGL cannot import a
// DMA-BUF, so the backend falls back to PBO.
if control == 0 {
crate::test_support::report_skip(&format!(
"{} - no zero-copy destination import on this host, so a \
view() destination is declined by the engine and there is nothing \
to measure",
function!()
));
log::info!(
"{}: pitch {pitch} offset {offset} -> control_dst_imports=0, skipped",
function!()
);
return;
}
// SUBJECT: a fresh view at the unaligned byte offset.
{
let mut m = canvas
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map canvas");
m.as_mut_slice().fill(BLANK);
}
let mut tile = canvas
.view(edgefirst_tensor::Region::new(X0, Y0, SIDE, SIDE))
.expect("fresh destination view");
assert_eq!(
tile.plane_offset(),
Some(offset),
"precondition: the view carries the unaligned byte offset"
);
assert!(
tile.view_origin().is_some(),
"precondition: a fresh view has a view_origin, which is what bases its \
import at 0"
);
let before_subject = imports(&gl);
gl.convert(&src, &mut tile, None)
.expect("convert into a fresh view destination at an unaligned offset");
let subject = imports(&gl) - before_subject;
log::info!(
"{}: pitch {pitch} offset {offset} -> control_dst_imports={control} \
subject_dst_imports={subject}",
function!()
);
// The pixels first: a lowered path is slow, a misplaced tile is wrong.
let out = canvas
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map canvas")
.as_slice()
.to_vec();
let px = |x: usize, y: usize| &out[y * pitch + x * BPP..][..BPP];
assert_eq!(
px(0, 0),
&[BLANK; BPP],
"the tile landed at the canvas ORIGIN, so the view's offset was lost"
);
for y in Y0..Y0 + SIDE {
for x in X0..X0 + SIDE {
assert_eq!(px(x, y), &want(x, y), "tile pixel ({x}, {y})");
}
}
// Then the routing. `control > 0` is guaranteed by the guard above, so
// this is never vacuous where it runs.
assert!(
subject > 0,
"this host imports whole zero-copy destinations (control={control}) but \
performed no destination import for a fresh view at unaligned byte \
offset {offset} (subject={subject}) -- the view's import bases at 0, so \
no offset rule should have applied to it"
);
}
// ── The PBO transfer gates ──────────────────────────────────────────
//
// Four tests over the three `PIXEL_UNPACK_BUFFER`-bound uploads and the
// PBO readback. They share three properties worth stating once.
//
// **They allocate through `GLProcessorThreaded::create_pbo_image*`**,
// which mints a GL buffer directly, rather than through
// `ImageProcessor::create_image`, which returns a PBO only where the
// zero-copy DMA-BUF import does not work. So they run on every GL host,
// including the boards, with no environment variable to remember.
//
// **`GLProcessorThreaded` has no CPU fallback.** `ImageProcessor` with
// `ComputeBackend::OpenGl` does -- that variant leaves `forced_backend`
// at `None` and a GL decline logs at debug and silently falls to the CPU
// path, whose float widen (`b as f32 / 255.0`) is bit-exact against the
// GPU's. A gate built on it would pass on a board where GL declined
// every frame. Here a decline is a hard `Err` at the `convert` call.
//
// **Each asserts the route positively**, via `assert_pbo_source_route`:
// exactly one PBO source feed, no CPU upload, no zero-copy import. A
// hard error plus a byte comparison still leaves "the engine ran, but
// fed the source some other way"; the counter closes it.
//
// Nothing here needs `EDGEFIRST_FORCE_TRANSFER`. To run just these four:
//
// ```sh
// EDGEFIRST_TESTDATA_DIR=<repo>/testdata \
// cargo test -p edgefirst-image --lib -- --exact \
// opengl_headless::tests::gl_tests::a_pbo_view_source_converts_its_own_region_gl \
// opengl_headless::tests::gl_tests::a_pbo_view_source_converts_its_own_region_to_f32_gl \
// opengl_headless::tests::gl_tests::a_padded_pbo_source_does_not_shear_the_f32_upload \
// opengl_headless::tests::gl_tests::a_padded_pbo_destination_is_written_at_its_own_pitch
// ```
/// A GL processor that allocates PBOs, or `None` with a skip line.
/// Nothing about it is host-dependent beyond having GL at all.
///
/// The skip lines go through [`crate::test_support::report_skip`], which
/// writes to `std::io::stderr()` directly rather than through
/// `eprintln!`. `eprintln!` passes through libtest's per-test output
/// capture, which is discarded for a test that passes -- and a skip *is*
/// a pass -- so a board that skipped all four PBO gates read green in
/// the fleet log with no line saying so. The `SKIPPED:` prefix is
/// load-bearing: `scripts/on-target-test.sh` counts a board's skips by
/// grepping its log for that literal, and TESTING.md's "Reading the
/// results" section states it as the rule.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn pbo_gl_or_skip(what: &str) -> Option<GLProcessorThreaded> {
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{what} - OpenGL not available"));
return None;
}
match GLProcessorThreaded::new(None) {
Ok(gl) => Some(gl),
Err(e) => {
crate::test_support::report_skip(&format!(
"{what} - GL processor unavailable: {e}"
));
None
}
}
}
/// [`pbo_gl_or_skip`] plus the F32 render capability the float gates
/// need. Separate so the u8 gates do not inherit a skip they have no
/// reason to take. Same skip-reporting rule, same reason.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn float_pbo_gl_or_skip(what: &str) -> Option<GLProcessorThreaded> {
let gl = pbo_gl_or_skip(what)?;
if !gl.supported_render_dtypes().f32 {
crate::test_support::report_skip(&format!("{what} - F32 render not supported"));
return None;
}
Some(gl)
}
/// An RGBA8 PBO of the given size. Infallible on a host that has GL:
/// this allocates a GL buffer outright, with no DMA-BUF attempt to
/// decline.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn rgba8_pbo(gl: &GLProcessorThreaded, w: usize, h: usize) -> TensorDyn {
let t = gl
.create_pbo_image(w, h, PixelFormat::Rgba)
.expect("allocate an RGBA8 PBO on the GL thread");
assert_eq!(
TensorTrait::memory(&t),
TensorMemory::Pbo,
"create_pbo_image must produce a PBO"
);
t.into()
}
/// Assert the convert just performed fed its source from a PBO, exactly
/// once, and did not reach either of the other two feeds.
///
/// `ConvertStats` counts source feeds 1:1 with frames -- every convert
/// is exactly one of import / pbo / upload -- so this is a complete
/// statement about the route, not a lower bound on it.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn assert_pbo_source_route(
gl: &GLProcessorThreaded,
before: &crate::opengl_headless::cache::ConvertStats,
what: &str,
) {
let after = gl.convert_stats().expect("convert stats after");
assert_eq!(
after.src_pbo_uploads - before.src_pbo_uploads,
1,
"{what}: expected exactly one PBO source feed; the byte comparison \
below is meaningless if the engine took another route"
);
assert_eq!(
after.src_uploads - before.src_uploads,
0,
"{what}: the source was fed by CPU map + upload, not from its PBO"
);
assert_eq!(
after.src_imports - before.src_imports,
0,
"{what}: the source was fed by zero-copy import, not from its PBO"
);
}
/// Stamp `R = x % 256`, `G = y % 256`, `B = 128`, honouring the tensor's
/// own pitch. Plain index values rather than multiples: at 240 rows and
/// 320 columns a multiplier wraps, and two positions these tests compare
/// could then share a value.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn stamp_rgba8_positionally(t: &TensorDyn, w: usize, h: usize) {
let pitch = t.effective_row_stride().unwrap_or(w * 4);
let mut m = t
.map_bytes(edgefirst_tensor::CpuAccess::ReadWrite)
.expect("map the source PBO");
let s = m.as_mut_slice();
for y in 0..h {
for x in 0..w {
let i = y * pitch + x * 4;
s[i] = (x % 256) as u8;
s[i + 1] = (y % 256) as u8;
s[i + 2] = 128;
s[i + 3] = 255;
}
}
}
/// Assert an F32 RGB destination holds [`stamp_rgba8_positionally`]'s
/// pattern for the source window starting at `(x0, y0)`, read from the
/// live mapping. The crop is the identity and the sizes match, so there
/// is no resampling and the exact expectation is the source byte over
/// 255 -- the same reference `convert_f32_nhwc_pbo_roundtrip` uses.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn assert_f32_dst_matches_rgba8_pattern(
dst: &TensorDyn,
w: usize,
h: usize,
x0: usize,
y0: usize,
case: &str,
) {
let pitch_f32 = dst.effective_row_stride().unwrap_or(w * 3 * 4) / 4;
let m = dst.as_f32().unwrap().map().unwrap();
for y in 0..h {
for x in 0..w {
let expect = [
((x + x0) % 256) as f32 / 255.0,
((y + y0) % 256) as f32 / 255.0,
128.0 / 255.0,
];
for (c, &want) in expect.iter().enumerate() {
let got = m[y * pitch_f32 + x * 3 + c];
assert!(
(got - want).abs() < 1e-3,
"{case}: f32 dst[{y},{x},{c}]={got}, expected {want} \
(source pixel ({}, {})); the parent's origin would be \
({x}, {y})",
x + x0,
y + y0
);
}
}
}
}
/// A `view()` of a PBO-backed source converts its OWN sub-region.
///
/// The u8 engine feeds a PBO source by binding it to
/// `PIXEL_UNPACK_BUFFER` and letting `glTexImage2D` read from it. With a
/// buffer bound, that call's `pixels` argument is a byte OFFSET, and it
/// was `NULL` -- so every view of one buffer uploaded the parent's
/// top-left tile instead of the window it names. Silent: the right
/// shape, the right byte count, the wrong pixels. Issue #162's converter
/// half; the storage half (a view demoting to a host placeholder under
/// the `dynamic` backend) is pinned in
/// `tests/interop/test_cross_package.py`.
///
/// The origin is non-zero and the window is NARROWER than its parent, so
/// both halves of the addressing are exercised: a fix that got the
/// offset right but stepped rows by the window's own tight pitch reads
/// row 0 correctly and shears every row after it. QVGA-scale rather than
/// a toy size, because tiny textures have their own failure modes on
/// Mali that would confound this one.
///
/// Route, allocation and fallback: see the block comment above.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn a_pbo_view_source_converts_its_own_region_gl() {
const W: usize = 320;
const H: usize = 240;
const SIDE: usize = 96;
const X0: usize = 40;
const Y0: usize = 32;
let Some(mut gl) = pbo_gl_or_skip(function!()) else {
return;
};
let src = rgba8_pbo(&gl, W, H);
stamp_rgba8_positionally(&src, W, H);
let view = src
.view(edgefirst_tensor::Region::new(X0, Y0, SIDE, SIDE))
.expect("view a narrow window of the PBO");
let mut dst = rgba8_pbo(&gl, SIDE, SIDE);
let before = gl.convert_stats().expect("convert stats before");
gl.convert(&view, &mut dst, None)
.expect("GL declined a PBO view source");
assert_pbo_source_route(&gl, &before, "u8 PBO view");
// Read from the live mapping, inside the guard.
let m = dst
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map the destination");
let out = m.as_slice();
let dst_pitch = dst.effective_row_stride().unwrap_or(SIDE * 4);
for y in 0..SIDE {
for x in 0..SIDE {
let i = y * dst_pitch + x * 4;
assert_eq!(
(out[i], out[i + 1]),
(((x + X0) % 256) as u8, ((y + Y0) % 256) as u8),
"output pixel ({x}, {y}) must be source ({}, {}); \
({x}, {y}) would be the parent's origin tile",
x + X0,
y + Y0
);
}
}
}
/// The float engine's PBO source arm reads the view's own region.
///
/// `feed_float_src`'s PBO arm was the float sibling of the u8 engine's
/// PBO upload, and it carried the identical pair of
/// defects: `TexImage2D`/`TexSubImage2D` were handed `NULL` with the
/// source bound to `PIXEL_UNPACK_BUFFER`, and no `UNPACK_ROW_LENGTH` was
/// set. The arm is taken on any `pbo_id()`, and a `view()` carries its
/// parent's id, so `convert(pbo_view, f32_dst)` uploaded the parent's
/// top-left tile.
///
/// Route, allocation and fallback: see the block comment above. The
/// route assertion is what makes this test about the float GL path
/// rather than about arithmetic: the CPU fallback's widen is bit-exact
/// against the GPU's, so byte agreement alone would prove nothing.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn a_pbo_view_source_converts_its_own_region_to_f32_gl() {
const W: usize = 320;
const H: usize = 240;
const SIDE: usize = 96;
const X0: usize = 40;
const Y0: usize = 32;
let Some(mut gl) = float_pbo_gl_or_skip(function!()) else {
return;
};
let src = rgba8_pbo(&gl, W, H);
stamp_rgba8_positionally(&src, W, H);
let view = src
.view(edgefirst_tensor::Region::new(X0, Y0, SIDE, SIDE))
.expect("view a narrow window of the PBO");
let mut dst = gl
.create_pbo_image_dtype(SIDE, SIDE, PixelFormat::Rgb, DType::F32)
.expect("allocate an F32 RGB PBO destination");
let before = gl.convert_stats().expect("convert stats before");
gl.convert(&view, &mut dst, None)
.expect("GL declined a PBO view source into an F32 destination");
assert_pbo_source_route(&gl, &before, "float PBO view");
assert_f32_dst_matches_rgba8_pattern(&dst, SIDE, SIDE, X0, Y0, "view at (40, 32)");
}
/// A padded source pitch must not shear the float engine's upload.
///
/// The other half of `feed_float_src`'s PBO arm: with no
/// `UNPACK_ROW_LENGTH`, GL reads the rows back to back and every row
/// after the first lands on the wrong columns. Isolated from the offset
/// deliberately -- this source starts at byte 0 -- so the two defects
/// fail this suite independently rather than as one lump.
///
/// The padded pitch comes from viewing a WIDER parent at `(0, 0)`:
/// `Tensor::view` records the parent's pitch on any multi-row window,
/// which is exactly the "rows are further apart than the image is wide"
/// shape a pitch-aligned producer hands over, and the only way to build
/// one here without lying to `set_row_stride` about a buffer.
///
/// Route, allocation and fallback: see the block comment above.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn a_padded_pbo_source_does_not_shear_the_f32_upload() {
const W_ALLOC: usize = 320;
const W: usize = 256;
const H: usize = 240;
let Some(mut gl) = float_pbo_gl_or_skip(function!()) else {
return;
};
let src = rgba8_pbo(&gl, W_ALLOC, H);
stamp_rgba8_positionally(&src, W_ALLOC, H);
let view = src
.view(edgefirst_tensor::Region::new(0, 0, W, H))
.expect("view the left W columns of a wider PBO");
assert_eq!(
view.effective_row_stride(),
Some(W_ALLOC * 4),
"precondition: the window's rows are the PARENT's pitch apart, not \
its own {} bytes",
W * 4
);
assert_eq!(
view.plane_offset().unwrap_or(0),
0,
"precondition: this case starts at byte 0, so only the pitch is \
under test"
);
let mut dst = gl
.create_pbo_image_dtype(W, H, PixelFormat::Rgb, DType::F32)
.expect("allocate an F32 RGB PBO destination");
let before = gl.convert_stats().expect("convert stats before");
gl.convert(&view, &mut dst, None)
.expect("GL declined a padded PBO source into an F32 destination");
assert_pbo_source_route(&gl, &before, "float padded PBO source");
assert_f32_dst_matches_rgba8_pattern(&dst, W, H, 0, 0, "padded pitch");
}
/// A padded whole-buffer PBO destination is written at its own pitch.
///
/// The destination half of the family. `plan_pbo_readback` accepts a
/// pitch-aligned destination -- that is what `pack_row_length` exists
/// for -- so both directions have to honour it:
/// `setup_renderbuffer_from_pbo` seeds the render texture from the
/// destination's current bytes on the way in, and the readback places
/// the rendered rows on the way out.
///
/// **What this pins, and what nothing can.** It pins the readback, which
/// is observable: get the pitch wrong there and the visible rows land on
/// top of each other. It does NOT pin the seed's own
/// `UNPACK_ROW_LENGTH`, and no test can, because no path lets the seeded
/// content survive to be read: `Crop::resolve` only ever produces a
/// `dst_rect` together with a `dst_color` (`Fit::Letterbox`), so a
/// partial convert always clears first, `Fit::Stretch` covers the whole
/// destination, and `draw_decoded_masks`/`draw_proto_masks` guarantee
/// they fully write `dst`. The seed is fixed anyway -- an upload should
/// describe the buffer it reads -- and this test is what keeps the
/// destination pitch honest end to end.
///
/// There is no destination-side counter in `ConvertStats`, so the route
/// is pinned from the source side plus a structural fact: the source
/// feed is asserted to be the PBO arm, and `lower_dst` maps a `Pbo`
/// destination to `TexturePbo` unconditionally (pinned by
/// `lower_dst_full_table`), so once the engine ran the destination went
/// through the PBO readback.
///
/// The padded destination is built the way a pool really produces one:
/// allocate at the wider width, then `configure_image` down and declare
/// the pitch the allocation still has. Nothing here lies to
/// `set_row_stride` -- 240 rows at 1280 B fit the 307200 B the 320-wide
/// allocation holds. `create_pbo_image` itself never pads: every width
/// comes back tight, so a pool is the only way a padded one arises.
///
/// Route, allocation and fallback: see the block comment above.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn a_padded_pbo_destination_is_written_at_its_own_pitch() {
const W_ALLOC: usize = 320;
const W: usize = 256;
const H: usize = 240;
const PITCH: usize = W_ALLOC * 4;
let Some(mut gl) = pbo_gl_or_skip(function!()) else {
return;
};
let src = rgba8_pbo(&gl, W, H);
stamp_rgba8_positionally(&src, W, H);
let mut dst = rgba8_pbo(&gl, W_ALLOC, H);
dst.configure_image(W, H, PixelFormat::Rgba)
.expect("narrow a pool tensor to the image it will hold");
dst.set_row_stride(PITCH)
.expect("declare the pitch the allocation still has");
assert_eq!(
dst.effective_row_stride(),
Some(PITCH),
"precondition: the destination's rows are {PITCH} B apart, not its \
own {} B",
W * 4
);
let before = gl.convert_stats().expect("convert stats before");
gl.convert(&src, &mut dst, None)
.expect("GL declined a pitch-aligned PBO destination");
assert_pbo_source_route(&gl, &before, "padded PBO destination");
// Read from the live mapping, inside the guard. Only the visible
// bytes of each row are checked: a driver may write the padding
// between rows while packing (Vivante does, issue #167).
let m = dst
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map the destination");
let out = m.as_slice();
for y in 0..H {
for x in 0..W {
let i = y * PITCH + x * 4;
assert_eq!(
(out[i], out[i + 1]),
((x % 256) as u8, (y % 256) as u8),
"dst pixel ({x}, {y}) at pitch {PITCH}; reading the rows back \
to back would put source row {} here",
y * PITCH / (W * 4)
);
}
}
}
/// Issue #177: a `view()` destination lowered to the **mapped-texture
/// readback** must receive exactly the pixels a whole destination of the
/// same size receives on the same path, at the parent's pitch, with
/// nothing outside the view touched.
///
/// The mapped path renders into an offscreen texture that IS the tile —
/// its origin is (0, 0), not the view's origin in the parent — so the
/// band `glViewport`/`glScissor` that places a tile inside a shared
/// zero-copy parent import must NOT be applied here. The placement
/// happens afterwards, in the readback, which writes through the view's
/// own `map()` at the parent's pitch.
///
/// The path is reached the way production reaches it: the destination
/// import FAILS and the convert lowers instead of ending. The hook
/// (`set_fail_dst_import`) injects that failure at the import itself,
/// because a driver that accepts every destination never produces one —
/// a fresh `view()` collapses its import base to 0, so `dst_import_places`
/// sees an aligned base and keeps the zero-copy route. The route is
/// asserted with `dst_import_fallbacks`, so the test cannot pass by
/// quietly taking the zero-copy import it means to avoid.
///
/// The oracle is the SAME convert into a whole destination on the SAME
/// mapped path, so a difference isolates the view-ness of the
/// destination rather than the readback path itself.
#[test]
fn mapped_texture_readback_places_a_view_destination() {
const PARENT_W: usize = 512;
const PARENT_H: usize = 320;
const VIEW_W: usize = 320;
const VIEW_H: usize = 240;
const BPP: usize = 4;
const POISON: u8 = 0xAB;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
#[cfg(target_os = "macos")]
if std::env::var_os("HAL_TEST_ALLOW_DLOPEN_ANGLE").is_none() {
crate::test_support::report_skip(&format!(
"{} - ANGLE dlopen gate closed (coverage pass 1)",
function!()
));
return;
}
let dma_rgba = |w: usize, h: usize| {
TensorDyn::image(
w,
h,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
)
};
// Distinct per-row and per-column values so a tile that lands at the
// wrong origin, or a row that lands at the wrong pitch, cannot
// coincidentally match.
let src = TensorDyn::image(
VIEW_W,
VIEW_H,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("source");
{
let stride = src.effective_row_stride().expect("source stride");
let mut m = src
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map source");
let b = m.as_mut_slice();
for y in 0..VIEW_H {
for x in 0..VIEW_W {
let i = y * stride + x * BPP;
b[i] = ((y * 3) % 256) as u8;
b[i + 1] = ((x * 5) % 256) as u8;
b[i + 2] = 255;
b[i + 3] = 255;
}
}
}
// A DIFFERENT image, converted into a whole destination immediately
// before each subject: the mapped path renders into a REUSED offscreen
// texture, so any tile pixel the subject fails to redraw shows this
// decoy instead of silently matching the oracle that ran before it.
let decoy = TensorDyn::image(
VIEW_W,
VIEW_H,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("decoy source");
{
let mut m = decoy
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map decoy");
for px in m.as_mut_slice().as_chunks_mut::<BPP>().0 {
px.copy_from_slice(&[7, 11, 13, 255]);
}
}
let mut gl = GLProcessorThreaded::new(None).expect("GL processor");
// CALIBRATION, with the hook OFF: a whole zero-copy destination says
// whether this host imports destinations at all. A host that imports
// none cannot run the subject either -- the engine declines a `view()`
// destination outright unless the transfer backend is zero-copy -- so
// it skips, which is what a desktop whose EGL cannot import a DMA-BUF
// does. Same self-calibration as
// `a_fresh_unaligned_view_destination_keeps_the_zero_copy_import`.
let imports = |g: &GLProcessorThreaded| {
let c = g.egl_cache_stats().expect("cache stats").dst;
c.misses + c.hits
};
let Some(mut oracle) = crate::test_support::gpu_buffer_allocated(
dma_rgba(VIEW_W, VIEW_H),
"zero-copy RGBA oracle",
) else {
return;
};
let before = imports(&gl);
gl.convert(&src, &mut oracle, None)
.expect("calibration convert into a whole zero-copy destination");
if imports(&gl) - before == 0 {
crate::test_support::report_skip(&format!(
"{} - no zero-copy destination import on this host, so a view() \
destination is declined by the engine and the mapped path cannot \
be reached for one",
function!()
));
return;
}
gl.set_fail_dst_import(true)
.expect("make the destination import fail");
let fallbacks = |g: &GLProcessorThreaded| {
g.convert_stats()
.expect("convert stats")
.dst_import_fallbacks
};
// The letterbox case carries the `glClear` the band scissor used to
// confine, so the two crops together cover both halves of the render.
let mut failures = Vec::new();
for (label, crop) in [
("stretch", Crop::default()),
(
"letterbox",
Crop::letterbox([114, 114, 114, 255]).with_source(Some(
edgefirst_tensor::Region::new(0, 0, VIEW_W, VIEW_H / 2),
)),
),
] {
// ORACLE: the same convert into the same WHOLE destination, on the same
// mapped-texture path. Comparing the view against this isolates the
// view-ness of the destination from the readback path itself.
gl.convert(
&src,
&mut oracle,
Some(crate::ConvertOptions::new().crop(crop)),
)
.expect("oracle convert into a whole destination on the mapped path");
let oracle_stride = oracle.effective_row_stride().expect("oracle stride");
let oracle_bytes = oracle
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map oracle")
.as_slice()
.to_vec();
for (x0, y0) in [(0usize, 0usize), (8, 8), (64, 32)] {
let parent = dma_rgba(PARENT_W, PARENT_H).expect("parent");
assert_eq!(
parent.memory(),
TensorMemory::DmaBuf,
"the parent must be the zero-copy backing under test"
);
let pitch = parent.effective_row_stride().expect("parent pitch");
{
let mut m = parent
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map parent");
m.as_mut_slice().fill(POISON);
}
let mut scratch = dma_rgba(VIEW_W, VIEW_H).expect("decoy destination");
gl.convert(&decoy, &mut scratch, None)
.expect("decoy convert");
let before = fallbacks(&gl);
{
let mut view = parent
.view(edgefirst_tensor::Region::new(x0, y0, VIEW_W, VIEW_H))
.expect("destination view");
if let Err(e) = gl.convert(
&src,
&mut view,
Some(crate::ConvertOptions::new().crop(crop)),
) {
failures.push(format!("{label} ({x0},{y0}): GL declined the view: {e}"));
continue;
}
}
// The route, not just the pixels: without this the test would
// still pass if the convert quietly took the zero-copy import
// it exists to bypass.
let took = fallbacks(&gl) - before;
if took != 1 {
failures.push(format!(
"{label} ({x0},{y0}): expected exactly one destination-import \
fallback for this convert, saw {took}"
));
}
let out = parent
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map parent")
.as_slice()
.to_vec();
let mut wrong = 0usize;
let mut first: Option<(usize, usize, Vec<u8>, Vec<u8>)> = None;
// Bounding box of the wrong pixels, and whether every one of them
// lies in the band a view-origin `glScissor` on an origin-(0,0)
// render target would have clipped away.
let (mut lx, mut ly, mut hx, mut hy) = (usize::MAX, usize::MAX, 0usize, 0usize);
let mut all_in_scissor_band = true;
for y in 0..VIEW_H {
for x in 0..VIEW_W {
let got = &out[(y0 + y) * pitch + (x0 + x) * BPP..][..BPP];
let want = &oracle_bytes[y * oracle_stride + x * BPP..][..BPP];
if got != want {
wrong += 1;
first.get_or_insert((x, y, got.to_vec(), want.to_vec()));
lx = lx.min(x);
ly = ly.min(y);
hx = hx.max(x);
hy = hy.max(y);
all_in_scissor_band &= x < x0 || y < y0;
}
}
}
if let Some((x, y, got, want)) = first {
failures.push(format!(
"{label} ({x0},{y0}) pitch {pitch}: {wrong}/{} tile pixels differ from the \
whole-destination oracle; first at tile ({x},{y}) got={got:?} \
want={want:?}; wrong-pixel bbox x[{lx}..={hx}] y[{ly}..={hy}]; \
every wrong pixel inside the x<{x0}||y<{y0} band: {all_in_scissor_band}",
VIEW_W * VIEW_H,
));
}
// Nothing outside the view region moved.
let mut outside = 0usize;
let mut first_outside = None;
for y in 0..PARENT_H {
for x in 0..PARENT_W {
if y >= y0 && y < y0 + VIEW_H && x >= x0 && x < x0 + VIEW_W {
continue;
}
let i = y * pitch + x * BPP;
if out[i..i + BPP] != [POISON; BPP] {
outside += 1;
first_outside.get_or_insert((x, y, out[i..i + BPP].to_vec()));
}
}
}
if let Some((x, y, got)) = first_outside {
failures.push(format!(
"{label} ({x0},{y0}): {outside} parent pixels OUTSIDE the view were \
overwritten; first at ({x},{y}) = {got:?}"
));
}
}
}
// A packed-RGB (or planar) view destination has no placement on EITHER
// route: the zero-copy band is a `glViewport` in destination pixels
// that the `W*3/4` packed surface does not have, and this readback
// writes `dst_w`-wide rows at the parent's pitch. So it must be refused
// however the destination import went. The hook makes the packed-RGB
// plan's import fail, which is the case that used to slip through --
// the refusal was keyed on the lowering, and a refused import re-plans
// onto the mapped route, flipping the very term the guard read.
// Asserted with the counter too: the refusal must come BEFORE the
// engine spends an import on a destination it is going to decline.
#[cfg(target_os = "linux")]
if let Some(rgb_parent) = crate::test_support::dma_allocated(
TensorDyn::image(
PARENT_W,
PARENT_H,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
),
"packed-RGB DMA parent",
) {
let rgb_src = TensorDyn::image(
VIEW_W,
VIEW_H,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("packed-RGB source");
let mut view = rgb_parent
.view(edgefirst_tensor::Region::new(8, 8, VIEW_W, VIEW_H))
.expect("packed-RGB destination view");
let before = fallbacks(&gl);
let outcome = gl.convert(&rgb_src, &mut view, None);
match outcome {
Err(crate::Error::NotSupported(_)) => {}
other => failures.push(format!(
"a packed-RGB view() destination must be declined on every \
destination route, got {other:?}"
)),
}
let spent = fallbacks(&gl) - before;
if spent != 0 {
failures.push(format!(
"a packed-RGB view() destination was declined only after \
spending {spent} destination import(s) on it"
));
}
}
// A WHOLE packed-RGB destination whose import is refused re-plans onto
// the mapped route, and must spend exactly ONE destination import
// doing so. The re-plan happens in `convert_via_engine`, before pass 1
// renders; `bind_dst` then has to BIND what was re-planned. Re-deriving
// the lowering there instead answers "zero-copy" (the import failed,
// the placement is fine), binds a zero-copy destination under a plan
// chosen for a texture one, and self-corrects only because the second
// import fails too -- at the cost of a wasted import, a second tick
// here, and an engine span whose `lowering` field says the opposite of
// what happened.
#[cfg(target_os = "linux")]
if let Some(mut rgb_dst) = crate::test_support::dma_allocated(
TensorDyn::image(
VIEW_W,
VIEW_H,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
),
"packed-RGB DMA destination",
) {
let rgb_src = TensorDyn::image(
VIEW_W,
VIEW_H,
PixelFormat::Rgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("packed-RGB source");
{
let mut m = rgb_src
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map packed-RGB source");
m.as_mut_slice().fill(0x5A);
}
let before = fallbacks(&gl);
match gl.convert(&rgb_src, &mut rgb_dst, None) {
Ok(()) => {
let spent = fallbacks(&gl) - before;
if spent != 1 {
failures.push(format!(
"a refused packed-RGB destination import must re-plan \
after exactly one attempt, spent {spent}"
));
}
let out = rgb_dst
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map packed-RGB destination")
.as_slice()
.to_vec();
if out.iter().all(|&b| b == 0) {
failures
.push("the re-planned packed-RGB convert wrote nothing".to_string());
}
}
Err(e) => failures.push(format!(
"a refused packed-RGB destination import must re-plan onto the \
mapped route, not end the convert: {e}"
)),
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// A refused destination import must re-plan, not just re-bind.
///
/// A non-NV source into a `PlanarRgb` destination is planned `SinglePass`
/// against the zero-copy lowering. When the import is then refused,
/// `bind_dst` falls back to the mapped-texture readback -- but the plan was
/// chosen for a lowering that no longer holds, and the single-pass planar
/// shader (`convert_to_planar`) imports its source UNCONDITIONALLY. A heap
/// source therefore failed there and the whole convert fell out to the CPU
/// backend, throwing away the fallback that had just been set up for it.
/// `plan_convert` calls that pair impossible; the engine has to re-plan
/// against what `bind_dst` actually bound.
///
/// Both triggers are exercised: the hook, which reaches the case on any
/// host with a zero-copy destination import, and a real driver refusal at
/// an unaligned plane offset, which is what Vivante does on i.MX 8M Plus.
#[test]
fn a_refused_planar_destination_import_replans_onto_the_mapped_route() {
const W: usize = 320;
const H: usize = 240;
if !is_opengl_available() {
crate::test_support::report_skip(&format!("{} - OpenGL not available", function!()));
return;
}
let src = TensorDyn::image(
W,
H,
PixelFormat::Rgba,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("host source");
{
let mut m = src
.map_bytes(edgefirst_tensor::CpuAccess::Write)
.expect("map source");
for (i, px) in m
.as_mut_slice()
.as_chunks_mut::<4>()
.0
.iter_mut()
.enumerate()
{
px.copy_from_slice(&[(i % 251) as u8, (i % 199) as u8, (i % 157) as u8, 255]);
}
}
// The oracle: the same convert on the CPU backend.
let mut reference = TensorDyn::image(
W,
H,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::Mem),
edgefirst_tensor::CpuAccess::ReadWrite,
)
.expect("reference destination");
crate::CPUProcessor::new()
.convert(&src, &mut reference, None)
.expect("CPU reference convert");
let want = reference
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map reference")
.as_slice()
.to_vec();
// Adreno's and V3D's upload-and-readback route samples the
// neighbouring texel in bands, so this sawtooth comes back up to 4
// levels off. The re-plan is what is under test. The renderer is read
// while the probe processor's context is current.
let tolerance: u8 = crate::opengl_headless::processor::GLProcessorST::new(None, None)
.map(|g| {
let v3d = edgefirst_gl::get_string(edgefirst_gl::gl::RENDERER)
.is_ok_and(|r| r.contains("V3D"));
if g.is_adreno || v3d {
4
} else {
0
}
})
.unwrap_or(0);
let mut gl = GLProcessorThreaded::new(None).expect("GL processor");
let planar_dma = || {
let image = TensorDyn::image(
W,
H,
PixelFormat::PlanarRgb,
DType::U8,
Some(TensorMemory::DmaBuf),
edgefirst_tensor::CpuAccess::ReadWrite,
);
if cfg!(target_os = "linux") {
crate::test_support::dma_allocated(image, "PlanarRgb DMA destination")
} else {
crate::test_support::allocated(
image,
"PlanarRgb DMA destination",
crate::test_support::Expect::MayFail(
"PlanarRgb u8 has no zero-copy image layout on this platform",
),
)
}
};
let Some(mut dst) = planar_dma() else {
return;
};
let mut failures: Vec<String> = Vec::new();
let measure = |gl: &mut GLProcessorThreaded,
label: &str,
dst: &mut TensorDyn,
failures: &mut Vec<String>|
-> u64 {
let before = gl
.convert_stats()
.expect("convert stats")
.dst_import_fallbacks;
let outcome = gl.convert(&src, dst, None);
let spent = gl
.convert_stats()
.expect("convert stats")
.dst_import_fallbacks
- before;
match outcome {
Ok(()) if spent > 0 => {
if spent != 1 {
failures.push(format!(
"{label}: expected exactly one destination-import fallback, \
saw {spent}"
));
}
let got = dst
.map_bytes(edgefirst_tensor::CpuAccess::Read)
.expect("map destination")
.as_slice()
.to_vec();
let off = |(a, b): (&u8, &u8)| a.abs_diff(*b) > tolerance;
if got.len() != want.len() || got.iter().zip(want.iter()).any(off) {
let first = got.iter().zip(want.iter()).position(off).unwrap_or(0);
failures.push(format!(
"{label}: the re-planned convert does not match the CPU \
reference; first differing byte {first} got={} want={}",
got[first], want[first]
));
}
}
Ok(()) => {}
Err(e) => failures.push(format!(
"{label}: a refused planar destination import must complete through the \
mapped-texture route, not end the convert ({spent} fallback(s) spent): {e}"
)),
}
spent
};
// TRIGGER 1 -- the hook, so the case is reachable on any host whose
// driver accepts every destination.
gl.set_fail_dst_import(true).expect("arm the hook");
let hooked = measure(&mut gl, "hooked refusal", &mut dst, &mut failures);
gl.set_fail_dst_import(false).expect("disarm the hook");
if hooked == 0 {
crate::test_support::report_skip(&format!(
"{} - no zero-copy destination import is attempted on this host",
function!()
));
return;
}
// TRIGGER 2 -- a real driver refusal: a plane offset that is not
// 64-byte aligned, which Vivante answers with `EGL_BAD_ACCESS`. Where
// the driver accepts it there is no refusal and nothing to assert, so
// the arm reports what it saw and stays silent.
if let Some(mut offset_dst) = planar_dma() {
offset_dst.set_plane_offset(32);
let real = measure(
&mut gl,
"driver refusal at offset 32",
&mut offset_dst,
&mut failures,
);
if real == 0 {
// Mali and V3D import an unaligned destination happily, so
// there is no refusal here and this arm asserted nothing. Said
// out loud, because a silent no-op arm is how a lane stops
// covering the production trigger without anyone noticing.
crate::test_support::report_skip(&format!(
"{} - this driver accepts an unaligned PlanarRgb destination, so the \
real-refusal arm had nothing to measure (the hooked arm still ran)",
function!()
));
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// Stamp a smooth YUYV or NV12 frame into `t` at its own pitch: luma
/// ramps with x and y, Cb with x, Cr with y. Smooth so that the GPU's
/// nearest chroma pair and the CPU converter's chroma upsampling cannot
/// differ by more than a code value or two, and inside the limited-range
/// band so neither side clips.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn stamp_yuv_gradient(t: &TensorDyn, fmt: PixelFormat, w: usize, h: usize) {
let luma = |x: usize, y: usize| (16 + x * 180 / w + y * 40 / h) as u8;
let cb = |x: usize| (64 + x * 128 / w) as u8;
let cr = |y: usize| (64 + y * 128 / h) as u8;
let mut m = t
.map_bytes(edgefirst_tensor::CpuAccess::ReadWrite)
.expect("map the source");
let s = m.as_mut_slice();
match fmt {
PixelFormat::Yuyv => {
let pitch = t.effective_row_stride().unwrap_or(w * 2);
for y in 0..h {
for x in (0..w).step_by(2) {
let i = y * pitch + x * 2;
s[i] = luma(x, y);
s[i + 1] = cb(x);
s[i + 2] = luma(x + 1, y);
s[i + 3] = cr(y);
}
}
}
PixelFormat::Nv12 => {
let pitch = t.effective_row_stride().unwrap_or(w);
for y in 0..h {
for x in 0..w {
s[y * pitch + x] = luma(x, y);
}
}
let uv = h * pitch;
for y in 0..h / 2 {
for x in (0..w).step_by(2) {
s[uv + y * pitch + x] = cb(x);
s[uv + y * pitch + x + 1] = cr(y * 2);
}
}
}
other => panic!("stamp_yuv_gradient: {other:?} is not YUYV or NV12"),
}
}
/// Largest per-byte difference between two images of one format, read at
/// each tensor's own pitch; int8 bytes compare as signed values. Returns
/// the difference and the first (x, row, byte) past `tolerance`.
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn image_max_diff(
a: &TensorDyn,
b: &TensorDyn,
tolerance: u32,
) -> (u32, Option<(usize, usize, usize)>) {
let fmt = a.format().expect("a formatted image");
let (w, h) = (a.width().unwrap(), a.height().unwrap());
let planar = fmt.layout() == edgefirst_tensor::PixelLayout::Planar;
let (rows, row_bytes) = if planar {
(h * fmt.channels(), w)
} else {
(h, w * fmt.channels())
};
let signed = a.dtype() == DType::I8;
let am = a.map_bytes(edgefirst_tensor::CpuAccess::Read).unwrap();
let bm = b.map_bytes(edgefirst_tensor::CpuAccess::Read).unwrap();
let (ap, bp) = (
a.effective_row_stride().unwrap_or(row_bytes),
b.effective_row_stride().unwrap_or(row_bytes),
);
let (mut worst, mut first) = (0u32, None);
for r in 0..rows {
for c in 0..row_bytes {
let (x, y) = (am.as_slice()[r * ap + c], bm.as_slice()[r * bp + c]);
let d = if signed {
(x as i8 as i32 - y as i8 as i32).unsigned_abs()
} else {
(x as i32 - y as i32).unsigned_abs()
};
worst = worst.max(d);
if d > tolerance && first.is_none() {
first = Some((c, r, d as usize));
}
}
}
(worst, first)
}
/// A planar convert after a packed-RGB one on the same processor writes
/// every plane. The packed-RGB pass 2 samples the shared intermediate on
/// texture unit 1; left bound there, Vivante applied the planar pass 2's
/// per-plane swizzle to the first plane only.
#[test]
#[cfg(target_os = "linux")]
fn a_planar_convert_after_a_packed_rgb_one_writes_every_plane() {
use crate::cpu::CPUProcessor;
let Some(mut gl) = pbo_gl_or_skip(function!()) else {
return;
};
if !crate::test_support::is_dma_available() {
crate::test_support::report_skip(&format!("{} - no DMA heap", function!()));
return;
}
let (w, h) = (320usize, 240usize);
let access = edgefirst_tensor::CpuAccess::ReadWrite;
let mut src = TensorDyn::image(
w,
h,
PixelFormat::Nv12,
DType::U8,
Some(TensorMemory::Mem),
access,
)
.unwrap();
stamp_yuv_gradient(&src, PixelFormat::Nv12, w, h);
src.set_colorimetry(Some(
edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full),
));
let image = |fmt, mem| TensorDyn::image(w, h, fmt, DType::U8, Some(mem), access).unwrap();
let mut want = image(PixelFormat::PlanarRgb, TensorMemory::Mem);
CPUProcessor::new().convert(&src, &mut want, None).unwrap();
for dst_fmt in [PixelFormat::Rgb, PixelFormat::PlanarRgb] {
let mut got = image(dst_fmt, TensorMemory::DmaBuf);
gl.convert(&src, &mut got, None)
.unwrap_or_else(|e| panic!("{dst_fmt:?}: {e}"));
if dst_fmt == PixelFormat::PlanarRgb {
let (worst, first) = image_max_diff(&got, &want, 4);
assert!(
first.is_none(),
"planar after packed RGB differs from the CPU by up to {worst} at {first:?} \
(byte, row, diff; rows {h}.. are the second plane)"
);
}
}
}
/// YUYV and NV12 sources reach the GPU whether they live in a PBO or in
/// host memory, on every destination route, and agree with the CPU
/// converter -- where the platform has no zero-copy import. Where it
/// does, YUYV from either and NV12 from a PBO are declined to the CPU,
/// which beats the upload there.
///
/// A PBO is the only GPU-visible source where DMA-BUF import is
/// unavailable -- every frame on a Jetson -- and these are the formats
/// cameras deliver. The
/// destinations cover each route a source can take: single-pass packed
/// (Rgba), single-pass genuine RGB or the two-pass packed-RGB route
/// (Rgb, by destination memory), the planar two-pass route (PlanarRgb),
/// and the int8 twin of each. A DMA-BUF destination, where the host has
/// one, is the case that must plan a PBO source as a host source: the
/// single-pass planar shader can only import its source.
///
/// The feed counters make this a statement about the GPU path: a convert
/// that fell back to the CPU would match the reference exactly.
#[test]
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn yuv_sources_from_pbo_and_host_memory_match_cpu() {
use crate::cpu::CPUProcessor;
let Some(mut gl) = pbo_gl_or_skip(function!()) else {
return;
};
let (w, h) = (320usize, 240usize);
// Tagged on both sides, so the comparison isolates the route rather
// than the untagged-colorimetry heuristic.
let cm = edgefirst_tensor::Colorimetry::default()
.with_encoding(edgefirst_tensor::ColorEncoding::Bt601)
.with_range(edgefirst_tensor::ColorRange::Full);
let dsts = [
(PixelFormat::Rgba, DType::U8),
(PixelFormat::Rgb, DType::U8),
(PixelFormat::PlanarRgb, DType::U8),
(PixelFormat::Rgba, DType::I8),
(PixelFormat::Rgb, DType::I8),
(PixelFormat::PlanarRgb, DType::I8),
];
#[allow(unused_mut)]
let mut dst_mems = vec![TensorMemory::Mem];
#[cfg(target_os = "linux")]
if crate::test_support::is_dma_available() {
dst_mems.push(TensorMemory::DmaBuf);
}
let access = edgefirst_tensor::CpuAccess::ReadWrite;
let uploads_yuv = !gl.transfer_backend().is_zero_copy();
let mut cpu = CPUProcessor::new();
let mut failures = Vec::new();
let mut checked = 0;
for src_fmt in [PixelFormat::Yuyv, PixelFormat::Nv12] {
let mut reference =
TensorDyn::image(w, h, src_fmt, DType::U8, Some(TensorMemory::Mem), access)
.expect("host reference source");
stamp_yuv_gradient(&reference, src_fmt, w, h);
reference.set_colorimetry(Some(cm));
for src_mem in [TensorMemory::Pbo, TensorMemory::Mem] {
let mut src: TensorDyn = if src_mem == TensorMemory::Pbo {
gl.create_pbo_image(w, h, src_fmt)
.expect("allocate the source PBO")
.into()
} else {
TensorDyn::image(w, h, src_fmt, DType::U8, Some(src_mem), access)
.expect("host source")
};
assert_eq!(src.memory(), src_mem);
stamp_yuv_gradient(&src, src_fmt, w, h);
src.set_colorimetry(Some(cm));
for &dst_mem in &dst_mems {
for (dst_fmt, dtype) in dsts {
let case =
format!("{src_fmt:?}/{src_mem:?} -> {dst_fmt:?} {dtype:?}/{dst_mem:?}");
let mut want =
TensorDyn::image(w, h, dst_fmt, dtype, Some(TensorMemory::Mem), access)
.unwrap();
cpu.convert(&reference, &mut want, None)
.unwrap_or_else(|e| panic!("{case}: CPU reference: {e}"));
let mut got = TensorDyn::image(w, h, dst_fmt, dtype, Some(dst_mem), access)
.unwrap_or_else(|e| panic!("{case}: destination: {e}"));
let before = gl.convert_stats().expect("convert stats before");
let result = gl.convert(&src, &mut got, None);
let declined = !uploads_yuv
&& (src_fmt == PixelFormat::Yuyv || src_mem == TensorMemory::Pbo);
if declined {
if !matches!(result, Err(crate::Error::NotSupported(_))) {
failures.push(format!(
"{case}: expected a NotSupported decline on a zero-copy \
platform, got {result:?}"
));
}
checked += 1;
continue;
}
if let Err(e) = result {
failures.push(format!("{case}: GL refused: {e}"));
continue;
}
let after = gl.convert_stats().expect("convert stats after");
let (pbo, upload, import) = (
after.src_pbo_uploads - before.src_pbo_uploads,
after.src_uploads - before.src_uploads,
after.src_imports - before.src_imports,
);
let fed = match src_mem {
TensorMemory::Pbo => pbo >= 1 && upload == 0,
_ => upload >= 1 && pbo == 0,
};
if !fed || import != 0 {
failures.push(format!(
"{case}: source fed {pbo} time(s) from the PBO, {upload} by \
map + upload, {import} by import"
));
continue;
}
let (worst, first) = image_max_diff(&got, &want, 4);
if let Some((c, r, d)) = first {
failures.push(format!(
"{case}: byte {c} of row {r} differs from the CPU by {d} \
(worst {worst}, tolerance 4)"
));
}
checked += 1;
}
}
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
assert_eq!(checked, 2 * 2 * dst_mems.len() * dsts.len());
}
}